Test Failed
Branch develop (86e751)
by Laurent
34:11
created
htdocs/core/modules/societe/modules_societe.class.php 4 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
     /**
112 112
      *  Return next value available
113 113
      *
114
-     *	@param	Societe		$objsoc		Object thirdparty
114
+     *	@param	integer		$objsoc		Object thirdparty
115 115
      *	@param	int			$type		Type
116 116
      *  @return string      			Value
117 117
      */
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
     /**		Return an example of result returned by getNextValue
273 273
      *
274 274
      *      @param	Translate	$langs		Object langs
275
-     *      @param	societe		$objsoc		Object thirdparty
275
+     *      @param	integer		$objsoc		Object thirdparty
276 276
      *      @param	int			$type		Type of third party (1:customer, 2:supplier, -1:autodetect)
277 277
      *      @return	string					Example
278 278
      */
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
  *  Create a document onto disk according to template module.
368 368
  *
369 369
  *	@param	DoliDB		$db  			Database handler
370
- *	@param  Facture		$object			Object invoice
370
+ *	@param  Societe		$object			Object invoice
371 371
  *  @param  string      $message        Message (not used, deprecated)
372 372
  *	@param	string		$modele			Force template to use ('' to not force)
373 373
  *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
Please login to merge, or discard this patch.
Indentation   +296 added lines, -296 removed lines patch added patch discarded remove patch
@@ -33,27 +33,27 @@  discard block
 block discarded – undo
33 33
  */
34 34
 abstract class ModeleThirdPartyDoc extends CommonDocGenerator
35 35
 {
36
-    var $error='';
36
+	var $error='';
37 37
 
38
-    /**
39
-     *  Return list of active generation modules
40
-     *
38
+	/**
39
+	 *  Return list of active generation modules
40
+	 *
41 41
 	 * 	@param	DoliDB		$db					Database handler
42
-     *  @param	integer		$maxfilenamelength  Max length of value to show
43
-     * 	@return	array							List of templates
44
-     */
45
-    static function liste_modeles($db,$maxfilenamelength=0)
46
-    {
47
-        global $conf;
42
+	 *  @param	integer		$maxfilenamelength  Max length of value to show
43
+	 * 	@return	array							List of templates
44
+	 */
45
+	static function liste_modeles($db,$maxfilenamelength=0)
46
+	{
47
+		global $conf;
48 48
 
49
-        $type='company';
50
-        $liste=array();
49
+		$type='company';
50
+		$liste=array();
51 51
 
52
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
53
-        $liste=getListOfModels($db,$type,$maxfilenamelength);
52
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
53
+		$liste=getListOfModels($db,$type,$maxfilenamelength);
54 54
 
55
-        return $liste;
56
-    }
55
+		return $liste;
56
+	}
57 57
 
58 58
 }
59 59
 
@@ -63,188 +63,188 @@  discard block
 block discarded – undo
63 63
  */
64 64
 abstract class ModeleThirdPartyCode
65 65
 {
66
-    var $error='';
67
-
68
-    /**     Renvoi la description par defaut du modele de numerotation
69
-     *
70
-     *		@param	Translate	$langs		Object langs
71
-     *      @return string      			Texte descripif
72
-     */
73
-    function info($langs)
74
-    {
75
-        $langs->load("bills");
76
-        return $langs->trans("NoDescription");
77
-    }
78
-
79
-    /**     Renvoi nom module
80
-     *
81
-     *		@param	Translate	$langs		Object langs
82
-     *      @return string      			Nom du module
83
-     */
84
-    function getNom($langs)
85
-    {
86
-        return $this->nom;
87
-    }
88
-
89
-
90
-    /**     Renvoi un exemple de numerotation
91
-     *
92
-     *		@param	Translate	$langs		Object langs
93
-     *      @return string      			Example
94
-     */
95
-    function getExample($langs)
96
-    {
97
-        $langs->load("bills");
98
-        return $langs->trans("NoExample");
99
-    }
100
-
101
-    /**     Test si les numeros deja en vigueur dans la base ne provoquent pas de
102
-     *      de conflits qui empechera cette numerotation de fonctionner.
103
-     *
104
-     *      @return     boolean     false si conflit, true si ok
105
-     */
106
-    function canBeActivated()
107
-    {
108
-        return true;
109
-    }
110
-
111
-    /**
112
-     *  Return next value available
113
-     *
114
-     *	@param	Societe		$objsoc		Object thirdparty
115
-     *	@param	int			$type		Type
116
-     *  @return string      			Value
117
-     */
118
-    function getNextValue($objsoc=0,$type=-1)
119
-    {
120
-        global $langs;
121
-        return $langs->trans("Function_getNextValue_InModuleNotWorking");
122
-    }
123
-
124
-
125
-    /**     Return version of module
126
-     *
127
-     *      @return     string      Version
128
-     */
129
-    function getVersion()
130
-    {
131
-        global $langs;
132
-        $langs->load("admin");
133
-
134
-        if ($this->version == 'development') return $langs->trans("VersionDevelopment");
135
-        if ($this->version == 'experimental') return $langs->trans("VersionExperimental");
136
-        if ($this->version == 'dolibarr') return DOL_VERSION;
137
-        if ($this->version) return $this->version;
138
-        return $langs->trans("NotAvailable");
139
-    }
140
-
141
-    /**
142
-     *  Renvoi la liste des modeles de numéroation
143
-     *
144
-     *  @param	DoliDB	$db     			Database handler
145
-     *  @param  integer	$maxfilenamelength  Max length of value to show
146
-     *  @return	array						List of numbers
147
-     */
148
-    static function liste_modeles($db,$maxfilenamelength=0)
149
-    {
150
-        $liste=array();
151
-        $sql ="";
152
-
153
-        $resql = $db->query($sql);
154
-        if ($resql)
155
-        {
156
-            $num = $db->num_rows($resql);
157
-            $i = 0;
158
-            while ($i < $num)
159
-            {
160
-                $row = $db->fetch_row($resql);
161
-                $liste[$row[0]]=$row[1];
162
-                $i++;
163
-            }
164
-        }
165
-        else
166
-        {
167
-            return -1;
168
-        }
169
-        return $liste;
170
-    }
171
-
172
-    /**
173
-     *      Return description of module parameters
174
-     *
175
-     *      @param	Translate	$langs      Output language
176
-     *		@param	Societe		$soc		Third party object
177
-     *		@param	int			$type		-1=Nothing, 0=Customer, 1=Supplier
178
-     *		@return	string					HTML translated description
179
-     */
180
-    function getToolTip($langs,$soc,$type)
181
-    {
182
-        global $conf;
183
-
184
-        $langs->load("admin");
185
-
186
-        $s='';
187
-        if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->getNom($langs).'</b><br>';
188
-        if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
189
-        if ($type == 0)  $s.=$langs->trans("CustomerCodeDesc").'<br>';
190
-        if ($type == 1)  $s.=$langs->trans("SupplierCodeDesc").'<br>';
191
-        if ($type != -1) $s.=$langs->trans("ValidityControledByModule").': <b>'.$this->getNom($langs).'</b><br>';
192
-        $s.='<br>';
193
-        $s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
194
-        if ($type == 0)
195
-        {
196
-            $s.=$langs->trans("RequiredIfCustomer").': ';
197
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
198
-            $s.=yn(!$this->code_null,1,2);
199
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
200
-            $s.='<br>';
201
-        }
202
-        if ($type == 1)
203
-        {
204
-            $s.=$langs->trans("RequiredIfSupplier").': ';
205
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
206
-            $s.=yn(!$this->code_null,1,2);
207
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
208
-            $s.='<br>';
209
-        }
210
-        if ($type == -1)
211
-        {
212
-            $s.=$langs->trans("Required").': ';
213
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
214
-            $s.=yn(!$this->code_null,1,2);
215
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
216
-            $s.='<br>';
217
-        }
218
-        $s.=$langs->trans("CanBeModifiedIfOk").': ';
219
-        $s.=yn($this->code_modifiable,1,2);
220
-        $s.='<br>';
221
-        $s.=$langs->trans("CanBeModifiedIfKo").': '.yn($this->code_modifiable_invalide,1,2).'<br>';
222
-        $s.=$langs->trans("AutomaticCode").': '.yn($this->code_auto,1,2).'<br>';
223
-        $s.='<br>';
224
-        if ($type == 0 || $type == -1)
225
-        {
226
-            $nextval=$this->getNextValue($soc,0);
227
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
228
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
229
-        }
230
-        if ($type == 1 || $type == -1)
231
-        {
232
-            $nextval=$this->getNextValue($soc,1);
233
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
234
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
235
-        }
236
-        return $s;
237
-    }
66
+	var $error='';
67
+
68
+	/**     Renvoi la description par defaut du modele de numerotation
69
+	 *
70
+	 *		@param	Translate	$langs		Object langs
71
+	 *      @return string      			Texte descripif
72
+	 */
73
+	function info($langs)
74
+	{
75
+		$langs->load("bills");
76
+		return $langs->trans("NoDescription");
77
+	}
78
+
79
+	/**     Renvoi nom module
80
+	 *
81
+	 *		@param	Translate	$langs		Object langs
82
+	 *      @return string      			Nom du module
83
+	 */
84
+	function getNom($langs)
85
+	{
86
+		return $this->nom;
87
+	}
88
+
89
+
90
+	/**     Renvoi un exemple de numerotation
91
+	 *
92
+	 *		@param	Translate	$langs		Object langs
93
+	 *      @return string      			Example
94
+	 */
95
+	function getExample($langs)
96
+	{
97
+		$langs->load("bills");
98
+		return $langs->trans("NoExample");
99
+	}
100
+
101
+	/**     Test si les numeros deja en vigueur dans la base ne provoquent pas de
102
+	 *      de conflits qui empechera cette numerotation de fonctionner.
103
+	 *
104
+	 *      @return     boolean     false si conflit, true si ok
105
+	 */
106
+	function canBeActivated()
107
+	{
108
+		return true;
109
+	}
110
+
111
+	/**
112
+	 *  Return next value available
113
+	 *
114
+	 *	@param	Societe		$objsoc		Object thirdparty
115
+	 *	@param	int			$type		Type
116
+	 *  @return string      			Value
117
+	 */
118
+	function getNextValue($objsoc=0,$type=-1)
119
+	{
120
+		global $langs;
121
+		return $langs->trans("Function_getNextValue_InModuleNotWorking");
122
+	}
123
+
124
+
125
+	/**     Return version of module
126
+	 *
127
+	 *      @return     string      Version
128
+	 */
129
+	function getVersion()
130
+	{
131
+		global $langs;
132
+		$langs->load("admin");
133
+
134
+		if ($this->version == 'development') return $langs->trans("VersionDevelopment");
135
+		if ($this->version == 'experimental') return $langs->trans("VersionExperimental");
136
+		if ($this->version == 'dolibarr') return DOL_VERSION;
137
+		if ($this->version) return $this->version;
138
+		return $langs->trans("NotAvailable");
139
+	}
140
+
141
+	/**
142
+	 *  Renvoi la liste des modeles de numéroation
143
+	 *
144
+	 *  @param	DoliDB	$db     			Database handler
145
+	 *  @param  integer	$maxfilenamelength  Max length of value to show
146
+	 *  @return	array						List of numbers
147
+	 */
148
+	static function liste_modeles($db,$maxfilenamelength=0)
149
+	{
150
+		$liste=array();
151
+		$sql ="";
152
+
153
+		$resql = $db->query($sql);
154
+		if ($resql)
155
+		{
156
+			$num = $db->num_rows($resql);
157
+			$i = 0;
158
+			while ($i < $num)
159
+			{
160
+				$row = $db->fetch_row($resql);
161
+				$liste[$row[0]]=$row[1];
162
+				$i++;
163
+			}
164
+		}
165
+		else
166
+		{
167
+			return -1;
168
+		}
169
+		return $liste;
170
+	}
171
+
172
+	/**
173
+	 *      Return description of module parameters
174
+	 *
175
+	 *      @param	Translate	$langs      Output language
176
+	 *		@param	Societe		$soc		Third party object
177
+	 *		@param	int			$type		-1=Nothing, 0=Customer, 1=Supplier
178
+	 *		@return	string					HTML translated description
179
+	 */
180
+	function getToolTip($langs,$soc,$type)
181
+	{
182
+		global $conf;
183
+
184
+		$langs->load("admin");
185
+
186
+		$s='';
187
+		if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->getNom($langs).'</b><br>';
188
+		if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
189
+		if ($type == 0)  $s.=$langs->trans("CustomerCodeDesc").'<br>';
190
+		if ($type == 1)  $s.=$langs->trans("SupplierCodeDesc").'<br>';
191
+		if ($type != -1) $s.=$langs->trans("ValidityControledByModule").': <b>'.$this->getNom($langs).'</b><br>';
192
+		$s.='<br>';
193
+		$s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
194
+		if ($type == 0)
195
+		{
196
+			$s.=$langs->trans("RequiredIfCustomer").': ';
197
+			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
198
+			$s.=yn(!$this->code_null,1,2);
199
+			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
200
+			$s.='<br>';
201
+		}
202
+		if ($type == 1)
203
+		{
204
+			$s.=$langs->trans("RequiredIfSupplier").': ';
205
+			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
206
+			$s.=yn(!$this->code_null,1,2);
207
+			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
208
+			$s.='<br>';
209
+		}
210
+		if ($type == -1)
211
+		{
212
+			$s.=$langs->trans("Required").': ';
213
+			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
214
+			$s.=yn(!$this->code_null,1,2);
215
+			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
216
+			$s.='<br>';
217
+		}
218
+		$s.=$langs->trans("CanBeModifiedIfOk").': ';
219
+		$s.=yn($this->code_modifiable,1,2);
220
+		$s.='<br>';
221
+		$s.=$langs->trans("CanBeModifiedIfKo").': '.yn($this->code_modifiable_invalide,1,2).'<br>';
222
+		$s.=$langs->trans("AutomaticCode").': '.yn($this->code_auto,1,2).'<br>';
223
+		$s.='<br>';
224
+		if ($type == 0 || $type == -1)
225
+		{
226
+			$nextval=$this->getNextValue($soc,0);
227
+			if (empty($nextval)) $nextval=$langs->trans("Undefined");
228
+			$s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
229
+		}
230
+		if ($type == 1 || $type == -1)
231
+		{
232
+			$nextval=$this->getNextValue($soc,1);
233
+			if (empty($nextval)) $nextval=$langs->trans("Undefined");
234
+			$s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
235
+		}
236
+		return $s;
237
+	}
238 238
 
239 239
 	/**
240 240
 	 *   Check if mask/numbering use prefix
241 241
 	 *
242 242
 	 *   @return	int		0=no, 1=yes
243 243
 	 */
244
-    function verif_prefixIsUsed()
245
-    {
246
-        return 0;
247
-    }
244
+	function verif_prefixIsUsed()
245
+	{
246
+		return 0;
247
+	}
248 248
 
249 249
 }
250 250
 
@@ -255,110 +255,110 @@  discard block
 block discarded – undo
255 255
  */
256 256
 abstract class ModeleAccountancyCode
257 257
 {
258
-    var $error='';
259
-
260
-
261
-    /**		Return description of module
262
-     *
263
-     * 		@param	Translate	$langs		Object langs
264
-     * 		@return string      			Description of module
265
-     */
266
-    function info($langs)
267
-    {
268
-        $langs->load("bills");
269
-        return $langs->trans("NoDescription");
270
-    }
271
-
272
-    /**		Return an example of result returned by getNextValue
273
-     *
274
-     *      @param	Translate	$langs		Object langs
275
-     *      @param	societe		$objsoc		Object thirdparty
276
-     *      @param	int			$type		Type of third party (1:customer, 2:supplier, -1:autodetect)
277
-     *      @return	string					Example
278
-     */
279
-    function getExample($langs,$objsoc=0,$type=-1)
280
-    {
281
-        $langs->load("bills");
282
-        return $langs->trans("NoExample");
283
-    }
284
-
285
-    /**     Test si les numeros deja en vigueur dans la base ne provoquent pas de
286
-     *      de conflits qui empechera cette numerotation de fonctionner.
287
-     *
288
-     *      @return     boolean     false si conflit, true si ok
289
-     */
290
-    function canBeActivated()
291
-    {
292
-        return true;
293
-    }
294
-
295
-    /**     Return version of module
296
-     *
297
-     *      @return     string      Version
298
-     */
299
-    function getVersion()
300
-    {
301
-        global $langs;
302
-        $langs->load("admin");
303
-
304
-        if ($this->version == 'development') return $langs->trans("VersionDevelopment");
305
-        if ($this->version == 'experimental') return $langs->trans("VersionExperimental");
306
-        if ($this->version == 'dolibarr') return DOL_VERSION;
307
-        if ($this->version) return $this->version;
308
-        return $langs->trans("NotAvailable");
309
-    }
310
-
311
-    /**
312
-     *      Return description of module parameters
313
-     *
314
-     *      @param	Translate	$langs      Output language
315
-     *		@param	Societe		$soc		Third party object
316
-     *		@param	int			$type		-1=Nothing, 0=Customer, 1=Supplier
317
-     *		@return	string					HTML translated description
318
-     */
319
-    function getToolTip($langs,$soc,$type)
320
-    {
321
-        global $conf,$db;
322
-
323
-        $langs->load("admin");
324
-
325
-        $s='';
326
-        if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->nom.'</b><br>';
327
-        if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
328
-        //$s.='<br>';
329
-        //$s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
330
-        $s.='<br>';
331
-        if ($type == 0 || $type == -1)
332
-        {
333
-            $result=$this->get_code($db,$soc,'customer');
334
-            $nextval=$this->code;
335
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
336
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
337
-        }
338
-        if ($type == 1 || $type == -1)
339
-        {
340
-            $result=$this->get_code($db,$soc,'supplier');
341
-            $nextval=$this->code;
342
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
343
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
344
-        }
345
-        return $s;
346
-    }
347
-
348
-    /**
349
-     *  Set accountancy account code for a third party into this->code
350
-     *
351
-     *  @param	DoliDB	$db             Database handler
352
-     *  @param  Societe	$societe        Third party object
353
-     *  @param  int		$type			'customer' or 'supplier'
354
-     *  @return	int						>=0 if OK, <0 if KO
355
-     */
356
-    function get_code($db, $societe, $type='')
357
-    {
358
-	    global $langs;
359
-
360
-        return $langs->trans("NotAvailable");
361
-    }
258
+	var $error='';
259
+
260
+
261
+	/**		Return description of module
262
+	 *
263
+	 * 		@param	Translate	$langs		Object langs
264
+	 * 		@return string      			Description of module
265
+	 */
266
+	function info($langs)
267
+	{
268
+		$langs->load("bills");
269
+		return $langs->trans("NoDescription");
270
+	}
271
+
272
+	/**		Return an example of result returned by getNextValue
273
+	 *
274
+	 *      @param	Translate	$langs		Object langs
275
+	 *      @param	societe		$objsoc		Object thirdparty
276
+	 *      @param	int			$type		Type of third party (1:customer, 2:supplier, -1:autodetect)
277
+	 *      @return	string					Example
278
+	 */
279
+	function getExample($langs,$objsoc=0,$type=-1)
280
+	{
281
+		$langs->load("bills");
282
+		return $langs->trans("NoExample");
283
+	}
284
+
285
+	/**     Test si les numeros deja en vigueur dans la base ne provoquent pas de
286
+	 *      de conflits qui empechera cette numerotation de fonctionner.
287
+	 *
288
+	 *      @return     boolean     false si conflit, true si ok
289
+	 */
290
+	function canBeActivated()
291
+	{
292
+		return true;
293
+	}
294
+
295
+	/**     Return version of module
296
+	 *
297
+	 *      @return     string      Version
298
+	 */
299
+	function getVersion()
300
+	{
301
+		global $langs;
302
+		$langs->load("admin");
303
+
304
+		if ($this->version == 'development') return $langs->trans("VersionDevelopment");
305
+		if ($this->version == 'experimental') return $langs->trans("VersionExperimental");
306
+		if ($this->version == 'dolibarr') return DOL_VERSION;
307
+		if ($this->version) return $this->version;
308
+		return $langs->trans("NotAvailable");
309
+	}
310
+
311
+	/**
312
+	 *      Return description of module parameters
313
+	 *
314
+	 *      @param	Translate	$langs      Output language
315
+	 *		@param	Societe		$soc		Third party object
316
+	 *		@param	int			$type		-1=Nothing, 0=Customer, 1=Supplier
317
+	 *		@return	string					HTML translated description
318
+	 */
319
+	function getToolTip($langs,$soc,$type)
320
+	{
321
+		global $conf,$db;
322
+
323
+		$langs->load("admin");
324
+
325
+		$s='';
326
+		if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->nom.'</b><br>';
327
+		if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
328
+		//$s.='<br>';
329
+		//$s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
330
+		$s.='<br>';
331
+		if ($type == 0 || $type == -1)
332
+		{
333
+			$result=$this->get_code($db,$soc,'customer');
334
+			$nextval=$this->code;
335
+			if (empty($nextval)) $nextval=$langs->trans("Undefined");
336
+			$s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
337
+		}
338
+		if ($type == 1 || $type == -1)
339
+		{
340
+			$result=$this->get_code($db,$soc,'supplier');
341
+			$nextval=$this->code;
342
+			if (empty($nextval)) $nextval=$langs->trans("Undefined");
343
+			$s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
344
+		}
345
+		return $s;
346
+	}
347
+
348
+	/**
349
+	 *  Set accountancy account code for a third party into this->code
350
+	 *
351
+	 *  @param	DoliDB	$db             Database handler
352
+	 *  @param  Societe	$societe        Third party object
353
+	 *  @param  int		$type			'customer' or 'supplier'
354
+	 *  @return	int						>=0 if OK, <0 if KO
355
+	 */
356
+	function get_code($db, $societe, $type='')
357
+	{
358
+		global $langs;
359
+
360
+		return $langs->trans("NotAvailable");
361
+	}
362 362
 }
363 363
 
364 364
 
Please login to merge, or discard this patch.
Spacing   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
  */
34 34
 abstract class ModeleThirdPartyDoc extends CommonDocGenerator
35 35
 {
36
-    var $error='';
36
+    var $error = '';
37 37
 
38 38
     /**
39 39
      *  Return list of active generation modules
@@ -42,15 +42,15 @@  discard block
 block discarded – undo
42 42
      *  @param	integer		$maxfilenamelength  Max length of value to show
43 43
      * 	@return	array							List of templates
44 44
      */
45
-    static function liste_modeles($db,$maxfilenamelength=0)
45
+    static function liste_modeles($db, $maxfilenamelength = 0)
46 46
     {
47 47
         global $conf;
48 48
 
49
-        $type='company';
50
-        $liste=array();
49
+        $type = 'company';
50
+        $liste = array();
51 51
 
52 52
         include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
53
-        $liste=getListOfModels($db,$type,$maxfilenamelength);
53
+        $liste = getListOfModels($db, $type, $maxfilenamelength);
54 54
 
55 55
         return $liste;
56 56
     }
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
  */
64 64
 abstract class ModeleThirdPartyCode
65 65
 {
66
-    var $error='';
66
+    var $error = '';
67 67
 
68 68
     /**     Renvoi la description par defaut du modele de numerotation
69 69
      *
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
      *	@param	int			$type		Type
116 116
      *  @return string      			Value
117 117
      */
118
-    function getNextValue($objsoc=0,$type=-1)
118
+    function getNextValue($objsoc = 0, $type = -1)
119 119
     {
120 120
         global $langs;
121 121
         return $langs->trans("Function_getNextValue_InModuleNotWorking");
@@ -145,10 +145,10 @@  discard block
 block discarded – undo
145 145
      *  @param  integer	$maxfilenamelength  Max length of value to show
146 146
      *  @return	array						List of numbers
147 147
      */
148
-    static function liste_modeles($db,$maxfilenamelength=0)
148
+    static function liste_modeles($db, $maxfilenamelength = 0)
149 149
     {
150
-        $liste=array();
151
-        $sql ="";
150
+        $liste = array();
151
+        $sql = "";
152 152
 
153 153
         $resql = $db->query($sql);
154 154
         if ($resql)
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
             while ($i < $num)
159 159
             {
160 160
                 $row = $db->fetch_row($resql);
161
-                $liste[$row[0]]=$row[1];
161
+                $liste[$row[0]] = $row[1];
162 162
                 $i++;
163 163
             }
164 164
         }
@@ -177,61 +177,61 @@  discard block
 block discarded – undo
177 177
      *		@param	int			$type		-1=Nothing, 0=Customer, 1=Supplier
178 178
      *		@return	string					HTML translated description
179 179
      */
180
-    function getToolTip($langs,$soc,$type)
180
+    function getToolTip($langs, $soc, $type)
181 181
     {
182 182
         global $conf;
183 183
 
184 184
         $langs->load("admin");
185 185
 
186
-        $s='';
187
-        if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->getNom($langs).'</b><br>';
188
-        if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
189
-        if ($type == 0)  $s.=$langs->trans("CustomerCodeDesc").'<br>';
190
-        if ($type == 1)  $s.=$langs->trans("SupplierCodeDesc").'<br>';
191
-        if ($type != -1) $s.=$langs->trans("ValidityControledByModule").': <b>'.$this->getNom($langs).'</b><br>';
192
-        $s.='<br>';
193
-        $s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
186
+        $s = '';
187
+        if ($type == -1) $s .= $langs->trans("Name").': <b>'.$this->getNom($langs).'</b><br>';
188
+        if ($type == -1) $s .= $langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
189
+        if ($type == 0)  $s .= $langs->trans("CustomerCodeDesc").'<br>';
190
+        if ($type == 1)  $s .= $langs->trans("SupplierCodeDesc").'<br>';
191
+        if ($type != -1) $s .= $langs->trans("ValidityControledByModule").': <b>'.$this->getNom($langs).'</b><br>';
192
+        $s .= '<br>';
193
+        $s .= '<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
194 194
         if ($type == 0)
195 195
         {
196
-            $s.=$langs->trans("RequiredIfCustomer").': ';
197
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
198
-            $s.=yn(!$this->code_null,1,2);
199
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
200
-            $s.='<br>';
196
+            $s .= $langs->trans("RequiredIfCustomer").': ';
197
+            if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && !empty($this->code_null)) $s .= '<strike>';
198
+            $s .= yn(!$this->code_null, 1, 2);
199
+            if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && !empty($this->code_null)) $s .= '</strike> '.yn(1, 1, 2).' ('.$langs->trans("ForcedToByAModule", $langs->transnoentities("yes")).')';
200
+            $s .= '<br>';
201 201
         }
202 202
         if ($type == 1)
203 203
         {
204
-            $s.=$langs->trans("RequiredIfSupplier").': ';
205
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
206
-            $s.=yn(!$this->code_null,1,2);
207
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
208
-            $s.='<br>';
204
+            $s .= $langs->trans("RequiredIfSupplier").': ';
205
+            if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && !empty($this->code_null)) $s .= '<strike>';
206
+            $s .= yn(!$this->code_null, 1, 2);
207
+            if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && !empty($this->code_null)) $s .= '</strike> '.yn(1, 1, 2).' ('.$langs->trans("ForcedToByAModule", $langs->transnoentities("yes")).')';
208
+            $s .= '<br>';
209 209
         }
210 210
         if ($type == -1)
211 211
         {
212
-            $s.=$langs->trans("Required").': ';
213
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
214
-            $s.=yn(!$this->code_null,1,2);
215
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
216
-            $s.='<br>';
212
+            $s .= $langs->trans("Required").': ';
213
+            if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && !empty($this->code_null)) $s .= '<strike>';
214
+            $s .= yn(!$this->code_null, 1, 2);
215
+            if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && !empty($this->code_null)) $s .= '</strike> '.yn(1, 1, 2).' ('.$langs->trans("ForcedToByAModule", $langs->transnoentities("yes")).')';
216
+            $s .= '<br>';
217 217
         }
218
-        $s.=$langs->trans("CanBeModifiedIfOk").': ';
219
-        $s.=yn($this->code_modifiable,1,2);
220
-        $s.='<br>';
221
-        $s.=$langs->trans("CanBeModifiedIfKo").': '.yn($this->code_modifiable_invalide,1,2).'<br>';
222
-        $s.=$langs->trans("AutomaticCode").': '.yn($this->code_auto,1,2).'<br>';
223
-        $s.='<br>';
218
+        $s .= $langs->trans("CanBeModifiedIfOk").': ';
219
+        $s .= yn($this->code_modifiable, 1, 2);
220
+        $s .= '<br>';
221
+        $s .= $langs->trans("CanBeModifiedIfKo").': '.yn($this->code_modifiable_invalide, 1, 2).'<br>';
222
+        $s .= $langs->trans("AutomaticCode").': '.yn($this->code_auto, 1, 2).'<br>';
223
+        $s .= '<br>';
224 224
         if ($type == 0 || $type == -1)
225 225
         {
226
-            $nextval=$this->getNextValue($soc,0);
227
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
228
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
226
+            $nextval = $this->getNextValue($soc, 0);
227
+            if (empty($nextval)) $nextval = $langs->trans("Undefined");
228
+            $s .= $langs->trans("NextValue").($type == -1 ? ' ('.$langs->trans("Customer").')' : '').': <b>'.$nextval.'</b><br>';
229 229
         }
230 230
         if ($type == 1 || $type == -1)
231 231
         {
232
-            $nextval=$this->getNextValue($soc,1);
233
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
234
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
232
+            $nextval = $this->getNextValue($soc, 1);
233
+            if (empty($nextval)) $nextval = $langs->trans("Undefined");
234
+            $s .= $langs->trans("NextValue").($type == -1 ? ' ('.$langs->trans("Supplier").')' : '').': <b>'.$nextval.'</b>';
235 235
         }
236 236
         return $s;
237 237
     }
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
  */
256 256
 abstract class ModeleAccountancyCode
257 257
 {
258
-    var $error='';
258
+    var $error = '';
259 259
 
260 260
 
261 261
     /**		Return description of module
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
      *      @param	int			$type		Type of third party (1:customer, 2:supplier, -1:autodetect)
277 277
      *      @return	string					Example
278 278
      */
279
-    function getExample($langs,$objsoc=0,$type=-1)
279
+    function getExample($langs, $objsoc = 0, $type = -1)
280 280
     {
281 281
         $langs->load("bills");
282 282
         return $langs->trans("NoExample");
@@ -316,31 +316,31 @@  discard block
 block discarded – undo
316 316
      *		@param	int			$type		-1=Nothing, 0=Customer, 1=Supplier
317 317
      *		@return	string					HTML translated description
318 318
      */
319
-    function getToolTip($langs,$soc,$type)
319
+    function getToolTip($langs, $soc, $type)
320 320
     {
321
-        global $conf,$db;
321
+        global $conf, $db;
322 322
 
323 323
         $langs->load("admin");
324 324
 
325
-        $s='';
326
-        if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->nom.'</b><br>';
327
-        if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
325
+        $s = '';
326
+        if ($type == -1) $s .= $langs->trans("Name").': <b>'.$this->nom.'</b><br>';
327
+        if ($type == -1) $s .= $langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
328 328
         //$s.='<br>';
329 329
         //$s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
330
-        $s.='<br>';
330
+        $s .= '<br>';
331 331
         if ($type == 0 || $type == -1)
332 332
         {
333
-            $result=$this->get_code($db,$soc,'customer');
334
-            $nextval=$this->code;
335
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
336
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
333
+            $result = $this->get_code($db, $soc, 'customer');
334
+            $nextval = $this->code;
335
+            if (empty($nextval)) $nextval = $langs->trans("Undefined");
336
+            $s .= $langs->trans("NextValue").($type == -1 ? ' ('.$langs->trans("Customer").')' : '').': <b>'.$nextval.'</b><br>';
337 337
         }
338 338
         if ($type == 1 || $type == -1)
339 339
         {
340
-            $result=$this->get_code($db,$soc,'supplier');
341
-            $nextval=$this->code;
342
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
343
-            $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
340
+            $result = $this->get_code($db, $soc, 'supplier');
341
+            $nextval = $this->code;
342
+            if (empty($nextval)) $nextval = $langs->trans("Undefined");
343
+            $s .= $langs->trans("NextValue").($type == -1 ? ' ('.$langs->trans("Supplier").')' : '').': <b>'.$nextval.'</b>';
344 344
         }
345 345
         return $s;
346 346
     }
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
      *  @param  int		$type			'customer' or 'supplier'
354 354
      *  @return	int						>=0 if OK, <0 if KO
355 355
      */
356
-    function get_code($db, $societe, $type='')
356
+    function get_code($db, $societe, $type = '')
357 357
     {
358 358
 	    global $langs;
359 359
 
@@ -378,9 +378,9 @@  discard block
 block discarded – undo
378 378
  *  @deprecated Use the new function generateDocument of Facture class
379 379
  *  @see Societe::generateDocument()
380 380
  */
381
-function thirdparty_doc_create(DoliDB $db, Societe $object, $message, $modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
381
+function thirdparty_doc_create(DoliDB $db, Societe $object, $message, $modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
382 382
 {
383
-	dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
383
+	dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
384 384
 
385 385
 	return $object->generateDocument($modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
386 386
 }
Please login to merge, or discard this patch.
Braces   +76 added lines, -27 removed lines patch added patch discarded remove patch
@@ -131,10 +131,18 @@  discard block
 block discarded – undo
131 131
         global $langs;
132 132
         $langs->load("admin");
133 133
 
134
-        if ($this->version == 'development') return $langs->trans("VersionDevelopment");
135
-        if ($this->version == 'experimental') return $langs->trans("VersionExperimental");
136
-        if ($this->version == 'dolibarr') return DOL_VERSION;
137
-        if ($this->version) return $this->version;
134
+        if ($this->version == 'development') {
135
+        	return $langs->trans("VersionDevelopment");
136
+        }
137
+        if ($this->version == 'experimental') {
138
+        	return $langs->trans("VersionExperimental");
139
+        }
140
+        if ($this->version == 'dolibarr') {
141
+        	return DOL_VERSION;
142
+        }
143
+        if ($this->version) {
144
+        	return $this->version;
145
+        }
138 146
         return $langs->trans("NotAvailable");
139 147
     }
140 148
 
@@ -161,8 +169,7 @@  discard block
 block discarded – undo
161 169
                 $liste[$row[0]]=$row[1];
162 170
                 $i++;
163 171
             }
164
-        }
165
-        else
172
+        } else
166 173
         {
167 174
             return -1;
168 175
         }
@@ -184,35 +191,57 @@  discard block
 block discarded – undo
184 191
         $langs->load("admin");
185 192
 
186 193
         $s='';
187
-        if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->getNom($langs).'</b><br>';
188
-        if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
189
-        if ($type == 0)  $s.=$langs->trans("CustomerCodeDesc").'<br>';
190
-        if ($type == 1)  $s.=$langs->trans("SupplierCodeDesc").'<br>';
191
-        if ($type != -1) $s.=$langs->trans("ValidityControledByModule").': <b>'.$this->getNom($langs).'</b><br>';
194
+        if ($type == -1) {
195
+        	$s.=$langs->trans("Name").': <b>'.$this->getNom($langs).'</b><br>';
196
+        }
197
+        if ($type == -1) {
198
+        	$s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
199
+        }
200
+        if ($type == 0) {
201
+        	$s.=$langs->trans("CustomerCodeDesc").'<br>';
202
+        }
203
+        if ($type == 1) {
204
+        	$s.=$langs->trans("SupplierCodeDesc").'<br>';
205
+        }
206
+        if ($type != -1) {
207
+        	$s.=$langs->trans("ValidityControledByModule").': <b>'.$this->getNom($langs).'</b><br>';
208
+        }
192 209
         $s.='<br>';
193 210
         $s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
194 211
         if ($type == 0)
195 212
         {
196 213
             $s.=$langs->trans("RequiredIfCustomer").': ';
197
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
214
+            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) {
215
+            	$s.='<strike>';
216
+            }
198 217
             $s.=yn(!$this->code_null,1,2);
199
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
218
+            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) {
219
+            	$s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
220
+            }
200 221
             $s.='<br>';
201 222
         }
202 223
         if ($type == 1)
203 224
         {
204 225
             $s.=$langs->trans("RequiredIfSupplier").': ';
205
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
226
+            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) {
227
+            	$s.='<strike>';
228
+            }
206 229
             $s.=yn(!$this->code_null,1,2);
207
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
230
+            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) {
231
+            	$s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
232
+            }
208 233
             $s.='<br>';
209 234
         }
210 235
         if ($type == -1)
211 236
         {
212 237
             $s.=$langs->trans("Required").': ';
213
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='<strike>';
238
+            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) {
239
+            	$s.='<strike>';
240
+            }
214 241
             $s.=yn(!$this->code_null,1,2);
215
-            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) $s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
242
+            if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED) && ! empty($this->code_null)) {
243
+            	$s.='</strike> '.yn(1,1,2).' ('.$langs->trans("ForcedToByAModule",$langs->transnoentities("yes")).')';
244
+            }
216 245
             $s.='<br>';
217 246
         }
218 247
         $s.=$langs->trans("CanBeModifiedIfOk").': ';
@@ -224,13 +253,17 @@  discard block
 block discarded – undo
224 253
         if ($type == 0 || $type == -1)
225 254
         {
226 255
             $nextval=$this->getNextValue($soc,0);
227
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
256
+            if (empty($nextval)) {
257
+            	$nextval=$langs->trans("Undefined");
258
+            }
228 259
             $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
229 260
         }
230 261
         if ($type == 1 || $type == -1)
231 262
         {
232 263
             $nextval=$this->getNextValue($soc,1);
233
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
264
+            if (empty($nextval)) {
265
+            	$nextval=$langs->trans("Undefined");
266
+            }
234 267
             $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
235 268
         }
236 269
         return $s;
@@ -301,10 +334,18 @@  discard block
 block discarded – undo
301 334
         global $langs;
302 335
         $langs->load("admin");
303 336
 
304
-        if ($this->version == 'development') return $langs->trans("VersionDevelopment");
305
-        if ($this->version == 'experimental') return $langs->trans("VersionExperimental");
306
-        if ($this->version == 'dolibarr') return DOL_VERSION;
307
-        if ($this->version) return $this->version;
337
+        if ($this->version == 'development') {
338
+        	return $langs->trans("VersionDevelopment");
339
+        }
340
+        if ($this->version == 'experimental') {
341
+        	return $langs->trans("VersionExperimental");
342
+        }
343
+        if ($this->version == 'dolibarr') {
344
+        	return DOL_VERSION;
345
+        }
346
+        if ($this->version) {
347
+        	return $this->version;
348
+        }
308 349
         return $langs->trans("NotAvailable");
309 350
     }
310 351
 
@@ -323,8 +364,12 @@  discard block
 block discarded – undo
323 364
         $langs->load("admin");
324 365
 
325 366
         $s='';
326
-        if ($type == -1) $s.=$langs->trans("Name").': <b>'.$this->nom.'</b><br>';
327
-        if ($type == -1) $s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
367
+        if ($type == -1) {
368
+        	$s.=$langs->trans("Name").': <b>'.$this->nom.'</b><br>';
369
+        }
370
+        if ($type == -1) {
371
+        	$s.=$langs->trans("Version").': <b>'.$this->getVersion().'</b><br>';
372
+        }
328 373
         //$s.='<br>';
329 374
         //$s.='<u>'.$langs->trans("ThisIsModuleRules").':</u><br>';
330 375
         $s.='<br>';
@@ -332,14 +377,18 @@  discard block
 block discarded – undo
332 377
         {
333 378
             $result=$this->get_code($db,$soc,'customer');
334 379
             $nextval=$this->code;
335
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
380
+            if (empty($nextval)) {
381
+            	$nextval=$langs->trans("Undefined");
382
+            }
336 383
             $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Customer").')':'').': <b>'.$nextval.'</b><br>';
337 384
         }
338 385
         if ($type == 1 || $type == -1)
339 386
         {
340 387
             $result=$this->get_code($db,$soc,'supplier');
341 388
             $nextval=$this->code;
342
-            if (empty($nextval)) $nextval=$langs->trans("Undefined");
389
+            if (empty($nextval)) {
390
+            	$nextval=$langs->trans("Undefined");
391
+            }
343 392
             $s.=$langs->trans("NextValue").($type == -1?' ('.$langs->trans("Supplier").')':'').': <b>'.$nextval.'</b>';
344 393
         }
345 394
         return $s;
Please login to merge, or discard this patch.
htdocs/core/modules/supplier_order/mod_commande_fournisseur_muguet.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
     /**
99 99
      * 	Return next value
100 100
 	 *
101
-	 *  @param	Societe		$objsoc     Object third party
101
+	 *  @param	integer		$objsoc     Object third party
102 102
 	 *  @param  Object		$object		Object
103 103
 	 *  @return string      			Value if OK, 0 if KO
104 104
      */
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
     /**
137 137
      * 	Renvoie la reference de commande suivante non utilisee
138 138
      *
139
-	 *  @param	Societe		$objsoc     Object third party
139
+	 *  @param	integer		$objsoc     Object third party
140 140
 	 *  @param  Object	    $object		Object
141 141
      *  @return string      			Texte descripif
142 142
      */
Please login to merge, or discard this patch.
Braces   +21 added lines, -8 removed lines patch added patch discarded remove patch
@@ -44,7 +44,10 @@  discard block
 block discarded – undo
44 44
 	{
45 45
 	    global $conf;
46 46
 	    
47
-	    if ((float) $conf->global->MAIN_VERSION_LAST_INSTALL >= 5.0) $this->prefix = 'PO';   // We use correct standard code "PO = Purchase Order"
47
+	    if ((float) $conf->global->MAIN_VERSION_LAST_INSTALL >= 5.0) {
48
+	    	$this->prefix = 'PO';
49
+	    }
50
+	    // We use correct standard code "PO = Purchase Order"
48 51
 	}
49 52
 	
50 53
     /**
@@ -96,8 +99,7 @@  discard block
 block discarded – undo
96 99
         if (! $coyymm || preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i',$coyymm))
97 100
         {
98 101
             return true;
99
-        }
100
-        else
102
+        } else
101 103
         {
102 104
 			$langs->load("errors");
103 105
 			$this->error=$langs->trans('ErrorNumRefModel',$max);
@@ -127,17 +129,28 @@  discard block
 block discarded – undo
127 129
         if ($resql)
128 130
         {
129 131
             $obj = $db->fetch_object($resql);
130
-            if ($obj) $max = intval($obj->max);
131
-            else $max=0;
132
+            if ($obj) {
133
+            	$max = intval($obj->max);
134
+            } else {
135
+            	$max=0;
136
+            }
132 137
         }
133 138
 
134 139
 		//$date=time();
135 140
         $date=$object->date_commande;   // Not always defined
136
-        if (empty($date)) $date=$object->date;  // Creation date is order date for suppliers orders
141
+        if (empty($date)) {
142
+        	$date=$object->date;
143
+        }
144
+        // Creation date is order date for suppliers orders
137 145
         $yymm = strftime("%y%m",$date);
138 146
         
139
-        if ($max >= (pow(10, 4) - 1)) $num=$max+1;	// If counter > 9999, we do not format on 4 chars, we take number as it is
140
-        else $num = sprintf("%04s",$max+1);
147
+        if ($max >= (pow(10, 4) - 1)) {
148
+        	$num=$max+1;
149
+        }
150
+        // If counter > 9999, we do not format on 4 chars, we take number as it is
151
+        else {
152
+        	$num = sprintf("%04s",$max+1);
153
+        }
141 154
 
142 155
         return $this->prefix.$yymm."-".$num;
143 156
     }
Please login to merge, or discard this patch.
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -42,117 +42,117 @@
 block discarded – undo
42 42
 	 */
43 43
 	function __construct()
44 44
 	{
45
-	    global $conf;
45
+		global $conf;
46 46
 
47
-	    if ((float) $conf->global->MAIN_VERSION_LAST_INSTALL >= 5.0) $this->prefix = 'PO';   // We use correct standard code "PO = Purchase Order"
47
+		if ((float) $conf->global->MAIN_VERSION_LAST_INSTALL >= 5.0) $this->prefix = 'PO';   // We use correct standard code "PO = Purchase Order"
48 48
 	}
49 49
 
50
-    /**
51
-     * 	Return description of numbering module
52
-     *
53
-     *  @return     string      Text with description
54
-     */
55
-    function info()
56
-    {
57
-    	global $langs;
58
-      	return $langs->trans("SimpleNumRefModelDesc",$this->prefix);
59
-    }
60
-
61
-
62
-    /**
63
-     * 	Renvoi un exemple de numerotation
64
-     *
65
-     *  @return     string      Example
66
-     */
67
-    function getExample()
68
-    {
69
-        return $this->prefix."0501-0001";
70
-    }
71
-
72
-
73
-    /**
74
-     * 	Test si les numeros deja en vigueur dans la base ne provoquent pas de
75
-     *  de conflits qui empechera cette numerotation de fonctionner.
76
-     *
77
-     *  @return     boolean     false si conflit, true si ok
78
-     */
79
-    function canBeActivated()
80
-    {
81
-    	global $conf,$langs,$db;
82
-
83
-        $coyymm=''; $max='';
50
+	/**
51
+	 * 	Return description of numbering module
52
+	 *
53
+	 *  @return     string      Text with description
54
+	 */
55
+	function info()
56
+	{
57
+		global $langs;
58
+	  	return $langs->trans("SimpleNumRefModelDesc",$this->prefix);
59
+	}
60
+
61
+
62
+	/**
63
+	 * 	Renvoi un exemple de numerotation
64
+	 *
65
+	 *  @return     string      Example
66
+	 */
67
+	function getExample()
68
+	{
69
+		return $this->prefix."0501-0001";
70
+	}
71
+
72
+
73
+	/**
74
+	 * 	Test si les numeros deja en vigueur dans la base ne provoquent pas de
75
+	 *  de conflits qui empechera cette numerotation de fonctionner.
76
+	 *
77
+	 *  @return     boolean     false si conflit, true si ok
78
+	 */
79
+	function canBeActivated()
80
+	{
81
+		global $conf,$langs,$db;
82
+
83
+		$coyymm=''; $max='';
84 84
 
85 85
 		$posindice=8;
86 86
 		$sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max";
87
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
87
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
88 88
 		$sql.= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'";
89
-        $sql.= " AND entity = ".$conf->entity;
90
-        $resql=$db->query($sql);
91
-        if ($resql)
92
-        {
93
-            $row = $db->fetch_row($resql);
94
-            if ($row) { $coyymm = substr($row[0],0,6); $max=$row[0]; }
95
-        }
96
-        if (! $coyymm || preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i',$coyymm))
97
-        {
98
-            return true;
99
-        }
100
-        else
101
-        {
89
+		$sql.= " AND entity = ".$conf->entity;
90
+		$resql=$db->query($sql);
91
+		if ($resql)
92
+		{
93
+			$row = $db->fetch_row($resql);
94
+			if ($row) { $coyymm = substr($row[0],0,6); $max=$row[0]; }
95
+		}
96
+		if (! $coyymm || preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i',$coyymm))
97
+		{
98
+			return true;
99
+		}
100
+		else
101
+		{
102 102
 			$langs->load("errors");
103 103
 			$this->error=$langs->trans('ErrorNumRefModel',$max);
104
-            return false;
105
-        }
106
-    }
104
+			return false;
105
+		}
106
+	}
107 107
 
108
-    /**
109
-     * 	Return next value
108
+	/**
109
+	 * 	Return next value
110 110
 	 *
111 111
 	 *  @param	Societe		$objsoc     Object third party
112 112
 	 *  @param  Object		$object		Object
113 113
 	 *  @return string      			Value if OK, 0 if KO
114
-     */
115
-    function getNextValue($objsoc=0,$object='')
116
-    {
117
-        global $db,$conf;
118
-
119
-        // D'abord on recupere la valeur max
120
-        $posindice=8;
121
-        $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max";
122
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
114
+	 */
115
+	function getNextValue($objsoc=0,$object='')
116
+	{
117
+		global $db,$conf;
118
+
119
+		// D'abord on recupere la valeur max
120
+		$posindice=8;
121
+		$sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max";
122
+		$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
123 123
 		$sql.= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'";
124
-        $sql.= " AND entity = ".$conf->entity;
124
+		$sql.= " AND entity = ".$conf->entity;
125 125
 
126
-        $resql=$db->query($sql);
127
-        if ($resql)
128
-        {
129
-            $obj = $db->fetch_object($resql);
130
-            if ($obj) $max = intval($obj->max);
131
-            else $max=0;
132
-        }
126
+		$resql=$db->query($sql);
127
+		if ($resql)
128
+		{
129
+			$obj = $db->fetch_object($resql);
130
+			if ($obj) $max = intval($obj->max);
131
+			else $max=0;
132
+		}
133 133
 
134 134
 		//$date=time();
135
-        $date=$object->date_commande;   // Not always defined
136
-        if (empty($date)) $date=$object->date;  // Creation date is order date for suppliers orders
137
-        $yymm = strftime("%y%m",$date);
135
+		$date=$object->date_commande;   // Not always defined
136
+		if (empty($date)) $date=$object->date;  // Creation date is order date for suppliers orders
137
+		$yymm = strftime("%y%m",$date);
138 138
 
139
-        if ($max >= (pow(10, 4) - 1)) $num=$max+1;	// If counter > 9999, we do not format on 4 chars, we take number as it is
140
-        else $num = sprintf("%04s",$max+1);
139
+		if ($max >= (pow(10, 4) - 1)) $num=$max+1;	// If counter > 9999, we do not format on 4 chars, we take number as it is
140
+		else $num = sprintf("%04s",$max+1);
141 141
 
142
-        return $this->prefix.$yymm."-".$num;
143
-    }
142
+		return $this->prefix.$yymm."-".$num;
143
+	}
144 144
 
145 145
 
146
-    /**
147
-     * 	Renvoie la reference de commande suivante non utilisee
148
-     *
146
+	/**
147
+	 * 	Renvoie la reference de commande suivante non utilisee
148
+	 *
149 149
 	 *  @param	Societe		$objsoc     Object third party
150 150
 	 *  @param  Object	    $object		Object
151
-     *  @return string      			Texte descripif
152
-     */
153
-    function commande_get_num($objsoc=0,$object='')
154
-    {
155
-        return $this->getNextValue($objsoc,$object);
156
-    }
151
+	 *  @return string      			Texte descripif
152
+	 */
153
+	function commande_get_num($objsoc=0,$object='')
154
+	{
155
+		return $this->getNextValue($objsoc,$object);
156
+	}
157 157
 }
158 158
 
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
  *		\brief      Fichier contenant la classe du modele de numerotation de reference de commande fournisseur Muguet
24 24
  */
25 25
 
26
-require_once DOL_DOCUMENT_ROOT .'/core/modules/supplier_order/modules_commandefournisseur.php';
26
+require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
27 27
 
28 28
 
29 29
 /**
@@ -31,10 +31,10 @@  discard block
 block discarded – undo
31 31
  */
32 32
 class mod_commande_fournisseur_muguet extends ModeleNumRefSuppliersOrders
33 33
 {
34
-	var $version='dolibarr';		// 'development', 'experimental', 'dolibarr'
34
+	var $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr'
35 35
 	var $error = '';
36 36
 	var $nom = 'Muguet';
37
-	var $prefix='CF';
37
+	var $prefix = 'CF';
38 38
 
39 39
 
40 40
 	/**
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 	{
45 45
 	    global $conf;
46 46
 
47
-	    if ((float) $conf->global->MAIN_VERSION_LAST_INSTALL >= 5.0) $this->prefix = 'PO';   // We use correct standard code "PO = Purchase Order"
47
+	    if ((float) $conf->global->MAIN_VERSION_LAST_INSTALL >= 5.0) $this->prefix = 'PO'; // We use correct standard code "PO = Purchase Order"
48 48
 	}
49 49
 
50 50
     /**
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
     function info()
56 56
     {
57 57
     	global $langs;
58
-      	return $langs->trans("SimpleNumRefModelDesc",$this->prefix);
58
+      	return $langs->trans("SimpleNumRefModelDesc", $this->prefix);
59 59
     }
60 60
 
61 61
 
@@ -78,29 +78,29 @@  discard block
 block discarded – undo
78 78
      */
79 79
     function canBeActivated()
80 80
     {
81
-    	global $conf,$langs,$db;
81
+    	global $conf, $langs, $db;
82 82
 
83
-        $coyymm=''; $max='';
83
+        $coyymm = ''; $max = '';
84 84
 
85
-		$posindice=8;
85
+		$posindice = 8;
86 86
 		$sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max";
87
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
88
-		$sql.= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'";
89
-        $sql.= " AND entity = ".$conf->entity;
90
-        $resql=$db->query($sql);
87
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
88
+		$sql .= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'";
89
+        $sql .= " AND entity = ".$conf->entity;
90
+        $resql = $db->query($sql);
91 91
         if ($resql)
92 92
         {
93 93
             $row = $db->fetch_row($resql);
94
-            if ($row) { $coyymm = substr($row[0],0,6); $max=$row[0]; }
94
+            if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; }
95 95
         }
96
-        if (! $coyymm || preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i',$coyymm))
96
+        if (!$coyymm || preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm))
97 97
         {
98 98
             return true;
99 99
         }
100 100
         else
101 101
         {
102 102
 			$langs->load("errors");
103
-			$this->error=$langs->trans('ErrorNumRefModel',$max);
103
+			$this->error = $langs->trans('ErrorNumRefModel', $max);
104 104
             return false;
105 105
         }
106 106
     }
@@ -112,32 +112,32 @@  discard block
 block discarded – undo
112 112
 	 *  @param  Object		$object		Object
113 113
 	 *  @return string      			Value if OK, 0 if KO
114 114
      */
115
-    function getNextValue($objsoc=0,$object='')
115
+    function getNextValue($objsoc = 0, $object = '')
116 116
     {
117
-        global $db,$conf;
117
+        global $db, $conf;
118 118
 
119 119
         // D'abord on recupere la valeur max
120
-        $posindice=8;
120
+        $posindice = 8;
121 121
         $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max";
122
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
123
-		$sql.= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'";
124
-        $sql.= " AND entity = ".$conf->entity;
122
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur";
123
+		$sql .= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'";
124
+        $sql .= " AND entity = ".$conf->entity;
125 125
 
126
-        $resql=$db->query($sql);
126
+        $resql = $db->query($sql);
127 127
         if ($resql)
128 128
         {
129 129
             $obj = $db->fetch_object($resql);
130 130
             if ($obj) $max = intval($obj->max);
131
-            else $max=0;
131
+            else $max = 0;
132 132
         }
133 133
 
134 134
 		//$date=time();
135
-        $date=$object->date_commande;   // Not always defined
136
-        if (empty($date)) $date=$object->date;  // Creation date is order date for suppliers orders
137
-        $yymm = strftime("%y%m",$date);
135
+        $date = $object->date_commande; // Not always defined
136
+        if (empty($date)) $date = $object->date; // Creation date is order date for suppliers orders
137
+        $yymm = strftime("%y%m", $date);
138 138
 
139
-        if ($max >= (pow(10, 4) - 1)) $num=$max+1;	// If counter > 9999, we do not format on 4 chars, we take number as it is
140
-        else $num = sprintf("%04s",$max+1);
139
+        if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is
140
+        else $num = sprintf("%04s", $max + 1);
141 141
 
142 142
         return $this->prefix.$yymm."-".$num;
143 143
     }
@@ -150,9 +150,9 @@  discard block
 block discarded – undo
150 150
 	 *  @param  Object	    $object		Object
151 151
      *  @return string      			Texte descripif
152 152
      */
153
-    function commande_get_num($objsoc=0,$object='')
153
+    function commande_get_num($objsoc = 0, $object = '')
154 154
     {
155
-        return $this->getNextValue($objsoc,$object);
155
+        return $this->getNextValue($objsoc, $object);
156 156
     }
157 157
 }
158 158
 
Please login to merge, or discard this patch.
htdocs/core/modules/supplier_order/mod_commande_fournisseur_orchidee.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 	/**
103 103
 	 *  Return next value
104 104
 	 *
105
-	 *  @param	Societe		$objsoc     Object third party
105
+	 *  @param	integer		$objsoc     Object third party
106 106
 	 *  @param  Object	    $object		Object
107 107
      *  @return string      			Value if OK, 0 if KO
108 108
 	*/
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
     /**
131 131
      *  Renvoie la reference de commande suivante non utilisee
132 132
      *
133
-	 *  @param	Societe		$objsoc     Object third party
133
+	 *  @param	integer		$objsoc     Object third party
134 134
 	 *  @param  Object	    $object		Object
135 135
      *  @return string      			Texte descripif
136 136
      */
Please login to merge, or discard this patch.
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -37,14 +37,14 @@  discard block
 block discarded – undo
37 37
 	var $nom = 'Orchidee';
38 38
 
39 39
 
40
-    /**
41
-     *  Renvoi la description du modele de numerotation
42
-     *
43
-     * 	@return     string      Texte descripif
44
-     */
40
+	/**
41
+	 *  Renvoi la description du modele de numerotation
42
+	 *
43
+	 * 	@return     string      Texte descripif
44
+	 */
45 45
 	function info()
46
-    {
47
-    	global $conf,$langs;
46
+	{
47
+		global $conf,$langs;
48 48
 
49 49
 		$langs->load("bills");
50 50
 		$langs->load("admin");
@@ -76,20 +76,20 @@  discard block
 block discarded – undo
76 76
 		$texte.= '</form>';
77 77
 
78 78
 		return $texte;
79
-    }
80
-
81
-    /**
82
-     *  Renvoi un exemple de numerotation
83
-     *
84
-     *  @return     string      Example
85
-     */
86
-    function getExample()
87
-    {
88
-    	global $conf,$langs,$mysoc;
89
-
90
-    	$old_code_client=$mysoc->code_client;
91
-    	$mysoc->code_client='CCCCCCCCCC';
92
-    	$numExample = $this->getNextValue($mysoc,'');
79
+	}
80
+
81
+	/**
82
+	 *  Renvoi un exemple de numerotation
83
+	 *
84
+	 *  @return     string      Example
85
+	 */
86
+	function getExample()
87
+	{
88
+		global $conf,$langs,$mysoc;
89
+
90
+		$old_code_client=$mysoc->code_client;
91
+		$mysoc->code_client='CCCCCCCCCC';
92
+		$numExample = $this->getNextValue($mysoc,'');
93 93
 		$mysoc->code_client=$old_code_client;
94 94
 
95 95
 		if (! $numExample)
@@ -97,17 +97,17 @@  discard block
 block discarded – undo
97 97
 			$numExample = $langs->trans('NotConfigured');
98 98
 		}
99 99
 		return $numExample;
100
-    }
100
+	}
101 101
 
102 102
 	/**
103 103
 	 *  Return next value
104 104
 	 *
105 105
 	 *  @param	Societe		$objsoc     Object third party
106 106
 	 *  @param  Object	    $object		Object
107
-     *  @return string      			Value if OK, 0 if KO
108
-	*/
109
-    function getNextValue($objsoc=0,$object='')
110
-    {
107
+	 *  @return string      			Value if OK, 0 if KO
108
+	 */
109
+	function getNextValue($objsoc=0,$object='')
110
+	{
111 111
 		global $db,$conf;
112 112
 
113 113
 		require_once DOL_DOCUMENT_ROOT .'/core/lib/functions2.lib.php';
@@ -127,16 +127,16 @@  discard block
 block discarded – undo
127 127
 	}
128 128
 
129 129
 
130
-    /**
131
-     *  Renvoie la reference de commande suivante non utilisee
132
-     *
130
+	/**
131
+	 *  Renvoie la reference de commande suivante non utilisee
132
+	 *
133 133
 	 *  @param	Societe		$objsoc     Object third party
134 134
 	 *  @param  Object	    $object		Object
135
-     *  @return string      			Texte descripif
136
-     */
137
-    function commande_get_num($objsoc=0,$object='')
138
-    {
139
-        return $this->getNextValue($objsoc,$object);
140
-    }
135
+	 *  @return string      			Texte descripif
136
+	 */
137
+	function commande_get_num($objsoc=0,$object='')
138
+	{
139
+		return $this->getNextValue($objsoc,$object);
140
+	}
141 141
 }
142 142
 
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  *	\brief      Fichier contenant la classe du modele de numerotation de reference de commande fournisseur Orchidee
25 25
  */
26 26
 
27
-require_once DOL_DOCUMENT_ROOT .'/core/modules/supplier_order/modules_commandefournisseur.php';
27
+require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
28 28
 
29 29
 
30 30
 /**
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
  */
33 33
 class mod_commande_fournisseur_orchidee extends ModeleNumRefSuppliersOrders
34 34
 {
35
-	var $version='dolibarr';		// 'development', 'experimental', 'dolibarr'
35
+	var $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr'
36 36
 	var $error = '';
37 37
 	var $nom = 'Orchidee';
38 38
 
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
      */
45 45
 	function info()
46 46
     {
47
-    	global $conf,$langs;
47
+    	global $conf, $langs;
48 48
 
49 49
 		$langs->load("bills");
50 50
 		$langs->load("admin");
@@ -52,28 +52,28 @@  discard block
 block discarded – undo
52 52
 		$form = new Form($this->db);
53 53
 
54 54
 		$texte = $langs->trans('GenericNumRefModelDesc')."<br>\n";
55
-		$texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
56
-		$texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
57
-		$texte.= '<input type="hidden" name="action" value="updateMask">';
58
-		$texte.= '<input type="hidden" name="maskconstorder" value="COMMANDE_FOURNISSEUR_ORCHIDEE_MASK">';
59
-		$texte.= '<table class="nobordernopadding" width="100%">';
60
-
61
-		$tooltip=$langs->trans("GenericMaskCodes",$langs->transnoentities("Order"),$langs->transnoentities("Order"));
62
-		$tooltip.=$langs->trans("GenericMaskCodes2");
63
-		$tooltip.=$langs->trans("GenericMaskCodes3");
64
-		$tooltip.=$langs->trans("GenericMaskCodes4a",$langs->transnoentities("Order"),$langs->transnoentities("Order"));
65
-		$tooltip.=$langs->trans("GenericMaskCodes5");
55
+		$texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
56
+		$texte .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
57
+		$texte .= '<input type="hidden" name="action" value="updateMask">';
58
+		$texte .= '<input type="hidden" name="maskconstorder" value="COMMANDE_FOURNISSEUR_ORCHIDEE_MASK">';
59
+		$texte .= '<table class="nobordernopadding" width="100%">';
60
+
61
+		$tooltip = $langs->trans("GenericMaskCodes", $langs->transnoentities("Order"), $langs->transnoentities("Order"));
62
+		$tooltip .= $langs->trans("GenericMaskCodes2");
63
+		$tooltip .= $langs->trans("GenericMaskCodes3");
64
+		$tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("Order"), $langs->transnoentities("Order"));
65
+		$tooltip .= $langs->trans("GenericMaskCodes5");
66 66
 
67 67
 		// Parametrage du prefix
68
-		$texte.= '<tr><td>'.$langs->trans("Mask").':</td>';
69
-		$texte.= '<td align="right">'.$form->textwithpicto('<input type="text" class="flat" size="24" name="maskorder" value="'.$conf->global->COMMANDE_FOURNISSEUR_ORCHIDEE_MASK.'">',$tooltip,1,1).'</td>';
68
+		$texte .= '<tr><td>'.$langs->trans("Mask").':</td>';
69
+		$texte .= '<td align="right">'.$form->textwithpicto('<input type="text" class="flat" size="24" name="maskorder" value="'.$conf->global->COMMANDE_FOURNISSEUR_ORCHIDEE_MASK.'">', $tooltip, 1, 1).'</td>';
70 70
 
71
-		$texte.= '<td align="left" rowspan="2">&nbsp; <input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button"></td>';
71
+		$texte .= '<td align="left" rowspan="2">&nbsp; <input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button"></td>';
72 72
 
73
-		$texte.= '</tr>';
73
+		$texte .= '</tr>';
74 74
 
75
-		$texte.= '</table>';
76
-		$texte.= '</form>';
75
+		$texte .= '</table>';
76
+		$texte .= '</form>';
77 77
 
78 78
 		return $texte;
79 79
     }
@@ -85,14 +85,14 @@  discard block
 block discarded – undo
85 85
      */
86 86
     function getExample()
87 87
     {
88
-    	global $conf,$langs,$mysoc;
88
+    	global $conf, $langs, $mysoc;
89 89
 
90
-    	$old_code_client=$mysoc->code_client;
91
-    	$mysoc->code_client='CCCCCCCCCC';
92
-    	$numExample = $this->getNextValue($mysoc,'');
93
-		$mysoc->code_client=$old_code_client;
90
+    	$old_code_client = $mysoc->code_client;
91
+    	$mysoc->code_client = 'CCCCCCCCCC';
92
+    	$numExample = $this->getNextValue($mysoc, '');
93
+		$mysoc->code_client = $old_code_client;
94 94
 
95
-		if (! $numExample)
95
+		if (!$numExample)
96 96
 		{
97 97
 			$numExample = $langs->trans('NotConfigured');
98 98
 		}
@@ -106,22 +106,22 @@  discard block
 block discarded – undo
106 106
 	 *  @param  Object	    $object		Object
107 107
      *  @return string      			Value if OK, 0 if KO
108 108
 	*/
109
-    function getNextValue($objsoc=0,$object='')
109
+    function getNextValue($objsoc = 0, $object = '')
110 110
     {
111
-		global $db,$conf;
111
+		global $db, $conf;
112 112
 
113
-		require_once DOL_DOCUMENT_ROOT .'/core/lib/functions2.lib.php';
113
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
114 114
 
115 115
 		// On defini critere recherche compteur
116
-		$mask=$conf->global->COMMANDE_FOURNISSEUR_ORCHIDEE_MASK;
116
+		$mask = $conf->global->COMMANDE_FOURNISSEUR_ORCHIDEE_MASK;
117 117
 
118
-		if (! $mask)
118
+		if (!$mask)
119 119
 		{
120
-			$this->error='NotConfigured';
120
+			$this->error = 'NotConfigured';
121 121
 			return 0;
122 122
 		}
123 123
 
124
-		$numFinal=get_next_value($db,$mask,'commande_fournisseur','ref','',$objsoc,$object->date_commande);
124
+		$numFinal = get_next_value($db, $mask, 'commande_fournisseur', 'ref', '', $objsoc, $object->date_commande);
125 125
 
126 126
 		return  $numFinal;
127 127
 	}
@@ -134,9 +134,9 @@  discard block
 block discarded – undo
134 134
 	 *  @param  Object	    $object		Object
135 135
      *  @return string      			Texte descripif
136 136
      */
137
-    function commande_get_num($objsoc=0,$object='')
137
+    function commande_get_num($objsoc = 0, $object = '')
138 138
     {
139
-        return $this->getNextValue($objsoc,$object);
139
+        return $this->getNextValue($objsoc, $object);
140 140
     }
141 141
 }
142 142
 
Please login to merge, or discard this patch.
htdocs/loan/class/paymentloan.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@
 block discarded – undo
226 226
 	/**
227 227
 	 *  Update database
228 228
 	 *
229
-	 *  @param	User	$user        	User that modify
229
+	 *  @param	integer	$user        	User that modify
230 230
 	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
231 231
 	 *  @return int         			<0 if KO, >0 if OK
232 232
 	 */
Please login to merge, or discard this patch.
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -37,8 +37,8 @@  discard block
 block discarded – undo
37 37
 	var $datec='';
38 38
 	var $tms='';
39 39
 	var $datep='';
40
-    var $amounts=array();   // Array of amounts
41
-    var $amount_capital;    // Total amount of payment
40
+	var $amounts=array();   // Array of amounts
41
+	var $amount_capital;    // Total amount of payment
42 42
 	var $amount_insurance;
43 43
 	var $amount_interest;
44 44
 	var $fk_typepayment;
@@ -65,8 +65,8 @@  discard block
 block discarded – undo
65 65
 
66 66
 	/**
67 67
 	 *  Create payment of loan into database.
68
-     *  Use this->amounts to have list of lines for the payment
69
-     *
68
+	 *  Use this->amounts to have list of lines for the payment
69
+	 *
70 70
 	 *  @param      User		$user   User making payment
71 71
 	 *  @return     int     			<0 if KO, id of payment if OK
72 72
 	 */
@@ -76,9 +76,9 @@  discard block
 block discarded – undo
76 76
 
77 77
 		$error=0;
78 78
 
79
-        $now=dol_now();
79
+		$now=dol_now();
80 80
 
81
-        // Validate parameters
81
+		// Validate parameters
82 82
 		if (! $this->datepaid)
83 83
 		{
84 84
 			$this->error='ErrorBadValueForParameter';
@@ -98,11 +98,11 @@  discard block
 block discarded – undo
98 98
 		if (isset($this->fk_user_creat))	$this->fk_user_creat = trim($this->fk_user_creat);
99 99
 		if (isset($this->fk_user_modif))	$this->fk_user_modif = trim($this->fk_user_modif);
100 100
 
101
-        $totalamount = $this->amount_capital + $this->amount_insurance + $this->amount_interest;
102
-        $totalamount = price2num($totalamount);
101
+		$totalamount = $this->amount_capital + $this->amount_insurance + $this->amount_interest;
102
+		$totalamount = price2num($totalamount);
103 103
 
104
-        // Check parameters
105
-        if ($totalamount == 0) return -1; // Negative amounts are accepted for reject prelevement but not null
104
+		// Check parameters
105
+		if ($totalamount == 0) return -1; // Negative amounts are accepted for reject prelevement but not null
106 106
 
107 107
 
108 108
 		$this->db->begin();
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 			}
128 128
 			else
129 129
 			{
130
-                $this->error=$this->db->lasterror();
130
+				$this->error=$this->db->lasterror();
131 131
 				$error++;
132 132
 			}
133 133
 
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 
136 136
 		if ($totalamount != 0 && ! $error)
137 137
 		{
138
-		    $this->amount_capital=$totalamount;
139
-            $this->total=$totalamount;    // deprecated
140
-		    $this->db->commit();
138
+			$this->amount_capital=$totalamount;
139
+			$this->total=$totalamount;    // deprecated
140
+			$this->db->commit();
141 141
 			return $this->id;
142 142
 		}
143 143
 		else
@@ -168,8 +168,8 @@  discard block
 block discarded – undo
168 168
 		$sql.= " t.amount_interest,";
169 169
 		$sql.= " t.fk_typepayment,";
170 170
 		$sql.= " t.num_payment,";
171
-        $sql.= " t.note_private,";
172
-        $sql.= " t.note_public,";
171
+		$sql.= " t.note_private,";
172
+		$sql.= " t.note_public,";
173 173
 		$sql.= " t.fk_bank,";
174 174
 		$sql.= " t.fk_user_creat,";
175 175
 		$sql.= " t.fk_user_modif,";
@@ -326,15 +326,15 @@  discard block
 block discarded – undo
326 326
 
327 327
 		$this->db->begin();
328 328
 
329
-	    if (! $error)
330
-        {
331
-            $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url";
332
-            $sql.= " WHERE type='payment_loan' AND url_id=".$this->id;
329
+		if (! $error)
330
+		{
331
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url";
332
+			$sql.= " WHERE type='payment_loan' AND url_id=".$this->id;
333 333
 
334
-            dol_syslog(get_class($this)."::delete", LOG_DEBUG);
335
-            $resql = $this->db->query($sql);
336
-            if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
337
-        }
334
+			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
335
+			$resql = $this->db->query($sql);
336
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
337
+		}
338 338
 
339 339
 		if (! $error)
340 340
 		{
@@ -380,95 +380,95 @@  discard block
 block discarded – undo
380 380
 		}
381 381
 	}
382 382
 
383
-    /**
384
-     *      Add record into bank for payment with links between this bank record and invoices of payment.
385
-     *      All payment properties must have been set first like after a call to create().
386
-     *
387
-     *      @param	User	$user               Object of user making payment
388
-     *      @param  int		$fk_loan            Id of fk_loan to do link with this payment
389
-     *      @param  string	$mode               'payment_loan'
390
-     *      @param  string	$label              Label to use in bank record
391
-     *      @param  int		$accountid          Id of bank account to do link with
392
-     *      @param  string	$emetteur_nom       Name of transmitter
393
-     *      @param  string	$emetteur_banque    Name of bank
394
-     *      @return int                 		<0 if KO, >0 if OK
395
-     */
396
-    function addPaymentToBank($user, $fk_loan, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque)
397
-    {
398
-        global $conf;
399
-
400
-        $error=0;
401
-
402
-        if (! empty($conf->banque->enabled))
403
-        {
404
-            require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
405
-
406
-            $acc = new Account($this->db);
407
-            $acc->fetch($accountid);
408
-
409
-            $total=$this->total;
410
-            if ($mode == 'payment_loan') $total=-$total;
411
-
412
-            // Insert payment into llx_bank
413
-            $bank_line_id = $acc->addline(
414
-                $this->datepaid,
415
-                $this->paymenttype,  // Payment mode id or code ("CHQ or VIR for example")
416
-                $label,
417
-                $total,
418
-                $this->num_payment,
419
-                '',
420
-                $user,
421
-                $emetteur_nom,
422
-                $emetteur_banque
423
-            );
424
-
425
-            // Update fk_bank into llx_paiement.
426
-            // We know the payment who generated the account write
427
-            if ($bank_line_id > 0)
428
-            {
429
-                $result=$this->update_fk_bank($bank_line_id);
430
-                if ($result <= 0)
431
-                {
432
-                    $error++;
433
-                    dol_print_error($this->db);
434
-                }
435
-
436
-                // Add link 'payment_loan' in bank_url between payment and bank transaction
437
-                $url='';
438
-                if ($mode == 'payment_loan') $url=DOL_URL_ROOT.'/loan/payment/card.php?id=';
439
-                if ($url)
440
-                {
441
-                    $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode);
442
-                    if ($result <= 0)
443
-                    {
444
-                        $error++;
445
-                        dol_print_error($this->db);
446
-                    }
447
-                }
448
-
449
-                // Add link 'loan' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
450
-                if ($mode == 'payment_loan')
451
-                {
452
-                    $result=$acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label?$this->label:''),'loan');
453
-                    if ($result <= 0) dol_print_error($this->db);
454
-                }
455
-            }
456
-            else
457
-            {
458
-                $this->error=$acc->error;
459
-                $error++;
460
-            }
461
-        }
462
-
463
-        if (! $error)
464
-        {
465
-            return 1;
466
-        }
467
-        else
468
-        {
469
-            return -1;
470
-        }
471
-    }
383
+	/**
384
+	 *      Add record into bank for payment with links between this bank record and invoices of payment.
385
+	 *      All payment properties must have been set first like after a call to create().
386
+	 *
387
+	 *      @param	User	$user               Object of user making payment
388
+	 *      @param  int		$fk_loan            Id of fk_loan to do link with this payment
389
+	 *      @param  string	$mode               'payment_loan'
390
+	 *      @param  string	$label              Label to use in bank record
391
+	 *      @param  int		$accountid          Id of bank account to do link with
392
+	 *      @param  string	$emetteur_nom       Name of transmitter
393
+	 *      @param  string	$emetteur_banque    Name of bank
394
+	 *      @return int                 		<0 if KO, >0 if OK
395
+	 */
396
+	function addPaymentToBank($user, $fk_loan, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque)
397
+	{
398
+		global $conf;
399
+
400
+		$error=0;
401
+
402
+		if (! empty($conf->banque->enabled))
403
+		{
404
+			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
405
+
406
+			$acc = new Account($this->db);
407
+			$acc->fetch($accountid);
408
+
409
+			$total=$this->total;
410
+			if ($mode == 'payment_loan') $total=-$total;
411
+
412
+			// Insert payment into llx_bank
413
+			$bank_line_id = $acc->addline(
414
+				$this->datepaid,
415
+				$this->paymenttype,  // Payment mode id or code ("CHQ or VIR for example")
416
+				$label,
417
+				$total,
418
+				$this->num_payment,
419
+				'',
420
+				$user,
421
+				$emetteur_nom,
422
+				$emetteur_banque
423
+			);
424
+
425
+			// Update fk_bank into llx_paiement.
426
+			// We know the payment who generated the account write
427
+			if ($bank_line_id > 0)
428
+			{
429
+				$result=$this->update_fk_bank($bank_line_id);
430
+				if ($result <= 0)
431
+				{
432
+					$error++;
433
+					dol_print_error($this->db);
434
+				}
435
+
436
+				// Add link 'payment_loan' in bank_url between payment and bank transaction
437
+				$url='';
438
+				if ($mode == 'payment_loan') $url=DOL_URL_ROOT.'/loan/payment/card.php?id=';
439
+				if ($url)
440
+				{
441
+					$result=$acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode);
442
+					if ($result <= 0)
443
+					{
444
+						$error++;
445
+						dol_print_error($this->db);
446
+					}
447
+				}
448
+
449
+				// Add link 'loan' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
450
+				if ($mode == 'payment_loan')
451
+				{
452
+					$result=$acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label?$this->label:''),'loan');
453
+					if ($result <= 0) dol_print_error($this->db);
454
+				}
455
+			}
456
+			else
457
+			{
458
+				$this->error=$acc->error;
459
+				$error++;
460
+			}
461
+		}
462
+
463
+		if (! $error)
464
+		{
465
+			return 1;
466
+		}
467
+		else
468
+		{
469
+			return -1;
470
+		}
471
+	}
472 472
 
473 473
 
474 474
 	/**
Please login to merge, or discard this patch.
Braces   +99 added lines, -46 removed lines patch added patch discarded remove patch
@@ -86,23 +86,48 @@  discard block
 block discarded – undo
86 86
 		}
87 87
 
88 88
 		// Clean parameters
89
-		if (isset($this->fk_loan)) 			$this->fk_loan = trim($this->fk_loan);
90
-		if (isset($this->amount_capital))	$this->amount_capital = price2num($this->amount_capital?$this->amount_capital:0);
91
-		if (isset($this->amount_insurance))	$this->amount_insurance = price2num($this->amount_insurance?$this->amount_insurance:0);
92
-		if (isset($this->amount_interest))	$this->amount_interest = price2num($this->amount_interest?$this->amount_interest:0);
93
-		if (isset($this->fk_typepayment))	$this->fk_typepayment = trim($this->fk_typepayment);
94
-		if (isset($this->num_payment))		$this->num_payment = trim($this->num_payment);
95
-		if (isset($this->note_private))     $this->note_private = trim($this->note_private);
96
-		if (isset($this->note_public))      $this->note_public = trim($this->note_public);
97
-		if (isset($this->fk_bank))			$this->fk_bank = trim($this->fk_bank);
98
-		if (isset($this->fk_user_creat))	$this->fk_user_creat = trim($this->fk_user_creat);
99
-		if (isset($this->fk_user_modif))	$this->fk_user_modif = trim($this->fk_user_modif);
89
+		if (isset($this->fk_loan)) {
90
+			$this->fk_loan = trim($this->fk_loan);
91
+		}
92
+		if (isset($this->amount_capital)) {
93
+			$this->amount_capital = price2num($this->amount_capital?$this->amount_capital:0);
94
+		}
95
+		if (isset($this->amount_insurance)) {
96
+			$this->amount_insurance = price2num($this->amount_insurance?$this->amount_insurance:0);
97
+		}
98
+		if (isset($this->amount_interest)) {
99
+			$this->amount_interest = price2num($this->amount_interest?$this->amount_interest:0);
100
+		}
101
+		if (isset($this->fk_typepayment)) {
102
+			$this->fk_typepayment = trim($this->fk_typepayment);
103
+		}
104
+		if (isset($this->num_payment)) {
105
+			$this->num_payment = trim($this->num_payment);
106
+		}
107
+		if (isset($this->note_private)) {
108
+			$this->note_private = trim($this->note_private);
109
+		}
110
+		if (isset($this->note_public)) {
111
+			$this->note_public = trim($this->note_public);
112
+		}
113
+		if (isset($this->fk_bank)) {
114
+			$this->fk_bank = trim($this->fk_bank);
115
+		}
116
+		if (isset($this->fk_user_creat)) {
117
+			$this->fk_user_creat = trim($this->fk_user_creat);
118
+		}
119
+		if (isset($this->fk_user_modif)) {
120
+			$this->fk_user_modif = trim($this->fk_user_modif);
121
+		}
100 122
 
101 123
         $totalamount = $this->amount_capital + $this->amount_insurance + $this->amount_interest;
102 124
         $totalamount = price2num($totalamount);
103 125
 
104 126
         // Check parameters
105
-        if ($totalamount == 0) return -1; // Negative amounts are accepted for reject prelevement but not null
127
+        if ($totalamount == 0) {
128
+        	return -1;
129
+        }
130
+        // Negative amounts are accepted for reject prelevement but not null
106 131
 
107 132
 
108 133
 		$this->db->begin();
@@ -124,8 +149,7 @@  discard block
 block discarded – undo
124 149
 			if ($resql)
125 150
 			{
126 151
 				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan");
127
-			}
128
-			else
152
+			} else
129 153
 			{
130 154
                 $this->error=$this->db->lasterror();
131 155
 				$error++;
@@ -139,8 +163,7 @@  discard block
 block discarded – undo
139 163
             $this->total=$totalamount;    // deprecated
140 164
 		    $this->db->commit();
141 165
 			return $this->id;
142
-		}
143
-		else
166
+		} else
144 167
 		{
145 168
 			$this->error=$this->db->lasterror();
146 169
 			$this->db->rollback();
@@ -214,8 +237,7 @@  discard block
 block discarded – undo
214 237
 			$this->db->free($resql);
215 238
 
216 239
 			return 1;
217
-		}
218
-		else
240
+		} else
219 241
 		{
220 242
 			$this->error="Error ".$this->db->lasterror();
221 243
 			return -1;
@@ -236,17 +258,39 @@  discard block
 block discarded – undo
236 258
 		$error=0;
237 259
 
238 260
 		// Clean parameters
239
-		if (isset($this->fk_loan)) $this->fk_loan=trim($this->fk_loan);
240
-		if (isset($this->amount_capital)) $this->amount_capital=trim($this->amount_capital);
241
-		if (isset($this->amount_insurance)) $this->amount_insurance=trim($this->amount_insurance);
242
-		if (isset($this->amount_interest)) $this->amount_interest=trim($this->amount_interest);
243
-		if (isset($this->fk_typepayment)) $this->fk_typepayment=trim($this->fk_typepayment);
244
-		if (isset($this->num_payment)) $this->num_payment=trim($this->num_payment);
245
-		if (isset($this->note_private)) $this->note=trim($this->note_private);
246
-		if (isset($this->note_public)) $this->note=trim($this->note_public);
247
-		if (isset($this->fk_bank)) $this->fk_bank=trim($this->fk_bank);
248
-		if (isset($this->fk_user_creat)) $this->fk_user_creat=trim($this->fk_user_creat);
249
-		if (isset($this->fk_user_modif)) $this->fk_user_modif=trim($this->fk_user_modif);
261
+		if (isset($this->fk_loan)) {
262
+			$this->fk_loan=trim($this->fk_loan);
263
+		}
264
+		if (isset($this->amount_capital)) {
265
+			$this->amount_capital=trim($this->amount_capital);
266
+		}
267
+		if (isset($this->amount_insurance)) {
268
+			$this->amount_insurance=trim($this->amount_insurance);
269
+		}
270
+		if (isset($this->amount_interest)) {
271
+			$this->amount_interest=trim($this->amount_interest);
272
+		}
273
+		if (isset($this->fk_typepayment)) {
274
+			$this->fk_typepayment=trim($this->fk_typepayment);
275
+		}
276
+		if (isset($this->num_payment)) {
277
+			$this->num_payment=trim($this->num_payment);
278
+		}
279
+		if (isset($this->note_private)) {
280
+			$this->note=trim($this->note_private);
281
+		}
282
+		if (isset($this->note_public)) {
283
+			$this->note=trim($this->note_public);
284
+		}
285
+		if (isset($this->fk_bank)) {
286
+			$this->fk_bank=trim($this->fk_bank);
287
+		}
288
+		if (isset($this->fk_user_creat)) {
289
+			$this->fk_user_creat=trim($this->fk_user_creat);
290
+		}
291
+		if (isset($this->fk_user_modif)) {
292
+			$this->fk_user_modif=trim($this->fk_user_modif);
293
+		}
250 294
 
251 295
 		// Check parameters
252 296
 		// Put here code to add control on parameters values
@@ -303,8 +347,7 @@  discard block
 block discarded – undo
303 347
 			}
304 348
 			$this->db->rollback();
305 349
 			return -1*$error;
306
-		}
307
-		else
350
+		} else
308 351
 		{
309 352
 			$this->db->commit();
310 353
 			return 1;
@@ -372,8 +415,7 @@  discard block
 block discarded – undo
372 415
 			}
373 416
 			$this->db->rollback();
374 417
 			return -1*$error;
375
-		}
376
-		else
418
+		} else
377 419
 		{
378 420
 			$this->db->commit();
379 421
 			return 1;
@@ -407,7 +449,9 @@  discard block
 block discarded – undo
407 449
             $acc->fetch($accountid);
408 450
 
409 451
             $total=$this->total;
410
-            if ($mode == 'payment_loan') $total=-$total;
452
+            if ($mode == 'payment_loan') {
453
+            	$total=-$total;
454
+            }
411 455
 
412 456
             // Insert payment into llx_bank
413 457
             $bank_line_id = $acc->addline(
@@ -435,7 +479,9 @@  discard block
 block discarded – undo
435 479
 
436 480
                 // Add link 'payment_loan' in bank_url between payment and bank transaction
437 481
                 $url='';
438
-                if ($mode == 'payment_loan') $url=DOL_URL_ROOT.'/loan/payment/card.php?id=';
482
+                if ($mode == 'payment_loan') {
483
+                	$url=DOL_URL_ROOT.'/loan/payment/card.php?id=';
484
+                }
439 485
                 if ($url)
440 486
                 {
441 487
                     $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode);
@@ -450,10 +496,11 @@  discard block
 block discarded – undo
450 496
                 if ($mode == 'payment_loan')
451 497
                 {
452 498
                     $result=$acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label?$this->label:''),'loan');
453
-                    if ($result <= 0) dol_print_error($this->db);
499
+                    if ($result <= 0) {
500
+                    	dol_print_error($this->db);
501
+                    }
454 502
                 }
455
-            }
456
-            else
503
+            } else
457 504
             {
458 505
                 $this->error=$acc->error;
459 506
                 $error++;
@@ -463,8 +510,7 @@  discard block
 block discarded – undo
463 510
         if (! $error)
464 511
         {
465 512
             return 1;
466
-        }
467
-        else
513
+        } else
468 514
         {
469 515
             return -1;
470 516
         }
@@ -486,8 +532,7 @@  discard block
 block discarded – undo
486 532
 		if ($result)
487 533
 		{
488 534
 			return 1;
489
-		}
490
-		else
535
+		} else
491 536
 		{
492 537
 			$this->error=$this->db->error();
493 538
 			return 0;
@@ -507,16 +552,24 @@  discard block
 block discarded – undo
507 552
 
508 553
 		$result='';
509 554
 
510
-		if (empty($this->ref)) $this->ref=$this->lib;
555
+		if (empty($this->ref)) {
556
+			$this->ref=$this->lib;
557
+		}
511 558
 
512 559
 		if (!empty($this->id))
513 560
 		{
514 561
 			$link = '<a href="'.DOL_URL_ROOT.'/compta/payment/card.php?id='.$this->id.'">';
515 562
 			$linkend='</a>';
516 563
 
517
-			if ($withpicto) $result.=($link.img_object($langs->trans("ShowPayment").': '.$this->ref,'payment').$linkend.' ');
518
-			if ($withpicto && $withpicto != 2) $result.=' ';
519
-			if ($withpicto != 2) $result.=$link.($maxlen?dol_trunc($this->ref,$maxlen):$this->ref).$linkend;
564
+			if ($withpicto) {
565
+				$result.=($link.img_object($langs->trans("ShowPayment").': '.$this->ref,'payment').$linkend.' ');
566
+			}
567
+			if ($withpicto && $withpicto != 2) {
568
+				$result.=' ';
569
+			}
570
+			if ($withpicto != 2) {
571
+				$result.=$link.($maxlen?dol_trunc($this->ref,$maxlen):$this->ref).$linkend;
572
+			}
520 573
 		}
521 574
 
522 575
 		return $result;
Please login to merge, or discard this patch.
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -30,15 +30,15 @@  discard block
 block discarded – undo
30 30
  */
31 31
 class PaymentLoan extends CommonObject
32 32
 {
33
-	public $element='payment_loan';			//!< Id that identify managed objects
34
-	public $table_element='payment_loan';	//!< Name of table without prefix where object is stored
33
+	public $element = 'payment_loan'; //!< Id that identify managed objects
34
+	public $table_element = 'payment_loan'; //!< Name of table without prefix where object is stored
35 35
 
36 36
 	var $fk_loan;
37
-	var $datec='';
38
-	var $tms='';
39
-	var $datep='';
40
-    var $amounts=array();   // Array of amounts
41
-    var $amount_capital;    // Total amount of payment
37
+	var $datec = '';
38
+	var $tms = '';
39
+	var $datep = '';
40
+    var $amounts = array(); // Array of amounts
41
+    var $amount_capital; // Total amount of payment
42 42
 	var $amount_insurance;
43 43
 	var $amount_interest;
44 44
 	var $fk_typepayment;
@@ -74,22 +74,22 @@  discard block
 block discarded – undo
74 74
 	{
75 75
 		global $conf, $langs;
76 76
 
77
-		$error=0;
77
+		$error = 0;
78 78
 
79
-        $now=dol_now();
79
+        $now = dol_now();
80 80
 
81 81
         // Validate parameters
82
-		if (! $this->datepaid)
82
+		if (!$this->datepaid)
83 83
 		{
84
-			$this->error='ErrorBadValueForParameter';
84
+			$this->error = 'ErrorBadValueForParameter';
85 85
 			return -1;
86 86
 		}
87 87
 
88 88
 		// Clean parameters
89 89
 		if (isset($this->fk_loan)) 			$this->fk_loan = trim($this->fk_loan);
90
-		if (isset($this->amount_capital))	$this->amount_capital = price2num($this->amount_capital?$this->amount_capital:0);
91
-		if (isset($this->amount_insurance))	$this->amount_insurance = price2num($this->amount_insurance?$this->amount_insurance:0);
92
-		if (isset($this->amount_interest))	$this->amount_interest = price2num($this->amount_interest?$this->amount_interest:0);
90
+		if (isset($this->amount_capital))	$this->amount_capital = price2num($this->amount_capital ? $this->amount_capital : 0);
91
+		if (isset($this->amount_insurance))	$this->amount_insurance = price2num($this->amount_insurance ? $this->amount_insurance : 0);
92
+		if (isset($this->amount_interest))	$this->amount_interest = price2num($this->amount_interest ? $this->amount_interest : 0);
93 93
 		if (isset($this->fk_typepayment))	$this->fk_typepayment = trim($this->fk_typepayment);
94 94
 		if (isset($this->num_payment))		$this->num_payment = trim($this->num_payment);
95 95
 		if (isset($this->note_private))     $this->note_private = trim($this->note_private);
@@ -110,39 +110,39 @@  discard block
 block discarded – undo
110 110
 		if ($totalamount != 0)
111 111
 		{
112 112
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_loan (fk_loan, datec, datep, amount_capital, amount_insurance, amount_interest,";
113
-			$sql.= " fk_typepayment, num_payment, note_private, note_public, fk_user_creat, fk_bank)";
114
-			$sql.= " VALUES (".$this->chid.", '".$this->db->idate($now)."',";
115
-			$sql.= " '".$this->db->idate($this->datepaid)."',";
116
-			$sql.= " ".$this->amount_capital.",";
117
-			$sql.= " ".$this->amount_insurance.",";
118
-			$sql.= " ".$this->amount_interest.",";
119
-			$sql.= " ".$this->paymenttype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', '".$this->db->escape($this->note_public)."', ".$user->id.",";
120
-			$sql.= " 0)";
113
+			$sql .= " fk_typepayment, num_payment, note_private, note_public, fk_user_creat, fk_bank)";
114
+			$sql .= " VALUES (".$this->chid.", '".$this->db->idate($now)."',";
115
+			$sql .= " '".$this->db->idate($this->datepaid)."',";
116
+			$sql .= " ".$this->amount_capital.",";
117
+			$sql .= " ".$this->amount_insurance.",";
118
+			$sql .= " ".$this->amount_interest.",";
119
+			$sql .= " ".$this->paymenttype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', '".$this->db->escape($this->note_public)."', ".$user->id.",";
120
+			$sql .= " 0)";
121 121
 
122 122
 			dol_syslog(get_class($this)."::create", LOG_DEBUG);
123
-			$resql=$this->db->query($sql);
123
+			$resql = $this->db->query($sql);
124 124
 			if ($resql)
125 125
 			{
126 126
 				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan");
127 127
 			}
128 128
 			else
129 129
 			{
130
-                $this->error=$this->db->lasterror();
130
+                $this->error = $this->db->lasterror();
131 131
 				$error++;
132 132
 			}
133 133
 
134 134
 		}
135 135
 
136
-		if ($totalamount != 0 && ! $error)
136
+		if ($totalamount != 0 && !$error)
137 137
 		{
138
-		    $this->amount_capital=$totalamount;
139
-            $this->total=$totalamount;    // deprecated
138
+		    $this->amount_capital = $totalamount;
139
+            $this->total = $totalamount; // deprecated
140 140
 		    $this->db->commit();
141 141
 			return $this->id;
142 142
 		}
143 143
 		else
144 144
 		{
145
-			$this->error=$this->db->lasterror();
145
+			$this->error = $this->db->lasterror();
146 146
 			$this->db->rollback();
147 147
 			return -1;
148 148
 		}
@@ -158,30 +158,30 @@  discard block
 block discarded – undo
158 158
 	{
159 159
 		global $langs;
160 160
 		$sql = "SELECT";
161
-		$sql.= " t.rowid,";
162
-		$sql.= " t.fk_loan,";
163
-		$sql.= " t.datec,";
164
-		$sql.= " t.tms,";
165
-		$sql.= " t.datep,";
166
-		$sql.= " t.amount_capital,";
167
-		$sql.= " t.amount_insurance,";
168
-		$sql.= " t.amount_interest,";
169
-		$sql.= " t.fk_typepayment,";
170
-		$sql.= " t.num_payment,";
171
-        $sql.= " t.note_private,";
172
-        $sql.= " t.note_public,";
173
-		$sql.= " t.fk_bank,";
174
-		$sql.= " t.fk_user_creat,";
175
-		$sql.= " t.fk_user_modif,";
176
-		$sql.= " pt.code as type_code, pt.libelle as type_libelle,";
177
-		$sql.= ' b.fk_account';
178
-		$sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."payment_loan as t)";
179
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid';
180
-		$sql.= " WHERE t.rowid = ".$id." AND t.fk_typepayment = pt.id";
181
-		$sql.= " AND pt.entity = " . getEntity('c_paiement');
161
+		$sql .= " t.rowid,";
162
+		$sql .= " t.fk_loan,";
163
+		$sql .= " t.datec,";
164
+		$sql .= " t.tms,";
165
+		$sql .= " t.datep,";
166
+		$sql .= " t.amount_capital,";
167
+		$sql .= " t.amount_insurance,";
168
+		$sql .= " t.amount_interest,";
169
+		$sql .= " t.fk_typepayment,";
170
+		$sql .= " t.num_payment,";
171
+        $sql .= " t.note_private,";
172
+        $sql .= " t.note_public,";
173
+		$sql .= " t.fk_bank,";
174
+		$sql .= " t.fk_user_creat,";
175
+		$sql .= " t.fk_user_modif,";
176
+		$sql .= " pt.code as type_code, pt.libelle as type_libelle,";
177
+		$sql .= ' b.fk_account';
178
+		$sql .= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."payment_loan as t)";
179
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid';
180
+		$sql .= " WHERE t.rowid = ".$id." AND t.fk_typepayment = pt.id";
181
+		$sql .= " AND pt.entity = ".getEntity('c_paiement');
182 182
 
183 183
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
184
-		$resql=$this->db->query($sql);
184
+		$resql = $this->db->query($sql);
185 185
 		if ($resql)
186 186
 		{
187 187
 			if ($this->db->num_rows($resql))
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 		}
219 219
 		else
220 220
 		{
221
-			$this->error="Error ".$this->db->lasterror();
221
+			$this->error = "Error ".$this->db->lasterror();
222 222
 			return -1;
223 223
 		}
224 224
 	}
@@ -231,23 +231,23 @@  discard block
 block discarded – undo
231 231
 	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
232 232
 	 *  @return int         			<0 if KO, >0 if OK
233 233
 	 */
234
-	function update($user=0, $notrigger=0)
234
+	function update($user = 0, $notrigger = 0)
235 235
 	{
236 236
 		global $conf, $langs;
237
-		$error=0;
237
+		$error = 0;
238 238
 
239 239
 		// Clean parameters
240
-		if (isset($this->fk_loan)) $this->fk_loan=trim($this->fk_loan);
241
-		if (isset($this->amount_capital)) $this->amount_capital=trim($this->amount_capital);
242
-		if (isset($this->amount_insurance)) $this->amount_insurance=trim($this->amount_insurance);
243
-		if (isset($this->amount_interest)) $this->amount_interest=trim($this->amount_interest);
244
-		if (isset($this->fk_typepayment)) $this->fk_typepayment=trim($this->fk_typepayment);
245
-		if (isset($this->num_payment)) $this->num_payment=trim($this->num_payment);
246
-		if (isset($this->note_private)) $this->note=trim($this->note_private);
247
-		if (isset($this->note_public)) $this->note=trim($this->note_public);
248
-		if (isset($this->fk_bank)) $this->fk_bank=trim($this->fk_bank);
249
-		if (isset($this->fk_user_creat)) $this->fk_user_creat=trim($this->fk_user_creat);
250
-		if (isset($this->fk_user_modif)) $this->fk_user_modif=trim($this->fk_user_modif);
240
+		if (isset($this->fk_loan)) $this->fk_loan = trim($this->fk_loan);
241
+		if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital);
242
+		if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance);
243
+		if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest);
244
+		if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment);
245
+		if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment);
246
+		if (isset($this->note_private)) $this->note = trim($this->note_private);
247
+		if (isset($this->note_public)) $this->note = trim($this->note_public);
248
+		if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank);
249
+		if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat);
250
+		if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif);
251 251
 
252 252
 		// Check parameters
253 253
 		// Put here code to add control on parameters values
@@ -255,32 +255,32 @@  discard block
 block discarded – undo
255 255
 		// Update request
256 256
 		$sql = "UPDATE ".MAIN_DB_PREFIX."payment_loan SET";
257 257
 
258
-		$sql.= " fk_loan=".(isset($this->fk_loan)?$this->fk_loan:"null").",";
259
-		$sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
260
-		$sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
261
-		$sql.= " datep=".(dol_strlen($this->datep)!=0 ? "'".$this->db->idate($this->datep)."'" : 'null').",";
262
-		$sql.= " amount_capital=".(isset($this->amount_capital)?$this->amount_capital:"null").",";
263
-		$sql.= " amount_insurance=".(isset($this->amount_insurance)?$this->amount_insurance:"null").",";
264
-		$sql.= " amount_interest=".(isset($this->amount_interest)?$this->amount_interest:"null").",";
265
-		$sql.= " fk_typepayment=".(isset($this->fk_typepayment)?$this->fk_typepayment:"null").",";
266
-		$sql.= " num_payment=".(isset($this->num_payment)?"'".$this->db->escape($this->num_payment)."'":"null").",";
267
-		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
268
-		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
269
-		$sql.= " fk_bank=".(isset($this->fk_bank)?$this->fk_bank:"null").",";
270
-		$sql.= " fk_user_creat=".(isset($this->fk_user_creat)?$this->fk_user_creat:"null").",";
271
-		$sql.= " fk_user_modif=".(isset($this->fk_user_modif)?$this->fk_user_modif:"null")."";
272
-
273
-		$sql.= " WHERE rowid=".$this->id;
258
+		$sql .= " fk_loan=".(isset($this->fk_loan) ? $this->fk_loan : "null").",";
259
+		$sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
260
+		$sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
261
+		$sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').",";
262
+		$sql .= " amount_capital=".(isset($this->amount_capital) ? $this->amount_capital : "null").",";
263
+		$sql .= " amount_insurance=".(isset($this->amount_insurance) ? $this->amount_insurance : "null").",";
264
+		$sql .= " amount_interest=".(isset($this->amount_interest) ? $this->amount_interest : "null").",";
265
+		$sql .= " fk_typepayment=".(isset($this->fk_typepayment) ? $this->fk_typepayment : "null").",";
266
+		$sql .= " num_payment=".(isset($this->num_payment) ? "'".$this->db->escape($this->num_payment)."'" : "null").",";
267
+		$sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
268
+		$sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
269
+		$sql .= " fk_bank=".(isset($this->fk_bank) ? $this->fk_bank : "null").",";
270
+		$sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").",";
271
+		$sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null")."";
272
+
273
+		$sql .= " WHERE rowid=".$this->id;
274 274
 
275 275
 		$this->db->begin();
276 276
 
277 277
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
278 278
 		$resql = $this->db->query($sql);
279
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
279
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
280 280
 
281
-		if (! $error)
281
+		if (!$error)
282 282
 		{
283
-			if (! $notrigger)
283
+			if (!$notrigger)
284 284
 			{
285 285
 				// Uncomment this and change MYOBJECT to your own tag if you
286 286
 				// want this action call a trigger.
@@ -297,13 +297,13 @@  discard block
 block discarded – undo
297 297
 		// Commit or rollback
298 298
 		if ($error)
299 299
 		{
300
-			foreach($this->errors as $errmsg)
300
+			foreach ($this->errors as $errmsg)
301 301
 			{
302 302
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
303
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
303
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
304 304
 			}
305 305
 			$this->db->rollback();
306
-			return -1*$error;
306
+			return -1 * $error;
307 307
 		}
308 308
 		else
309 309
 		{
@@ -320,36 +320,36 @@  discard block
 block discarded – undo
320 320
 	 *  @param  int		$notrigger		0=launch triggers after, 1=disable triggers
321 321
 	 *  @return int						<0 if KO, >0 if OK
322 322
 	 */
323
-	function delete($user, $notrigger=0)
323
+	function delete($user, $notrigger = 0)
324 324
 	{
325 325
 		global $conf, $langs;
326
-		$error=0;
326
+		$error = 0;
327 327
 
328 328
 		$this->db->begin();
329 329
 
330
-	    if (! $error)
330
+	    if (!$error)
331 331
         {
332 332
             $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url";
333
-            $sql.= " WHERE type='payment_loan' AND url_id=".$this->id;
333
+            $sql .= " WHERE type='payment_loan' AND url_id=".$this->id;
334 334
 
335 335
             dol_syslog(get_class($this)."::delete", LOG_DEBUG);
336 336
             $resql = $this->db->query($sql);
337
-            if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
337
+            if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
338 338
         }
339 339
 
340
-		if (! $error)
340
+		if (!$error)
341 341
 		{
342 342
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_loan";
343
-			$sql.= " WHERE rowid=".$this->id;
343
+			$sql .= " WHERE rowid=".$this->id;
344 344
 
345 345
 			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
346 346
 			$resql = $this->db->query($sql);
347
-			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
347
+			if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
348 348
 		}
349 349
 
350
-		if (! $error)
350
+		if (!$error)
351 351
 		{
352
-			if (! $notrigger)
352
+			if (!$notrigger)
353 353
 			{
354 354
 				// Uncomment this and change MYOBJECT to your own tag if you
355 355
 				// want this action call a trigger.
@@ -366,13 +366,13 @@  discard block
 block discarded – undo
366 366
 		// Commit or rollback
367 367
 		if ($error)
368 368
 		{
369
-			foreach($this->errors as $errmsg)
369
+			foreach ($this->errors as $errmsg)
370 370
 			{
371 371
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
372
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
372
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
373 373
 			}
374 374
 			$this->db->rollback();
375
-			return -1*$error;
375
+			return -1 * $error;
376 376
 		}
377 377
 		else
378 378
 		{
@@ -398,22 +398,22 @@  discard block
 block discarded – undo
398 398
     {
399 399
         global $conf;
400 400
 
401
-        $error=0;
401
+        $error = 0;
402 402
 
403
-        if (! empty($conf->banque->enabled))
403
+        if (!empty($conf->banque->enabled))
404 404
         {
405 405
             require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
406 406
 
407 407
             $acc = new Account($this->db);
408 408
             $acc->fetch($accountid);
409 409
 
410
-            $total=$this->total;
411
-            if ($mode == 'payment_loan') $total=-$total;
410
+            $total = $this->total;
411
+            if ($mode == 'payment_loan') $total = -$total;
412 412
 
413 413
             // Insert payment into llx_bank
414 414
             $bank_line_id = $acc->addline(
415 415
                 $this->datepaid,
416
-                $this->paymenttype,  // Payment mode id or code ("CHQ or VIR for example")
416
+                $this->paymenttype, // Payment mode id or code ("CHQ or VIR for example")
417 417
                 $label,
418 418
                 $total,
419 419
                 $this->num_payment,
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
             // We know the payment who generated the account write
428 428
             if ($bank_line_id > 0)
429 429
             {
430
-                $result=$this->update_fk_bank($bank_line_id);
430
+                $result = $this->update_fk_bank($bank_line_id);
431 431
                 if ($result <= 0)
432 432
                 {
433 433
                     $error++;
@@ -435,11 +435,11 @@  discard block
 block discarded – undo
435 435
                 }
436 436
 
437 437
                 // Add link 'payment_loan' in bank_url between payment and bank transaction
438
-                $url='';
439
-                if ($mode == 'payment_loan') $url=DOL_URL_ROOT.'/loan/payment/card.php?id=';
438
+                $url = '';
439
+                if ($mode == 'payment_loan') $url = DOL_URL_ROOT.'/loan/payment/card.php?id=';
440 440
                 if ($url)
441 441
                 {
442
-                    $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode);
442
+                    $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode);
443 443
                     if ($result <= 0)
444 444
                     {
445 445
                         $error++;
@@ -450,18 +450,18 @@  discard block
 block discarded – undo
450 450
                 // Add link 'loan' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
451 451
                 if ($mode == 'payment_loan')
452 452
                 {
453
-                    $result=$acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label?$this->label:''),'loan');
453
+                    $result = $acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label ? $this->label : ''), 'loan');
454 454
                     if ($result <= 0) dol_print_error($this->db);
455 455
                 }
456 456
             }
457 457
             else
458 458
             {
459
-                $this->error=$acc->error;
459
+                $this->error = $acc->error;
460 460
                 $error++;
461 461
             }
462 462
         }
463 463
 
464
-        if (! $error)
464
+        if (!$error)
465 465
         {
466 466
             return 1;
467 467
         }
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 		}
491 491
 		else
492 492
 		{
493
-			$this->error=$this->db->error();
493
+			$this->error = $this->db->error();
494 494
 			return 0;
495 495
 		}
496 496
 	}
@@ -502,22 +502,22 @@  discard block
 block discarded – undo
502 502
 	 * 	@param	int		$maxlen			Max length label
503 503
 	 *	@return	string					Chaine with URL
504 504
 	 */
505
-	function getNomUrl($withpicto=0,$maxlen=0)
505
+	function getNomUrl($withpicto = 0, $maxlen = 0)
506 506
 	{
507 507
 		global $langs;
508 508
 
509
-		$result='';
509
+		$result = '';
510 510
 
511
-		if (empty($this->ref)) $this->ref=$this->lib;
511
+		if (empty($this->ref)) $this->ref = $this->lib;
512 512
 
513 513
 		if (!empty($this->id))
514 514
 		{
515 515
 			$link = '<a href="'.DOL_URL_ROOT.'/compta/payment/card.php?id='.$this->id.'">';
516
-			$linkend='</a>';
516
+			$linkend = '</a>';
517 517
 
518
-			if ($withpicto) $result.=($link.img_object($langs->trans("ShowPayment").': '.$this->ref,'payment').$linkend.' ');
519
-			if ($withpicto && $withpicto != 2) $result.=' ';
520
-			if ($withpicto != 2) $result.=$link.($maxlen?dol_trunc($this->ref,$maxlen):$this->ref).$linkend;
518
+			if ($withpicto) $result .= ($link.img_object($langs->trans("ShowPayment").': '.$this->ref, 'payment').$linkend.' ');
519
+			if ($withpicto && $withpicto != 2) $result .= ' ';
520
+			if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend;
521 521
 		}
522 522
 
523 523
 		return $result;
Please login to merge, or discard this patch.
htdocs/main.inc.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1590,7 +1590,7 @@  discard block
 block discarded – undo
1590 1590
 /**
1591 1591
  *  Show left menu bar
1592 1592
  *
1593
- *  @param  array	$menu_array_before 	       	Table of menu entries to show before entries of menu handler. This param is deprectaed and must be provided to ''.
1593
+ *  @param  string	$menu_array_before 	       	Table of menu entries to show before entries of menu handler. This param is deprectaed and must be provided to ''.
1594 1594
  *  @param  string	$helppagename    	       	Name of wiki page for help ('' by default).
1595 1595
  * 				     		                   	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
1596 1596
  * 									         		       For other external page: http://server/url
@@ -1598,7 +1598,7 @@  discard block
 block discarded – undo
1598 1598
  *  @param  array	$menu_array_after           Table of menu entries to show after entries of menu handler
1599 1599
  *  @param  int		$leftmenuwithoutmainarea    Must be set to 1. 0 by default for backward compatibility with old modules.
1600 1600
  *  @param  string	$title                      Title of web page
1601
- *  @param  string  $acceptdelayedhtml          1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
1601
+ *  @param  integer  $acceptdelayedhtml          1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
1602 1602
  *  @return	void
1603 1603
  */
1604 1604
 function left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
Please login to merge, or discard this patch.
Indentation   +1386 added lines, -1386 removed lines patch added patch discarded remove patch
@@ -38,34 +38,34 @@  discard block
 block discarded – undo
38 38
 $micro_start_time=0;
39 39
 if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
40 40
 {
41
-    list($usec, $sec) = explode(" ", microtime());
42
-    $micro_start_time=((float) $usec + (float) $sec);
43
-    // Add Xdebug code coverage
44
-    //define('XDEBUGCOVERAGE',1);
45
-    if (defined('XDEBUGCOVERAGE')) {
46
-        xdebug_start_code_coverage();
47
-    }
41
+	list($usec, $sec) = explode(" ", microtime());
42
+	$micro_start_time=((float) $usec + (float) $sec);
43
+	// Add Xdebug code coverage
44
+	//define('XDEBUGCOVERAGE',1);
45
+	if (defined('XDEBUGCOVERAGE')) {
46
+		xdebug_start_code_coverage();
47
+	}
48 48
 }
49 49
 
50 50
 // Removed magic_quotes
51 51
 if (function_exists('get_magic_quotes_gpc'))	// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
52 52
 {
53
-    if (get_magic_quotes_gpc())
54
-    {
55
-        // Forcing parameter setting magic_quotes_gpc and cleaning parameters
56
-        // (Otherwise he would have for each position, condition
57
-        // Reading stripslashes variable according to state get_magic_quotes_gpc).
58
-        // Off mode recommended (just do $db->escape for insert / update).
59
-        function stripslashes_deep($value)
60
-        {
61
-            return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
62
-        }
63
-        $_GET     = array_map('stripslashes_deep', $_GET);
64
-        $_POST    = array_map('stripslashes_deep', $_POST);
65
-        $_FILES   = array_map('stripslashes_deep', $_FILES);
66
-        //$_COOKIE  = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql
67
-        @set_magic_quotes_runtime(0);
68
-    }
53
+	if (get_magic_quotes_gpc())
54
+	{
55
+		// Forcing parameter setting magic_quotes_gpc and cleaning parameters
56
+		// (Otherwise he would have for each position, condition
57
+		// Reading stripslashes variable according to state get_magic_quotes_gpc).
58
+		// Off mode recommended (just do $db->escape for insert / update).
59
+		function stripslashes_deep($value)
60
+		{
61
+			return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
62
+		}
63
+		$_GET     = array_map('stripslashes_deep', $_GET);
64
+		$_POST    = array_map('stripslashes_deep', $_POST);
65
+		$_FILES   = array_map('stripslashes_deep', $_FILES);
66
+		//$_COOKIE  = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql
67
+		@set_magic_quotes_runtime(0);
68
+	}
69 69
 }
70 70
 
71 71
 /**
@@ -77,44 +77,44 @@  discard block
 block discarded – undo
77 77
  */
78 78
 function test_sql_and_script_inject($val, $type)
79 79
 {
80
-    $inj = 0;
81
-    // For SQL Injection (only GET and POST are used to be included into bad escaped SQL requests)
82
-    if ($type != 2)
83
-    {
84
-        $inj += preg_match('/delete\s+from/i',	 $val);
85
-        $inj += preg_match('/create\s+table/i',	 $val);
86
-        $inj += preg_match('/update.+set.+=/i',  $val);
87
-        $inj += preg_match('/insert\s+into/i', 	 $val);
88
-        $inj += preg_match('/select.+from/i', 	 $val);
89
-        $inj += preg_match('/union.+select/i', 	 $val);
90
-        $inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
91
-        $inj += preg_match('/(\.\.%2f)+/i',		 $val);
92
-    }
93
-    // For XSS Injection done by adding javascript with script
94
-    // This is all cases a browser consider text is javascript:
95
-    // When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
96
-    // All examples on page: http://ha.ckers.org/xss.html#XSScalc
80
+	$inj = 0;
81
+	// For SQL Injection (only GET and POST are used to be included into bad escaped SQL requests)
82
+	if ($type != 2)
83
+	{
84
+		$inj += preg_match('/delete\s+from/i',	 $val);
85
+		$inj += preg_match('/create\s+table/i',	 $val);
86
+		$inj += preg_match('/update.+set.+=/i',  $val);
87
+		$inj += preg_match('/insert\s+into/i', 	 $val);
88
+		$inj += preg_match('/select.+from/i', 	 $val);
89
+		$inj += preg_match('/union.+select/i', 	 $val);
90
+		$inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
91
+		$inj += preg_match('/(\.\.%2f)+/i',		 $val);
92
+	}
93
+	// For XSS Injection done by adding javascript with script
94
+	// This is all cases a browser consider text is javascript:
95
+	// When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
96
+	// All examples on page: http://ha.ckers.org/xss.html#XSScalc
97 97
 	// More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
98
-    $inj += preg_match('/<script/i', $val);
98
+	$inj += preg_match('/<script/i', $val);
99 99
 	$inj += preg_match('/<iframe/i', $val);
100 100
 	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
101
-    if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
102
-    $inj += preg_match('/base[\s]+href/si', $val);
103
-    $inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
104
-    $inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
105
-    $inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
106
-    $inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
107
-    //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
101
+	if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
102
+	$inj += preg_match('/base[\s]+href/si', $val);
103
+	$inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
104
+	$inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
105
+	$inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
106
+	$inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
107
+	//$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
108 108
 	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
109
-    //if ($type == 1)
110
-    //{
111
-        $inj += preg_match('/javascript:/i', $val);
112
-        $inj += preg_match('/vbscript:/i', $val);
113
-    //}
114
-    // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
115
-    if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
116
-    if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
117
-    return $inj;
109
+	//if ($type == 1)
110
+	//{
111
+		$inj += preg_match('/javascript:/i', $val);
112
+		$inj += preg_match('/vbscript:/i', $val);
113
+	//}
114
+	// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
115
+	if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
116
+	if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
117
+	return $inj;
118 118
 }
119 119
 
120 120
 /**
@@ -126,26 +126,26 @@  discard block
 block discarded – undo
126 126
  */
127 127
 function analyseVarsForSqlAndScriptsInjection(&$var, $type)
128 128
 {
129
-    if (is_array($var))
130
-    {
131
-        foreach ($var as $key => $value)
132
-        {
133
-            if (analyseVarsForSqlAndScriptsInjection($value,$type))
134
-            {
135
-                $var[$key] = $value;
136
-            }
137
-            else
129
+	if (is_array($var))
130
+	{
131
+		foreach ($var as $key => $value)
132
+		{
133
+			if (analyseVarsForSqlAndScriptsInjection($value,$type))
138 134
 			{
139
-                print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
140
-                exit;
141
-            }
142
-        }
143
-        return true;
144
-    }
145
-    else
146
-    {
147
-        return (test_sql_and_script_inject($var,$type) <= 0);
148
-    }
135
+				$var[$key] = $value;
136
+			}
137
+			else
138
+			{
139
+				print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
140
+				exit;
141
+			}
142
+		}
143
+		return true;
144
+	}
145
+	else
146
+	{
147
+		return (test_sql_and_script_inject($var,$type) <= 0);
148
+	}
149 149
 }
150 150
 
151 151
 
@@ -155,14 +155,14 @@  discard block
 block discarded – undo
155 155
 // Sanity check on URL
156 156
 if (! empty($_SERVER["PHP_SELF"]))
157 157
 {
158
-    $morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
159
-    analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
158
+	$morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
159
+	analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
160 160
 }
161 161
 // Sanity check on GET parameters
162 162
 if (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER["QUERY_STRING"]))
163 163
 {
164
-    $morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
165
-    analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
164
+	$morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
165
+	analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
166 166
 }
167 167
 // Sanity check on POST
168 168
 if (! defined('NOSCANPOSTFORINJECTION'))
@@ -211,14 +211,14 @@  discard block
 block discarded – undo
211 211
 // We need this lock as long as we read/write $_SESSION ['vars']. We can close released when finished.
212 212
 if (! defined('NOSESSION'))
213 213
 {
214
-    session_start();
215
-    if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
216
-    {
217
-        foreach ($_SESSION as $key=>$value)
218
-        {
219
-            if (isset($GLOBALS[$key])) unset($GLOBALS[$key]);
220
-        }
221
-    }
214
+	session_start();
215
+	if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
216
+	{
217
+		foreach ($_SESSION as $key=>$value)
218
+		{
219
+			if (isset($GLOBALS[$key])) unset($GLOBALS[$key]);
220
+		}
221
+	}
222 222
 }
223 223
 
224 224
 // Init the 5 global objects, this include will make the new and set properties for: $conf, $db, $langs, $user, $mysoc
@@ -230,54 +230,54 @@  discard block
 block discarded – undo
230 230
 // Detection browser
231 231
 if (isset($_SERVER["HTTP_USER_AGENT"]))
232 232
 {
233
-    $tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
234
-    $conf->browser->name=$tmp['browsername'];
235
-    $conf->browser->os=$tmp['browseros'];
236
-    $conf->browser->version=$tmp['browserversion'];
237
-    $conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
238
-    $conf->browser->phone=$tmp['phone'];	   // TODO deprecated, use ->layout
239
-    $conf->browser->tablet=$tmp['tablet'];	   // TODO deprecated, use ->layout
240
-    //var_dump($conf->browser);
241
-
242
-    if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
243
-    if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
233
+	$tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
234
+	$conf->browser->name=$tmp['browsername'];
235
+	$conf->browser->os=$tmp['browseros'];
236
+	$conf->browser->version=$tmp['browserversion'];
237
+	$conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
238
+	$conf->browser->phone=$tmp['phone'];	   // TODO deprecated, use ->layout
239
+	$conf->browser->tablet=$tmp['tablet'];	   // TODO deprecated, use ->layout
240
+	//var_dump($conf->browser);
241
+
242
+	if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
243
+	if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
244 244
 }
245 245
 
246 246
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
247 247
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
248 248
 if (! empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
249 249
 {
250
-    $newurl='';
251
-    if (is_numeric($conf->file->main_force_https))
252
-    {
253
-        if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
254
-        {
255
-            if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
256
-            {
257
-                $newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
258
-            }
259
-        }
260
-        else	// Check HTTPS environment variable (Apache/mod_ssl only)
261
-        {
262
-            $newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
263
-        }
264
-    }
265
-    else
266
-    {
267
-        // Check HTTPS environment variable (Apache/mod_ssl only)
268
-        $newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
269
-    }
270
-    // Start redirect
271
-    if ($newurl)
272
-    {
273
-        dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
274
-        header("Location: ".$newurl);
275
-        exit;
276
-    }
277
-    else
278
-    {
279
-        dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
280
-    }
250
+	$newurl='';
251
+	if (is_numeric($conf->file->main_force_https))
252
+	{
253
+		if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
254
+		{
255
+			if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
256
+			{
257
+				$newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
258
+			}
259
+		}
260
+		else	// Check HTTPS environment variable (Apache/mod_ssl only)
261
+		{
262
+			$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
263
+		}
264
+	}
265
+	else
266
+	{
267
+		// Check HTTPS environment variable (Apache/mod_ssl only)
268
+		$newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
269
+	}
270
+	// Start redirect
271
+	if ($newurl)
272
+	{
273
+		dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
274
+		header("Location: ".$newurl);
275
+		exit;
276
+	}
277
+	else
278
+	{
279
+		dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
280
+	}
281 281
 }
282 282
 
283 283
 
@@ -288,74 +288,74 @@  discard block
 block discarded – undo
288 288
 // If install or upgrade process not done or not completely finished, we call the install page.
289 289
 if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
290 290
 {
291
-    dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
292
-    header("Location: ".DOL_URL_ROOT."/install/index.php");
293
-    exit;
291
+	dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
292
+	header("Location: ".DOL_URL_ROOT."/install/index.php");
293
+	exit;
294 294
 }
295 295
 // If an upgrade process is required, we call the install page.
296 296
 if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
297 297
 || (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
298 298
 {
299
-    $versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
300
-    require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
301
-    $dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
302
-    $dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
303
-    $rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
304
-    if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
305
-    {
306
-        dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
307
-        header("Location: ".DOL_URL_ROOT."/install/index.php");
308
-        exit;
309
-    }
299
+	$versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
300
+	require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
301
+	$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
302
+	$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
303
+	$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
304
+	if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
305
+	{
306
+		dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
307
+		header("Location: ".DOL_URL_ROOT."/install/index.php");
308
+		exit;
309
+	}
310 310
 }
311 311
 
312 312
 // Creation of a token against CSRF vulnerabilities
313 313
 if (! defined('NOTOKENRENEWAL'))
314 314
 {
315
-    // roulement des jetons car cree a chaque appel
316
-    if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
315
+	// roulement des jetons car cree a chaque appel
316
+	if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
317 317
 
318
-    // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
319
-    $token = dol_hash(uniqid(mt_rand(),TRUE)); // Generates a hash of a random number
320
-    $_SESSION['newtoken'] = $token;
318
+	// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
319
+	$token = dol_hash(uniqid(mt_rand(),TRUE)); // Generates a hash of a random number
320
+	$_SESSION['newtoken'] = $token;
321 321
 }
322 322
 if (! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))	// Check validity of token, only if option enabled (this option breaks some features sometimes)
323 323
 {
324
-    if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
325
-    {
326
-        print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
327
-        print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
328
-        die;
329
-    }
330
-    if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
331
-    {
332
-        if (GETPOST('token', 'alpha') != $_SESSION['token'])
333
-        {
334
-            dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
335
-            //print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
336
-            unset($_POST);
337
-        }
338
-    }
324
+	if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
325
+	{
326
+		print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
327
+		print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
328
+		die;
329
+	}
330
+	if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
331
+	{
332
+		if (GETPOST('token', 'alpha') != $_SESSION['token'])
333
+		{
334
+			dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
335
+			//print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
336
+			unset($_POST);
337
+		}
338
+	}
339 339
 }
340 340
 
341 341
 // Disable modules (this must be after session_start and after conf has been loaded)
342 342
 if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
343 343
 if (! empty($_SESSION["disablemodules"]))
344 344
 {
345
-    $disabled_modules=explode(',',$_SESSION["disablemodules"]);
346
-    foreach($disabled_modules as $module)
347
-    {
348
-        if ($module)
349
-        {
350
-        	if (empty($conf->$module)) $conf->$module=new stdClass();
351
-        	$conf->$module->enabled=false;
352
-        	if ($module == 'fournisseur')		// Special case
353
-        	{
354
-        		$conf->supplier_order->enabled=0;
355
-        		$conf->supplier_invoice->enabled=0;
356
-        	}
357
-        }
358
-    }
345
+	$disabled_modules=explode(',',$_SESSION["disablemodules"]);
346
+	foreach($disabled_modules as $module)
347
+	{
348
+		if ($module)
349
+		{
350
+			if (empty($conf->$module)) $conf->$module=new stdClass();
351
+			$conf->$module->enabled=false;
352
+			if ($module == 'fournisseur')		// Special case
353
+			{
354
+				$conf->supplier_order->enabled=0;
355
+				$conf->supplier_invoice->enabled=0;
356
+			}
357
+		}
358
+	}
359 359
 }
360 360
 
361 361
 
@@ -365,433 +365,433 @@  discard block
 block discarded – undo
365 365
 $login='';
366 366
 if (! defined('NOLOGIN'))
367 367
 {
368
-    // $authmode lists the different means of identification to be tested in order of preference.
369
-    // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser'
370
-
371
-    // Authentication mode
372
-    if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
373
-    // Authentication mode: forceuser
374
-    if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
375
-    // Set authmode
376
-    $authmode=explode(',',$dolibarr_main_authentication);
377
-
378
-    // No authentication mode
379
-    if (! count($authmode))
380
-    {
381
-        $langs->load('main');
382
-        dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
383
-        exit;
384
-    }
385
-
386
-    // If login request was already post, we retrieve login from the session
387
-    // Call module if not realized that his request.
388
-    // At the end of this phase, the variable $login is defined.
389
-    $resultFetchUser='';
390
-    $test=true;
391
-    if (! isset($_SESSION["dol_login"]))
392
-    {
393
-        // It is not already authenticated and it requests the login / password
394
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
395
-
396
-        $dol_dst_observed=GETPOST("dst_observed",'int',3);
397
-        $dol_dst_first=GETPOST("dst_first",'int',3);
398
-        $dol_dst_second=GETPOST("dst_second",'int',3);
399
-        $dol_screenwidth=GETPOST("screenwidth",'int',3);
400
-        $dol_screenheight=GETPOST("screenheight",'int',3);
401
-        $dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
402
-        $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
403
-        $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
404
-        $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
405
-        $dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
406
-        //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
407
-
408
-        // If in demo mode, we check we go to home page through the public/demo/index.php page
409
-        if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
410
-        {
411
-            if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
412
-            {
413
-                dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
414
-                $url='';
415
-                $url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
416
-                $url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
417
-                $url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
418
-                $url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
419
-                $url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
420
-                $url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
421
-                header("Location: ".$url);
422
-                exit;
423
-            }
424
-        }
425
-
426
-        // Verification security graphic code
427
-        if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
428
-        {
429
-            $sessionkey = 'dol_antispam_value';
430
-            $ok=(array_key_exists($sessionkey, $_SESSION) === TRUE && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
431
-
432
-            // Check code
433
-            if (! $ok)
434
-            {
435
-                dol_syslog('Bad value for code, connexion refused');
436
-                $langs->load('main');
437
-                $langs->load('errors');
438
-
439
-                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
440
-                $test=false;
441
-
442
-                // TODO @deprecated Remove this. Hook must be used, not this trigger.
443
-                $user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
444
-                // Call of triggers
445
-                include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
446
-                $interface=new Interfaces($db);
447
-                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
448
-                if ($result < 0) {
449
-                    $error++;
450
-                }
451
-                // End Call of triggers
452
-
453
-                // Hooks on failed login
454
-		        $action='';
455
-		        $hookmanager->initHooks(array('login'));
456
-		        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
457
-		        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
458
-		        if ($reshook < 0) $error++;
459
-
460
-		        // Note: exit is done later
461
-            }
462
-        }
463
-
464
-        $usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",2));
465
-        $passwordtotest	= GETPOST('password','none',2);
466
-        $entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
467
-
468
-        // Define if we received data to test the login.
469
-        $goontestloop=false;
470
-        if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
471
-        if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
472
-        if (GETPOST("username","alpha",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
473
-
474
-        if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
475
-        {
476
-            include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
477
-            $langs=new Translate("",$conf);
478
-    		$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
479
-        	$langs->setDefaultLang($langcode);
480
-        }
481
-
482
-        // Validation of login/pass/entity
483
-        // If ok, the variable login will be returned
484
-        // If error, we will put error message in session under the name dol_loginmesg
485
-        if ($test && $goontestloop)
486
-        {
487
-        	$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
488
-        	if ($login)
489
-            {
490
-                $dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
491
-                $dol_tz=$_POST["tz"];
492
-                $dol_tz_string=$_POST["tz_string"];
493
-                $dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
494
-                $dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
495
-                $dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
496
-                $dol_dst=0;
497
-                if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
498
-                {
499
-                    include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
500
-                    $datenow=dol_now();
501
-                    $datefirst=dol_stringtotime($_POST["dst_first"]);
502
-                    $datesecond=dol_stringtotime($_POST["dst_second"]);
503
-                    if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
504
-                }
505
-                //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
506
-            }
507
-
508
-            if (! $login)
509
-            {
510
-                dol_syslog('Bad password, connexion refused',LOG_DEBUG);
511
-                $langs->load('main');
512
-                $langs->load('errors');
513
-
514
-                // Bad password. No authmode has found a good password.
515
-                // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
516
-                if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
517
-
518
-                // TODO @deprecated Remove this. Hook must be used, not this trigger.
519
-                $user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
520
-                // Call of triggers
521
-                include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
522
-                $interface=new Interfaces($db);
523
-                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
524
-                if ($result < 0) {
525
-                    $error++;
526
-                }
527
-                // End Call of triggers
528
-
529
-                // Hooks on failed login
530
-		        $action='';
531
-		        $hookmanager->initHooks(array('login'));
532
-		        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
533
-		        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
534
-		        if ($reshook < 0) $error++;
535
-
536
-		        // Note: exit is done in next chapter
537
-            }
538
-        }
539
-
540
-        // End test login / passwords
541
-        if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
542
-        {
543
-            // No data to test login, so we show the login page
368
+	// $authmode lists the different means of identification to be tested in order of preference.
369
+	// Example: 'http', 'dolibarr', 'ldap', 'http,forceuser'
370
+
371
+	// Authentication mode
372
+	if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
373
+	// Authentication mode: forceuser
374
+	if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
375
+	// Set authmode
376
+	$authmode=explode(',',$dolibarr_main_authentication);
377
+
378
+	// No authentication mode
379
+	if (! count($authmode))
380
+	{
381
+		$langs->load('main');
382
+		dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
383
+		exit;
384
+	}
385
+
386
+	// If login request was already post, we retrieve login from the session
387
+	// Call module if not realized that his request.
388
+	// At the end of this phase, the variable $login is defined.
389
+	$resultFetchUser='';
390
+	$test=true;
391
+	if (! isset($_SESSION["dol_login"]))
392
+	{
393
+		// It is not already authenticated and it requests the login / password
394
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
395
+
396
+		$dol_dst_observed=GETPOST("dst_observed",'int',3);
397
+		$dol_dst_first=GETPOST("dst_first",'int',3);
398
+		$dol_dst_second=GETPOST("dst_second",'int',3);
399
+		$dol_screenwidth=GETPOST("screenwidth",'int',3);
400
+		$dol_screenheight=GETPOST("screenheight",'int',3);
401
+		$dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
402
+		$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
403
+		$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
404
+		$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
405
+		$dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
406
+		//dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
407
+
408
+		// If in demo mode, we check we go to home page through the public/demo/index.php page
409
+		if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
410
+		{
411
+			if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
412
+			{
413
+				dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
414
+				$url='';
415
+				$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
416
+				$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
417
+				$url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
418
+				$url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
419
+				$url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
420
+				$url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
421
+				header("Location: ".$url);
422
+				exit;
423
+			}
424
+		}
425
+
426
+		// Verification security graphic code
427
+		if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
428
+		{
429
+			$sessionkey = 'dol_antispam_value';
430
+			$ok=(array_key_exists($sessionkey, $_SESSION) === TRUE && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
431
+
432
+			// Check code
433
+			if (! $ok)
434
+			{
435
+				dol_syslog('Bad value for code, connexion refused');
436
+				$langs->load('main');
437
+				$langs->load('errors');
438
+
439
+				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
440
+				$test=false;
441
+
442
+				// TODO @deprecated Remove this. Hook must be used, not this trigger.
443
+				$user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
444
+				// Call of triggers
445
+				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
446
+				$interface=new Interfaces($db);
447
+				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
448
+				if ($result < 0) {
449
+					$error++;
450
+				}
451
+				// End Call of triggers
452
+
453
+				// Hooks on failed login
454
+				$action='';
455
+				$hookmanager->initHooks(array('login'));
456
+				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
457
+				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
458
+				if ($reshook < 0) $error++;
459
+
460
+				// Note: exit is done later
461
+			}
462
+		}
463
+
464
+		$usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",2));
465
+		$passwordtotest	= GETPOST('password','none',2);
466
+		$entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
467
+
468
+		// Define if we received data to test the login.
469
+		$goontestloop=false;
470
+		if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
471
+		if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
472
+		if (GETPOST("username","alpha",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
473
+
474
+		if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
475
+		{
476
+			include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
477
+			$langs=new Translate("",$conf);
478
+			$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
479
+			$langs->setDefaultLang($langcode);
480
+		}
481
+
482
+		// Validation of login/pass/entity
483
+		// If ok, the variable login will be returned
484
+		// If error, we will put error message in session under the name dol_loginmesg
485
+		if ($test && $goontestloop)
486
+		{
487
+			$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
488
+			if ($login)
489
+			{
490
+				$dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
491
+				$dol_tz=$_POST["tz"];
492
+				$dol_tz_string=$_POST["tz_string"];
493
+				$dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
494
+				$dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
495
+				$dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
496
+				$dol_dst=0;
497
+				if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
498
+				{
499
+					include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
500
+					$datenow=dol_now();
501
+					$datefirst=dol_stringtotime($_POST["dst_first"]);
502
+					$datesecond=dol_stringtotime($_POST["dst_second"]);
503
+					if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
504
+				}
505
+				//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
506
+			}
507
+
508
+			if (! $login)
509
+			{
510
+				dol_syslog('Bad password, connexion refused',LOG_DEBUG);
511
+				$langs->load('main');
512
+				$langs->load('errors');
513
+
514
+				// Bad password. No authmode has found a good password.
515
+				// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
516
+				if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
517
+
518
+				// TODO @deprecated Remove this. Hook must be used, not this trigger.
519
+				$user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
520
+				// Call of triggers
521
+				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
522
+				$interface=new Interfaces($db);
523
+				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
524
+				if ($result < 0) {
525
+					$error++;
526
+				}
527
+				// End Call of triggers
528
+
529
+				// Hooks on failed login
530
+				$action='';
531
+				$hookmanager->initHooks(array('login'));
532
+				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
533
+				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
534
+				if ($reshook < 0) $error++;
535
+
536
+				// Note: exit is done in next chapter
537
+			}
538
+		}
539
+
540
+		// End test login / passwords
541
+		if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
542
+		{
543
+			// No data to test login, so we show the login page
544 544
 			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
545 545
 			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
546
-        	else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
547
-            exit;
548
-        }
549
-
550
-        $resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
551
-        if ($resultFetchUser <= 0)
552
-        {
553
-            dol_syslog('User not found, connexion refused');
554
-            session_destroy();
555
-            session_name($sessionname);
556
-            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
557
-            session_start();    // Fixing the bug of register_globals here is useless since session is empty
558
-
559
-            if ($resultFetchUser == 0)
560
-            {
561
-                $langs->load('main');
562
-                $langs->load('errors');
546
+			else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
547
+			exit;
548
+		}
563 549
 
564
-                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
550
+		$resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
551
+		if ($resultFetchUser <= 0)
552
+		{
553
+			dol_syslog('User not found, connexion refused');
554
+			session_destroy();
555
+			session_name($sessionname);
556
+			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
557
+			session_start();    // Fixing the bug of register_globals here is useless since session is empty
565 558
 
566
-                // TODO @deprecated Remove this. Hook must be used, not this trigger.
567
-                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
568
-            }
569
-            if ($resultFetchUser < 0)
570
-            {
571
-                $_SESSION["dol_loginmesg"]=$user->error;
572
-
573
-                // TODO @deprecated Remove this. Hook must be used, not this trigger.
574
-                $user->trigger_mesg=$user->error;
575
-            }
576
-
577
-            // Call triggers
578
-            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
579
-            $interface=new Interfaces($db);
580
-            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
581
-            if ($result < 0) {
582
-                $error++;
583
-            }
584
-            // End call triggers
585
-
586
-	        // Hooks on failed login
587
-	        $action='';
588
-	        $hookmanager->initHooks(array('login'));
589
-	        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
590
-	        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
591
-	        if ($reshook < 0) $error++;
592
-
593
-	        $paramsurl=array();
594
-	        if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
595
-	        if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
596
-	        if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
597
-            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
598
-            exit;
599
-        }
600
-    }
601
-    else
602
-    {
603
-        // We are already into an authenticated session
604
-        $login=$_SESSION["dol_login"];
605
-        $entity=$_SESSION["dol_entity"];
606
-        dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
607
-
608
-        $resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
609
-        if ($resultFetchUser <= 0)
610
-        {
611
-            // Account has been removed after login
612
-            dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
613
-            session_destroy();
614
-            session_name($sessionname);
615
-            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
616
-            session_start();    // Fixing the bug of register_globals here is useless since session is empty
617
-
618
-            if ($resultFetchUser == 0)
619
-            {
620
-                $langs->load('main');
621
-                $langs->load('errors');
559
+			if ($resultFetchUser == 0)
560
+			{
561
+				$langs->load('main');
562
+				$langs->load('errors');
622 563
 
623
-                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
564
+				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
624 565
 
625
-                // TODO @deprecated Remove this. Hook must be used, not this trigger.
626
-                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
627
-            }
628
-            if ($resultFetchUser < 0)
629
-            {
630
-                $_SESSION["dol_loginmesg"]=$user->error;
631
-
632
-                // TODO @deprecated Remove this. Hook must be used, not this trigger.
633
-                $user->trigger_mesg=$user->error;
634
-            }
635
-
636
-            // TODO @deprecated Remove this. Hook must be used, not this trigger.
637
-            // Call triggers
638
-            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
639
-            $interface=new Interfaces($db);
640
-            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
641
-            if ($result < 0) {
642
-                $error++;
643
-            }
644
-            // End call triggers
645
-
646
-	        // Hooks on failed login
647
-	        $action='';
648
-	        $hookmanager->initHooks(array('login'));
649
-	        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
650
-	        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
651
-	        if ($reshook < 0) $error++;
652
-
653
-	        $paramsurl=array();
654
-	        if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
655
-	        if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
656
-	        if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
657
-            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
658
-            exit;
659
-        }
660
-        else
566
+				// TODO @deprecated Remove this. Hook must be used, not this trigger.
567
+				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
568
+			}
569
+			if ($resultFetchUser < 0)
570
+			{
571
+				$_SESSION["dol_loginmesg"]=$user->error;
572
+
573
+				// TODO @deprecated Remove this. Hook must be used, not this trigger.
574
+				$user->trigger_mesg=$user->error;
575
+			}
576
+
577
+			// Call triggers
578
+			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
579
+			$interface=new Interfaces($db);
580
+			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
581
+			if ($result < 0) {
582
+				$error++;
583
+			}
584
+			// End call triggers
585
+
586
+			// Hooks on failed login
587
+			$action='';
588
+			$hookmanager->initHooks(array('login'));
589
+			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
590
+			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
591
+			if ($reshook < 0) $error++;
592
+
593
+			$paramsurl=array();
594
+			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
595
+			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
596
+			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
597
+			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
598
+			exit;
599
+		}
600
+	}
601
+	else
602
+	{
603
+		// We are already into an authenticated session
604
+		$login=$_SESSION["dol_login"];
605
+		$entity=$_SESSION["dol_entity"];
606
+		dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
607
+
608
+		$resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
609
+		if ($resultFetchUser <= 0)
661 610
 		{
662
-	       // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
663
-	       $hookmanager->initHooks(array('main'));
664
-
665
-	       // Code for search criteria persistence.
666
-	       if (! empty($_GET['save_lastsearch_values']))    // Keep $_GET here
667
-	       {
668
-               $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
669
-               $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
670
-               // Clean $relativepathstring
671
-   	           if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
672
-               $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
673
-               $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
674
-               //var_dump($relativepathstring);
675
-
676
-               if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
677
-               {
678
-                   $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
679
-                   unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
680
-               }
681
-	       }
682
-
683
-	       $action = '';
684
-	       $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
685
-	       if ($reshook < 0) {
686
-		       setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
687
-	       }
688
-        }
689
-    }
690
-
691
-    // Is it a new session that has started ?
692
-    // If we are here, this means authentication was successfull.
693
-    if (! isset($_SESSION["dol_login"]))
694
-    {
695
-        // New session for this login has started.
696
-    	$error=0;
697
-
698
-    	// Store value into session (values always stored)
699
-        $_SESSION["dol_login"]=$user->login;
700
-        $_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
701
-        $_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
702
-        $_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
703
-        $_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
704
-        $_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
705
-        $_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
706
-        $_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
707
-        $_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
708
-        $_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
709
-        $_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
710
-        $_SESSION["dol_entity"]=$conf->entity;
711
-    	// Store value into session (values stored only if defined)
712
-        if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
713
-        if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
714
-        if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
715
-        if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
716
-        if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
717
-
718
-        dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
719
-
720
-        $db->begin();
721
-
722
-        $user->update_last_login_date();
723
-
724
-        $loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
725
-
726
-        // TODO @deprecated Remove this. Hook must be used, not this trigger.
727
-        $user->trigger_mesg = $loginfo;
728
-        // Call triggers
729
-        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
730
-        $interface=new Interfaces($db);
731
-        $result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
732
-        if ($result < 0) {
733
-            $error++;
734
-        }
735
-        // End call triggers
736
-
737
-        // Hooks on successfull login
738
-        $action='';
739
-        $hookmanager->initHooks(array('login'));
740
-        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
741
-        $reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
742
-        if ($reshook < 0) $error++;
743
-
744
-        if ($error)
745
-        {
746
-            $db->rollback();
747
-            session_destroy();
748
-            dol_print_error($db,'Error in some hooks afterLogin (or old trigger USER_LOGIN)');
749
-            exit;
750
-        }
751
-        else
611
+			// Account has been removed after login
612
+			dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
613
+			session_destroy();
614
+			session_name($sessionname);
615
+			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
616
+			session_start();    // Fixing the bug of register_globals here is useless since session is empty
617
+
618
+			if ($resultFetchUser == 0)
619
+			{
620
+				$langs->load('main');
621
+				$langs->load('errors');
622
+
623
+				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
624
+
625
+				// TODO @deprecated Remove this. Hook must be used, not this trigger.
626
+				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
627
+			}
628
+			if ($resultFetchUser < 0)
629
+			{
630
+				$_SESSION["dol_loginmesg"]=$user->error;
631
+
632
+				// TODO @deprecated Remove this. Hook must be used, not this trigger.
633
+				$user->trigger_mesg=$user->error;
634
+			}
635
+
636
+			// TODO @deprecated Remove this. Hook must be used, not this trigger.
637
+			// Call triggers
638
+			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
639
+			$interface=new Interfaces($db);
640
+			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
641
+			if ($result < 0) {
642
+				$error++;
643
+			}
644
+			// End call triggers
645
+
646
+			// Hooks on failed login
647
+			$action='';
648
+			$hookmanager->initHooks(array('login'));
649
+			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
650
+			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
651
+			if ($reshook < 0) $error++;
652
+
653
+			$paramsurl=array();
654
+			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
655
+			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
656
+			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
657
+			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
658
+			exit;
659
+		}
660
+		else
752 661
 		{
753
-            $db->commit();
754
-        }
755
-
756
-        // Change landing page if defined.
757
-        $landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
758
-        if (! empty($landingpage))    // Example: /index.php
759
-        {
760
-            $newpath=dol_buildpath($landingpage, 1);
761
-            if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
762
-            {
763
-                header('Location: '.$newpath);
764
-                exit;
765
-            }
766
-        }
767
-    }
768
-
769
-
770
-    // If user admin, we force the rights-based modules
771
-    if ($user->admin)
772
-    {
773
-        $user->rights->user->user->lire=1;
774
-        $user->rights->user->user->creer=1;
775
-        $user->rights->user->user->password=1;
776
-        $user->rights->user->user->supprimer=1;
777
-        $user->rights->user->self->creer=1;
778
-        $user->rights->user->self->password=1;
779
-    }
780
-
781
-    /*
662
+		   // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
663
+		   $hookmanager->initHooks(array('main'));
664
+
665
+		   // Code for search criteria persistence.
666
+		   if (! empty($_GET['save_lastsearch_values']))    // Keep $_GET here
667
+		   {
668
+			   $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
669
+			   $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
670
+			   // Clean $relativepathstring
671
+   			   if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
672
+			   $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
673
+			   $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
674
+			   //var_dump($relativepathstring);
675
+
676
+			   if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
677
+			   {
678
+				   $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
679
+				   unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
680
+			   }
681
+		   }
682
+
683
+		   $action = '';
684
+		   $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
685
+		   if ($reshook < 0) {
686
+			   setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
687
+		   }
688
+		}
689
+	}
690
+
691
+	// Is it a new session that has started ?
692
+	// If we are here, this means authentication was successfull.
693
+	if (! isset($_SESSION["dol_login"]))
694
+	{
695
+		// New session for this login has started.
696
+		$error=0;
697
+
698
+		// Store value into session (values always stored)
699
+		$_SESSION["dol_login"]=$user->login;
700
+		$_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
701
+		$_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
702
+		$_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
703
+		$_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
704
+		$_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
705
+		$_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
706
+		$_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
707
+		$_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
708
+		$_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
709
+		$_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
710
+		$_SESSION["dol_entity"]=$conf->entity;
711
+		// Store value into session (values stored only if defined)
712
+		if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
713
+		if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
714
+		if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
715
+		if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
716
+		if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
717
+
718
+		dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
719
+
720
+		$db->begin();
721
+
722
+		$user->update_last_login_date();
723
+
724
+		$loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
725
+
726
+		// TODO @deprecated Remove this. Hook must be used, not this trigger.
727
+		$user->trigger_mesg = $loginfo;
728
+		// Call triggers
729
+		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
730
+		$interface=new Interfaces($db);
731
+		$result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
732
+		if ($result < 0) {
733
+			$error++;
734
+		}
735
+		// End call triggers
736
+
737
+		// Hooks on successfull login
738
+		$action='';
739
+		$hookmanager->initHooks(array('login'));
740
+		$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
741
+		$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
742
+		if ($reshook < 0) $error++;
743
+
744
+		if ($error)
745
+		{
746
+			$db->rollback();
747
+			session_destroy();
748
+			dol_print_error($db,'Error in some hooks afterLogin (or old trigger USER_LOGIN)');
749
+			exit;
750
+		}
751
+		else
752
+		{
753
+			$db->commit();
754
+		}
755
+
756
+		// Change landing page if defined.
757
+		$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
758
+		if (! empty($landingpage))    // Example: /index.php
759
+		{
760
+			$newpath=dol_buildpath($landingpage, 1);
761
+			if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
762
+			{
763
+				header('Location: '.$newpath);
764
+				exit;
765
+			}
766
+		}
767
+	}
768
+
769
+
770
+	// If user admin, we force the rights-based modules
771
+	if ($user->admin)
772
+	{
773
+		$user->rights->user->user->lire=1;
774
+		$user->rights->user->user->creer=1;
775
+		$user->rights->user->user->password=1;
776
+		$user->rights->user->user->supprimer=1;
777
+		$user->rights->user->self->creer=1;
778
+		$user->rights->user->self->password=1;
779
+	}
780
+
781
+	/*
782 782
      * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)
783 783
      */
784 784
 
785
-    // Set liste_limit
786
-    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
787
-    if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
785
+	// Set liste_limit
786
+	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
787
+	if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
788 788
 
789
-    // Replace conf->css by personalized value if theme not forced
790
-    if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
791
-    {
792
-        $conf->theme=$user->conf->MAIN_THEME;
793
-        $conf->css  = "/theme/".$conf->theme."/style.css.php";
794
-    }
789
+	// Replace conf->css by personalized value if theme not forced
790
+	if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
791
+	{
792
+		$conf->theme=$user->conf->MAIN_THEME;
793
+		$conf->css  = "/theme/".$conf->theme."/style.css.php";
794
+	}
795 795
 }
796 796
 
797 797
 // Case forcing style from url
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
815 815
 if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
816 816
 {
817
-    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
817
+	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
818 818
 }
819 819
 
820 820
 // Set terminal output option according to conf->browser.
@@ -843,39 +843,39 @@  discard block
 block discarded – undo
843 843
 
844 844
 if (! defined('NOREQUIRETRAN'))
845 845
 {
846
-    if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
847
-    {
848
-        // If user has chosen its own language
849
-        if (! empty($user->conf->MAIN_LANG_DEFAULT))
850
-        {
851
-            // If different than current language
852
-            //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
853
-            if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
854
-            {
855
-                $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
856
-            }
857
-        }
858
-    }
846
+	if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
847
+	{
848
+		// If user has chosen its own language
849
+		if (! empty($user->conf->MAIN_LANG_DEFAULT))
850
+		{
851
+			// If different than current language
852
+			//print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
853
+			if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
854
+			{
855
+				$langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
856
+			}
857
+		}
858
+	}
859 859
 }
860 860
 
861 861
 if (! defined('NOLOGIN'))
862 862
 {
863
-    // If the login is not recovered, it is identified with an account that does not exist.
864
-    // Hacking attempt?
865
-    if (! $user->login) accessforbidden();
866
-
867
-    // Check if user is active
868
-    if ($user->statut < 1)
869
-    {
870
-        // If not active, we refuse the user
871
-        $langs->load("other");
872
-        dol_syslog("Authentification ko as login is disabled");
873
-        accessforbidden($langs->trans("ErrorLoginDisabled"));
874
-        exit;
875
-    }
876
-
877
-    // Load permissions
878
-    $user->getrights();
863
+	// If the login is not recovered, it is identified with an account that does not exist.
864
+	// Hacking attempt?
865
+	if (! $user->login) accessforbidden();
866
+
867
+	// Check if user is active
868
+	if ($user->statut < 1)
869
+	{
870
+		// If not active, we refuse the user
871
+		$langs->load("other");
872
+		dol_syslog("Authentification ko as login is disabled");
873
+		accessforbidden($langs->trans("ErrorLoginDisabled"));
874
+		exit;
875
+	}
876
+
877
+	// Load permissions
878
+	$user->getrights();
879 879
 }
880 880
 
881 881
 
@@ -886,8 +886,8 @@  discard block
 block discarded – undo
886 886
 // Load main languages files
887 887
 if (! defined('NOREQUIRETRAN'))
888 888
 {
889
-    $langs->load("main");
890
-    $langs->load("dict");
889
+	$langs->load("main");
890
+	$langs->load("dict");
891 891
 }
892 892
 
893 893
 // Define some constants used for style of arrays
@@ -904,27 +904,27 @@  discard block
 block discarded – undo
904 904
 // Constants used to defined number of lines in textarea
905 905
 if (empty($conf->browser->firefox))
906 906
 {
907
-    define('ROWS_1',1);
908
-    define('ROWS_2',2);
909
-    define('ROWS_3',3);
910
-    define('ROWS_4',4);
911
-    define('ROWS_5',5);
912
-    define('ROWS_6',6);
913
-    define('ROWS_7',7);
914
-    define('ROWS_8',8);
915
-    define('ROWS_9',9);
907
+	define('ROWS_1',1);
908
+	define('ROWS_2',2);
909
+	define('ROWS_3',3);
910
+	define('ROWS_4',4);
911
+	define('ROWS_5',5);
912
+	define('ROWS_6',6);
913
+	define('ROWS_7',7);
914
+	define('ROWS_8',8);
915
+	define('ROWS_9',9);
916 916
 }
917 917
 else
918 918
 {
919
-    define('ROWS_1',0);
920
-    define('ROWS_2',1);
921
-    define('ROWS_3',2);
922
-    define('ROWS_4',3);
923
-    define('ROWS_5',4);
924
-    define('ROWS_6',5);
925
-    define('ROWS_7',6);
926
-    define('ROWS_8',7);
927
-    define('ROWS_9',8);
919
+	define('ROWS_1',0);
920
+	define('ROWS_2',1);
921
+	define('ROWS_3',2);
922
+	define('ROWS_4',3);
923
+	define('ROWS_5',4);
924
+	define('ROWS_6',5);
925
+	define('ROWS_7',6);
926
+	define('ROWS_8',7);
927
+	define('ROWS_9',8);
928 928
 }
929 929
 
930 930
 $heightforframes=48;
@@ -970,31 +970,31 @@  discard block
 block discarded – undo
970 970
 
971 971
 if (! function_exists("llxHeader"))
972 972
 {
973
-    /**
974
-     *	Show HTML header HTML + BODY + Top menu + left menu + DIV
975
-     *
976
-     * @param 	string 	$head				Optionnal head lines
977
-     * @param 	string 	$title				HTML title
978
-     * @param	string	$help_url			Url links to help page
979
-     * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
980
-     *                                  	For other external page: http://server/url
981
-     * @param	string	$target				Target to use on links
982
-     * @param 	int    	$disablejs			More content into html header
983
-     * @param 	int    	$disablehead		More content into html header
984
-     * @param 	array  	$arrayofjs			Array of complementary js files
985
-     * @param 	array  	$arrayofcss			Array of complementary css files
986
-     * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (use only if autodetect fails)
987
-     * @param   string  $morecssonbody      More CSS on body tag.
988
-     * @return	void
989
-     */
973
+	/**
974
+	 *	Show HTML header HTML + BODY + Top menu + left menu + DIV
975
+	 *
976
+	 * @param 	string 	$head				Optionnal head lines
977
+	 * @param 	string 	$title				HTML title
978
+	 * @param	string	$help_url			Url links to help page
979
+	 * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
980
+	 *                                  	For other external page: http://server/url
981
+	 * @param	string	$target				Target to use on links
982
+	 * @param 	int    	$disablejs			More content into html header
983
+	 * @param 	int    	$disablehead		More content into html header
984
+	 * @param 	array  	$arrayofjs			Array of complementary js files
985
+	 * @param 	array  	$arrayofcss			Array of complementary css files
986
+	 * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (use only if autodetect fails)
987
+	 * @param   string  $morecssonbody      More CSS on body tag.
988
+	 * @return	void
989
+	 */
990 990
 	function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='')
991 991
 	{
992
-	    global $conf;
992
+		global $conf;
993 993
 
994
-	    // html header
994
+		// html header
995 995
 		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
996 996
 
997
-        print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
997
+		print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
998 998
 
999 999
 		// top menu and left menu area
1000 1000
 		if (empty($conf->dol_hide_topmenu))
@@ -1021,25 +1021,25 @@  discard block
 block discarded – undo
1021 1021
  */
1022 1022
 function top_httphead($contenttype='text/html')
1023 1023
 {
1024
-    global $conf;
1025
-
1026
-    if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1027
-    else header("Content-Type: ".$contenttype);
1028
-    // Security options
1029
-    header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1030
-    header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1031
-    if (! empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1032
-    {
1033
-        // For example, to restrict script, object, frames or img to some domains
1034
-        // script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; child-src https://youtube.com; img-src: https://static.example.com
1035
-        // For example, to restrict everything to one domain, except object, ...
1036
-        // default-src https://cdn.example.net; object-src 'none'
1037
-        header("Content-Security-Policy: ".$conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY);
1038
-    }
1039
-
1040
-
1041
-    // On the fly GZIP compression for all pages (if browser support it). Must set the bit 3 of constant to 1.
1042
-    /*if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x04)) {
1024
+	global $conf;
1025
+
1026
+	if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1027
+	else header("Content-Type: ".$contenttype);
1028
+	// Security options
1029
+	header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1030
+	header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1031
+	if (! empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1032
+	{
1033
+		// For example, to restrict script, object, frames or img to some domains
1034
+		// script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; child-src https://youtube.com; img-src: https://static.example.com
1035
+		// For example, to restrict everything to one domain, except object, ...
1036
+		// default-src https://cdn.example.net; object-src 'none'
1037
+		header("Content-Security-Policy: ".$conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY);
1038
+	}
1039
+
1040
+
1041
+	// On the fly GZIP compression for all pages (if browser support it). Must set the bit 3 of constant to 1.
1042
+	/*if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x04)) {
1043 1043
         ob_start("ob_gzhandler");
1044 1044
     }*/
1045 1045
 }
@@ -1060,206 +1060,206 @@  discard block
 block discarded – undo
1060 1060
  */
1061 1061
 function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)
1062 1062
 {
1063
-    global $user, $conf, $langs, $db;
1064
-
1065
-    top_httphead();
1066
-
1067
-    if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1068
-
1069
-    if (! empty($conf->global->MAIN_ACTIVATE_HTML4)) {
1070
-        $doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
1071
-    }else {
1072
-        $doctype = '<!doctype html>';
1073
-    }
1074
-    print $doctype."\n";
1075
-    if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1076
-    else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1077
-    //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1078
-    if (empty($disablehead))
1079
-    {
1080
-        print "<head>\n";
1063
+	global $user, $conf, $langs, $db;
1064
+
1065
+	top_httphead();
1066
+
1067
+	if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1068
+
1069
+	if (! empty($conf->global->MAIN_ACTIVATE_HTML4)) {
1070
+		$doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
1071
+	}else {
1072
+		$doctype = '<!doctype html>';
1073
+	}
1074
+	print $doctype."\n";
1075
+	if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1076
+	else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1077
+	//print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1078
+	if (empty($disablehead))
1079
+	{
1080
+		print "<head>\n";
1081 1081
 		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1082
-        // Displays meta
1083
-        print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";      				// Do not index
1084
-        print '<meta name="viewport" content="width=device-width, initial-scale=1.0">';	// Scale for mobile device
1085
-        print '<meta name="author" content="Dolibarr Development Team">'."\n";
1086
-        // Favicon
1082
+		// Displays meta
1083
+		print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";      				// Do not index
1084
+		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">';	// Scale for mobile device
1085
+		print '<meta name="author" content="Dolibarr Development Team">'."\n";
1086
+		// Favicon
1087 1087
 		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1088
-        if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1089
-        if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1090
-        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1091
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1092
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1093
-
1094
-        // Displays title
1095
-        $appli=constant('DOL_APPLICATION_TITLE');
1096
-        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1097
-
1098
-        if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';
1099
-        else if ($title) print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';
1100
-        else print "<title>".dol_htmlentities($appli)."</title>";
1101
-        print "\n";
1102
-
1103
-        //$ext='';
1104
-        //if (! empty($conf->dol_use_jmobile)) $ext='version='.urlencode(DOL_VERSION);
1105
-        $ext='version='.urlencode(DOL_VERSION);
1106
-
1107
-        if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1108
-        if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1109
-
1110
-        $themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1111
-        $themeparam.=($ext?'&amp;'.$ext:'');
1112
-        if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1113
-        if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1114
-        if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1115
-        if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1116
-        if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1117
-        if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1118
-
1119
-        if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1120
-        {
1121
-            print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1122
-            $jquerytheme = 'smoothness';
1123
-            if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1124
-            if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1125
-            else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1126
-            if (! defined('DISABLE_JQUERY_TIPTIP')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/tipTip.css'.($ext?'?'.$ext:'').'">'."\n";                           // Tooltip
1127
-            if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1128
-            /* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
1088
+		if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1089
+		if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1090
+		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1091
+		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1092
+		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1093
+
1094
+		// Displays title
1095
+		$appli=constant('DOL_APPLICATION_TITLE');
1096
+		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1097
+
1098
+		if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';
1099
+		else if ($title) print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';
1100
+		else print "<title>".dol_htmlentities($appli)."</title>";
1101
+		print "\n";
1102
+
1103
+		//$ext='';
1104
+		//if (! empty($conf->dol_use_jmobile)) $ext='version='.urlencode(DOL_VERSION);
1105
+		$ext='version='.urlencode(DOL_VERSION);
1106
+
1107
+		if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1108
+		if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1109
+
1110
+		$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1111
+		$themeparam.=($ext?'&amp;'.$ext:'');
1112
+		if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1113
+		if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1114
+		if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1115
+		if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1116
+		if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1117
+		if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1118
+
1119
+		if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1120
+		{
1121
+			print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1122
+			$jquerytheme = 'smoothness';
1123
+			if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1124
+			if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1125
+			else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1126
+			if (! defined('DISABLE_JQUERY_TIPTIP')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/tipTip.css'.($ext?'?'.$ext:'').'">'."\n";                           // Tooltip
1127
+			if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1128
+			/* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
1129 1129
             if (! empty($conf->global->MAIN_USE_JQUERY_DATATABLES) || (defined('REQUIRE_JQUERY_DATATABLES') && constant('REQUIRE_JQUERY_DATATABLES')))     // jQuery datatables
1130 1130
             {
1131 1131
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/media/css/jquery.dataTables.min.css'.($ext?'?'.$ext:'').'">'."\n";
1132 1132
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/Buttons/css/buttons.dataTables.min.css'.($ext?'?'.$ext:'').'">'."\n";
1133 1133
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/ColReorder/css/colReorder.dataTables.min.css'.($ext?'?'.$ext:'').'"></script>'."\n";
1134 1134
             }*/
1135
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1136
-            {
1137
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1138
-            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1139
-            }
1140
-            // jQuery Timepicker
1141
-            if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1142
-            {
1143
-            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.css'.($ext?'?'.$ext:'').'">'."\n";
1144
-            }
1145
-        }
1146
-
1147
-        if (! defined('DISABLE_FONT_AWSOME'))
1148
-        {
1149
-            print '<!-- Includes CSS for font awesome -->'."\n";
1150
-            print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1151
-        }
1152
-
1153
-        print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1154
-        // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1155
-        $themepath=dol_buildpath($conf->css,1);
1156
-        $themesubdir='';
1157
-        if (! empty($conf->modules_parts['theme']))	// This slow down
1158
-        {
1159
-	        foreach($conf->modules_parts['theme'] as $reldir)
1160
-	        {
1161
-	        	if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1162
-	        	{
1135
+			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1136
+			{
1137
+				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1138
+				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1139
+			}
1140
+			// jQuery Timepicker
1141
+			if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1142
+			{
1143
+				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.css'.($ext?'?'.$ext:'').'">'."\n";
1144
+			}
1145
+		}
1146
+
1147
+		if (! defined('DISABLE_FONT_AWSOME'))
1148
+		{
1149
+			print '<!-- Includes CSS for font awesome -->'."\n";
1150
+			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1151
+		}
1152
+
1153
+		print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1154
+		// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1155
+		$themepath=dol_buildpath($conf->css,1);
1156
+		$themesubdir='';
1157
+		if (! empty($conf->modules_parts['theme']))	// This slow down
1158
+		{
1159
+			foreach($conf->modules_parts['theme'] as $reldir)
1160
+			{
1161
+				if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1162
+				{
1163 1163
 					$themepath=dol_buildpath($reldir.$conf->css, 1);
1164 1164
 					$themesubdir=$reldir;
1165 1165
 					break;
1166
-	        	}
1167
-	        }
1168
-        }
1169
-        //print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1170
-        print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1171
-	    if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1172
-
1173
-        // CSS forced by modules (relative url starting with /)
1174
-        if (! empty($conf->modules_parts['css']))
1175
-        {
1176
-        	$arraycss=(array) $conf->modules_parts['css'];
1177
-        	foreach($arraycss as $modcss => $filescss)
1178
-        	{
1179
-        		$filescss=(array) $filescss;	// To be sure filecss is an array
1180
-        		foreach($filescss as $cssfile)
1181
-        		{
1182
-        			if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1183
-        			// cssfile is a relative path
1184
-	        		print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1185
-	        		// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1186
-	        		if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1187
-	        		print '">'."\n";
1188
-        		}
1189
-        	}
1190
-        }
1191
-        // CSS forced by page in top_htmlhead call (relative url starting with /)
1192
-        if (is_array($arrayofcss))
1193
-        {
1194
-            foreach($arrayofcss as $cssfile)
1195
-            {
1196
-            	print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1197
-                // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1198
-                if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1199
-                print '">'."\n";
1200
-            }
1201
-        }
1202
-
1203
-        // Output standard javascript links
1204
-        if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1205
-        {
1206
-            // JQuery. Must be before other includes
1207
-            print '<!-- Includes JS for JQuery -->'."\n";
1208
-            if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1209
-            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1210
-            if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1211
-            {
1212
-                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1213
-                else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1214
-            }
1215
-            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1216
-            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1217
-            if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.0.6.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1218
-            if (! defined('DISABLE_JQUERY_TIPTIP')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/jquery.tipTip.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1219
-            // jQuery jnotify
1220
-            if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1221
-            {
1222
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1223
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/jnotify.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1224
-            }
1225
-            // Flot
1226
-            if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1227
-            {
1228
-                if (constant('JS_JQUERY_FLOT'))
1229
-                {
1230
-                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1231
-                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1232
-                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1233
-                }
1234
-                else
1235
-                {
1236
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1237
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1238
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1239
-                }
1240
-            }
1241
-            // jQuery jeditable
1242
-            if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1243
-            {
1244
-            	print '<!-- JS to manage editInPlace feature -->'."\n";
1245
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1246
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1247
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1248
-                print '<script type="text/javascript">'."\n";
1249
-                print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1250
-                print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1251
-                print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1252
-                print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1253
-                print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1254
-                print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1255
-                print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1256
-                print 'var withInPlace = 300;';		// width in pixel for default string edit
1257
-                print '</script>'."\n";
1258
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1259
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1260
-            }
1261
-            // jQuery DataTables
1262
-            /* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
1166
+				}
1167
+			}
1168
+		}
1169
+		//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1170
+		print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1171
+		if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1172
+
1173
+		// CSS forced by modules (relative url starting with /)
1174
+		if (! empty($conf->modules_parts['css']))
1175
+		{
1176
+			$arraycss=(array) $conf->modules_parts['css'];
1177
+			foreach($arraycss as $modcss => $filescss)
1178
+			{
1179
+				$filescss=(array) $filescss;	// To be sure filecss is an array
1180
+				foreach($filescss as $cssfile)
1181
+				{
1182
+					if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1183
+					// cssfile is a relative path
1184
+					print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1185
+					// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1186
+					if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1187
+					print '">'."\n";
1188
+				}
1189
+			}
1190
+		}
1191
+		// CSS forced by page in top_htmlhead call (relative url starting with /)
1192
+		if (is_array($arrayofcss))
1193
+		{
1194
+			foreach($arrayofcss as $cssfile)
1195
+			{
1196
+				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1197
+				// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1198
+				if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1199
+				print '">'."\n";
1200
+			}
1201
+		}
1202
+
1203
+		// Output standard javascript links
1204
+		if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1205
+		{
1206
+			// JQuery. Must be before other includes
1207
+			print '<!-- Includes JS for JQuery -->'."\n";
1208
+			if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1209
+			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1210
+			if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1211
+			{
1212
+				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1213
+				else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1214
+			}
1215
+			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1216
+			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1217
+			if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.0.6.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1218
+			if (! defined('DISABLE_JQUERY_TIPTIP')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/jquery.tipTip.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1219
+			// jQuery jnotify
1220
+			if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1221
+			{
1222
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1223
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/jnotify.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1224
+			}
1225
+			// Flot
1226
+			if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1227
+			{
1228
+				if (constant('JS_JQUERY_FLOT'))
1229
+				{
1230
+					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1231
+					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1232
+					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1233
+				}
1234
+				else
1235
+				{
1236
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1237
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1238
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1239
+				}
1240
+			}
1241
+			// jQuery jeditable
1242
+			if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1243
+			{
1244
+				print '<!-- JS to manage editInPlace feature -->'."\n";
1245
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1246
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1247
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1248
+				print '<script type="text/javascript">'."\n";
1249
+				print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1250
+				print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1251
+				print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1252
+				print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1253
+				print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1254
+				print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1255
+				print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1256
+				print 'var withInPlace = 300;';		// width in pixel for default string edit
1257
+				print '</script>'."\n";
1258
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1259
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1260
+			}
1261
+			// jQuery DataTables
1262
+			/* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
1263 1263
             if (! empty($conf->global->MAIN_USE_JQUERY_DATATABLES) || (defined('REQUIRE_JQUERY_DATATABLES') && constant('REQUIRE_JQUERY_DATATABLES')))
1264 1264
             {
1265 1265
                 print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/media/js/jquery.dataTables.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
@@ -1271,103 +1271,103 @@  discard block
 block discarded – undo
1271 1271
                 print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/ColReorder/js/dataTables.colReorder.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1272 1272
                 print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jszip/jszip.min.js"></script>'."\n";
1273 1273
             }*/
1274
-            // jQuery Timepicker
1275
-            if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1276
-            {
1277
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1278
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1279
-            }
1280
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1281
-            {
1282
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1283
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1284
-            }
1285
-        }
1286
-
1287
-        if (! $disablejs && ! empty($conf->use_javascript_ajax))
1288
-        {
1289
-            // CKEditor
1290
-            if (! empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && ! defined('DISABLE_CKEDITOR'))
1291
-            {
1292
-                print '<!-- Includes JS for CKEditor -->'."\n";
1293
-                $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
1294
-                $jsckeditor='ckeditor.js';
1295
-                if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1296
-                {
1297
-                	$pathckeditor=constant('JS_CKEDITOR');
1298
-                }
1299
-                print '<script type="text/javascript">';
1300
-                print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1301
-                print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\';'."\n";		// $themesubdir='' in standard usage
1302
-                print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1303
-                print 'var ckeditorFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1304
-                print '</script>'."\n";
1305
-                print '<script type="text/javascript" src="'.$pathckeditor.$jsckeditor.($ext?'?'.$ext:'').'"></script>'."\n";
1306
-            }
1307
-
1308
-            // Browser notifications
1309
-            if (! defined('DISABLE_BROWSER_NOTIF'))
1310
-            {
1311
-                $enablebrowsernotif=false;
1312
-                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;
1313
-                if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
1314
-                if ($enablebrowsernotif)
1315
-                {
1316
-                    print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
1317
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext?'?'.$ext:'').'"></script>'."\n";
1318
-                }
1319
-            }
1320
-
1321
-            // Global js function
1322
-            print '<!-- Includes JS of Dolibarr -->'."\n";
1323
-            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1324
-
1325
-            // Add datepicker default options
1326
-            /*if (! defined('DISABLE_DATE_PICKER'))
1274
+			// jQuery Timepicker
1275
+			if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1276
+			{
1277
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1278
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1279
+			}
1280
+			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1281
+			{
1282
+				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1283
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1284
+			}
1285
+		}
1286
+
1287
+		if (! $disablejs && ! empty($conf->use_javascript_ajax))
1288
+		{
1289
+			// CKEditor
1290
+			if (! empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && ! defined('DISABLE_CKEDITOR'))
1291
+			{
1292
+				print '<!-- Includes JS for CKEditor -->'."\n";
1293
+				$pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
1294
+				$jsckeditor='ckeditor.js';
1295
+				if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1296
+				{
1297
+					$pathckeditor=constant('JS_CKEDITOR');
1298
+				}
1299
+				print '<script type="text/javascript">';
1300
+				print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1301
+				print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\';'."\n";		// $themesubdir='' in standard usage
1302
+				print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1303
+				print 'var ckeditorFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1304
+				print '</script>'."\n";
1305
+				print '<script type="text/javascript" src="'.$pathckeditor.$jsckeditor.($ext?'?'.$ext:'').'"></script>'."\n";
1306
+			}
1307
+
1308
+			// Browser notifications
1309
+			if (! defined('DISABLE_BROWSER_NOTIF'))
1310
+			{
1311
+				$enablebrowsernotif=false;
1312
+				if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;
1313
+				if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
1314
+				if ($enablebrowsernotif)
1315
+				{
1316
+					print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
1317
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext?'?'.$ext:'').'"></script>'."\n";
1318
+				}
1319
+			}
1320
+
1321
+			// Global js function
1322
+			print '<!-- Includes JS of Dolibarr -->'."\n";
1323
+			print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1324
+
1325
+			// Add datepicker default options
1326
+			/*if (! defined('DISABLE_DATE_PICKER'))
1327 1327
             {
1328 1328
                 print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/datepicker.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
1329 1329
             }*/
1330 1330
 
1331
-            // JS forced by modules (relative url starting with /)
1332
-            if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1333
-        	{
1334
-        		$arrayjs=(array) $conf->modules_parts['js'];
1335
-	            foreach($arrayjs as $modjs => $filesjs)
1336
-	            {
1337
-        			$filesjs=(array) $filesjs;	// To be sure filejs is an array
1338
-		            foreach($filesjs as $jsfile)
1339
-		            {
1340
-	    	    		// jsfile is a relative path
1341
-	        	    	print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1342
-		            }
1343
-	            }
1344
-        	}
1345
-            // JS forced by page in top_htmlhead (relative url starting with /)
1346
-            if (is_array($arrayofjs))
1347
-            {
1348
-                print '<!-- Includes JS added by page -->'."\n";
1349
-                foreach($arrayofjs as $jsfile)
1350
-                {
1351
-                    if (preg_match('/^http/i',$jsfile))
1352
-                    {
1353
-                        print '<script type="text/javascript" src="'.$jsfile.'"></script>'."\n";
1354
-                    }
1355
-                    else
1356
-                    {
1357
-                        if (! preg_match('/^\//',$jsfile)) $jsfile='/'.$jsfile;	// For backward compatibility
1358
-                        print '<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1359
-                    }
1360
-                }
1361
-            }
1362
-        }
1363
-
1364
-        if (! empty($head)) print $head."\n";
1365
-        if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1366
-
1367
-        print "</head>\n\n";
1368
-    }
1369
-
1370
-    $conf->headerdone=1;	// To tell header was output
1331
+			// JS forced by modules (relative url starting with /)
1332
+			if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1333
+			{
1334
+				$arrayjs=(array) $conf->modules_parts['js'];
1335
+				foreach($arrayjs as $modjs => $filesjs)
1336
+				{
1337
+					$filesjs=(array) $filesjs;	// To be sure filejs is an array
1338
+					foreach($filesjs as $jsfile)
1339
+					{
1340
+						// jsfile is a relative path
1341
+						print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1342
+					}
1343
+				}
1344
+			}
1345
+			// JS forced by page in top_htmlhead (relative url starting with /)
1346
+			if (is_array($arrayofjs))
1347
+			{
1348
+				print '<!-- Includes JS added by page -->'."\n";
1349
+				foreach($arrayofjs as $jsfile)
1350
+				{
1351
+					if (preg_match('/^http/i',$jsfile))
1352
+					{
1353
+						print '<script type="text/javascript" src="'.$jsfile.'"></script>'."\n";
1354
+					}
1355
+					else
1356
+					{
1357
+						if (! preg_match('/^\//',$jsfile)) $jsfile='/'.$jsfile;	// For backward compatibility
1358
+						print '<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1359
+					}
1360
+				}
1361
+			}
1362
+		}
1363
+
1364
+		if (! empty($head)) print $head."\n";
1365
+		if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1366
+
1367
+		print "</head>\n\n";
1368
+	}
1369
+
1370
+	$conf->headerdone=1;	// To tell header was output
1371 1371
 }
1372 1372
 
1373 1373
 
@@ -1389,93 +1389,93 @@  discard block
 block discarded – undo
1389 1389
  */
1390 1390
 function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')
1391 1391
 {
1392
-    global $user, $conf, $langs, $db;
1393
-    global $dolibarr_main_authentication, $dolibarr_main_demo;
1394
-    global $hookmanager,$menumanager;
1392
+	global $user, $conf, $langs, $db;
1393
+	global $dolibarr_main_authentication, $dolibarr_main_demo;
1394
+	global $hookmanager,$menumanager;
1395 1395
 
1396
-    $searchform='';
1397
-    $bookmarks='';
1396
+	$searchform='';
1397
+	$bookmarks='';
1398 1398
 
1399
-    // Instantiate hooks of thirdparty module
1400
-    $hookmanager->initHooks(array('toprightmenu'));
1399
+	// Instantiate hooks of thirdparty module
1400
+	$hookmanager->initHooks(array('toprightmenu'));
1401 1401
 
1402
-    $toprightmenu='';
1402
+	$toprightmenu='';
1403 1403
 
1404
-    // For backward compatibility with old modules
1405
-    if (empty($conf->headerdone))
1406
-    {
1407
-        top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1408
-        print '<body id="mainbody">';
1409
-    }
1404
+	// For backward compatibility with old modules
1405
+	if (empty($conf->headerdone))
1406
+	{
1407
+		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1408
+		print '<body id="mainbody">';
1409
+	}
1410 1410
 
1411
-    /*
1411
+	/*
1412 1412
      * Top menu
1413 1413
      */
1414
-    if (empty($conf->dol_hide_topmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1415
-    {
1416
-        print "\n".'<!-- Start top horizontal -->'."\n";
1417
-
1418
-        print '<div class="side-nav-vert"><div id="id-top">';
1419
-
1420
-	    // Show menu entries
1421
-    	print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1422
-    	$menumanager->atarget=$target;
1423
-	    $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1424
-	    print "</div>\n";
1425
-
1426
-	    // Define link to login card
1427
-        $appli=constant('DOL_APPLICATION_TITLE');
1428
-	    if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1429
-	    {
1430
-	    	$appli=$conf->global->MAIN_APPLICATION_TITLE;
1431
-	    	if (preg_match('/\d\.\d/', $appli))
1432
-	    	{
1414
+	if (empty($conf->dol_hide_topmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1415
+	{
1416
+		print "\n".'<!-- Start top horizontal -->'."\n";
1417
+
1418
+		print '<div class="side-nav-vert"><div id="id-top">';
1419
+
1420
+		// Show menu entries
1421
+		print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1422
+		$menumanager->atarget=$target;
1423
+		$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1424
+		print "</div>\n";
1425
+
1426
+		// Define link to login card
1427
+		$appli=constant('DOL_APPLICATION_TITLE');
1428
+		if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1429
+		{
1430
+			$appli=$conf->global->MAIN_APPLICATION_TITLE;
1431
+			if (preg_match('/\d\.\d/', $appli))
1432
+			{
1433 1433
 				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1434
-	    	}
1435
-	    	else $appli.=" ".DOL_VERSION;
1436
-	    }
1437
-	    else $appli.=" ".DOL_VERSION;
1438
-
1439
-	    if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1440
-
1441
-	    $logouttext='';
1442
-	    if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1443
-	    {
1444
-    	    //$logouthtmltext=$appli.'<br>';
1445
-    	    if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1446
-    	    {
1447
-    	    	$logouthtmltext.=$langs->trans("Logout").'<br>';
1448
-
1449
-    	    	$logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php">';
1450
-    	        //$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1451
-    	    	$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1452
-    	        $logouttext .='</a>';
1453
-    	    }
1454
-    	    else
1455
-    	    {
1456
-    	    	$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1457
-    	        $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1458
-    	    }
1459
-	    }
1460
-
1461
-	    print '<div class="login_block">'."\n";
1462
-
1463
-	    // Add login user link
1464
-	    $toprightmenu.='<div class="login_block_user">';
1465
-
1466
-	    // Login name with photo and tooltip
1434
+			}
1435
+			else $appli.=" ".DOL_VERSION;
1436
+		}
1437
+		else $appli.=" ".DOL_VERSION;
1438
+
1439
+		if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1440
+
1441
+		$logouttext='';
1442
+		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1443
+		{
1444
+			//$logouthtmltext=$appli.'<br>';
1445
+			if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1446
+			{
1447
+				$logouthtmltext.=$langs->trans("Logout").'<br>';
1448
+
1449
+				$logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php">';
1450
+				//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1451
+				$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1452
+				$logouttext .='</a>';
1453
+			}
1454
+			else
1455
+			{
1456
+				$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1457
+				$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1458
+			}
1459
+		}
1460
+
1461
+		print '<div class="login_block">'."\n";
1462
+
1463
+		// Add login user link
1464
+		$toprightmenu.='<div class="login_block_user">';
1465
+
1466
+		// Login name with photo and tooltip
1467 1467
 		$mode=-1;
1468
-	    $toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1469
-        $toprightmenu.=$user->getNomUrl($mode, '', true, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1470
-        $toprightmenu.='</div></div>';
1468
+		$toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1469
+		$toprightmenu.=$user->getNomUrl($mode, '', true, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1470
+		$toprightmenu.='</div></div>';
1471 1471
 
1472 1472
 		$toprightmenu.='</div>';
1473 1473
 
1474
-	    $toprightmenu.='<div class="login_block_other">';
1474
+		$toprightmenu.='<div class="login_block_other">';
1475 1475
 
1476 1476
 		// Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1477
-	    $parameters=array();
1478
-	    $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1477
+		$parameters=array();
1478
+		$result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1479 1479
 		if (is_numeric($result))
1480 1480
 		{
1481 1481
 			if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
@@ -1483,90 +1483,90 @@  discard block
 block discarded – undo
1483 1483
 		}
1484 1484
 		else $toprightmenu.=$result;	// For backward compatibility
1485 1485
 
1486
-    	// Link to module builder
1487
-	    if (! empty($conf->modulebuilder->enabled))
1488
-	    {
1489
-	        $text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1490
-	        //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1491
-	        $text.='<span class="fa fa-bug atoplogin"></span>';
1492
-	        $text.='</a>';
1493
-	        $toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1494
-	    }
1486
+		// Link to module builder
1487
+		if (! empty($conf->modulebuilder->enabled))
1488
+		{
1489
+			$text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1490
+			//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1491
+			$text.='<span class="fa fa-bug atoplogin"></span>';
1492
+			$text.='</a>';
1493
+			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1494
+		}
1495 1495
 
1496 1496
 		// Link to print main content area
1497
-	    if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && empty($conf->browser->phone))
1498
-	    {
1499
-	        $qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1500
-
1501
-	        if (is_array($_POST))
1502
-	        {
1503
-    			foreach($_POST as $key=>$value) {
1504
-    				if ($key!=='action' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1505
-    			}
1506
-	        }
1497
+		if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && empty($conf->browser->phone))
1498
+		{
1499
+			$qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1500
+
1501
+			if (is_array($_POST))
1502
+			{
1503
+				foreach($_POST as $key=>$value) {
1504
+					if ($key!=='action' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1505
+				}
1506
+			}
1507 1507
 			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1508
-	        $text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1509
-	        //$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1510
-	        $text.='<span class="fa fa-print atoplogin"></span>';
1511
-	        $text.='</a>';
1512
-	        $toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1513
-	    }
1514
-
1515
-	    // Link to Dolibarr wiki pages
1516
-	    if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1517
-	    {
1518
-	        $langs->load("help");
1519
-
1520
-	        $helpbaseurl='';
1521
-	        $helppage='';
1522
-	        $mode='';
1523
-
1524
-	        if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1525
-
1526
-	        // Get helpbaseurl, helppage and mode from helppagename and langs
1527
-	        $arrayres=getHelpParamFor($helppagename,$langs);
1528
-	        $helpbaseurl=$arrayres['helpbaseurl'];
1529
-	        $helppage=$arrayres['helppage'];
1530
-	        $mode=$arrayres['mode'];
1531
-
1532
-	        // Link to help pages
1533
-	        if ($helpbaseurl && $helppage)
1534
-	        {
1535
-	            $text='';
1536
-	            $title=$appli.'<br>';
1537
-	            $title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1538
-	            if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1539
-	            $text.='<a class="help" target="_blank" href="';
1540
-	            if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1541
-	            else $text.=sprintf($helpbaseurl,$helppage);
1542
-	            $text.='">';
1543
-	            //$text.=img_picto('', 'helpdoc_top').' ';
1544
-	            $text.='<span class="fa fa-question-circle atoplogin"></span>';
1545
-	            //$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1546
-	            //if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1547
-	            $text.='</a>';
1548
-	            //$toprightmenu.='</div>'."\n";
1549
-	            $toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1550
-	        }
1551
-	    }
1508
+			$text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1509
+			//$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1510
+			$text.='<span class="fa fa-print atoplogin"></span>';
1511
+			$text.='</a>';
1512
+			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1513
+		}
1514
+
1515
+		// Link to Dolibarr wiki pages
1516
+		if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1517
+		{
1518
+			$langs->load("help");
1519
+
1520
+			$helpbaseurl='';
1521
+			$helppage='';
1522
+			$mode='';
1523
+
1524
+			if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1525
+
1526
+			// Get helpbaseurl, helppage and mode from helppagename and langs
1527
+			$arrayres=getHelpParamFor($helppagename,$langs);
1528
+			$helpbaseurl=$arrayres['helpbaseurl'];
1529
+			$helppage=$arrayres['helppage'];
1530
+			$mode=$arrayres['mode'];
1531
+
1532
+			// Link to help pages
1533
+			if ($helpbaseurl && $helppage)
1534
+			{
1535
+				$text='';
1536
+				$title=$appli.'<br>';
1537
+				$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1538
+				if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1539
+				$text.='<a class="help" target="_blank" href="';
1540
+				if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1541
+				else $text.=sprintf($helpbaseurl,$helppage);
1542
+				$text.='">';
1543
+				//$text.=img_picto('', 'helpdoc_top').' ';
1544
+				$text.='<span class="fa fa-question-circle atoplogin"></span>';
1545
+				//$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1546
+				//if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1547
+				$text.='</a>';
1548
+				//$toprightmenu.='</div>'."\n";
1549
+				$toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1550
+			}
1551
+		}
1552 1552
 
1553 1553
 		// Logout link
1554
-	    $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1554
+		$toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1555 1555
 
1556
-	    $toprightmenu.='</div>';
1556
+		$toprightmenu.='</div>';
1557 1557
 
1558
-	    print $toprightmenu;
1558
+		print $toprightmenu;
1559 1559
 
1560
-	    print "</div>\n";
1560
+		print "</div>\n";
1561 1561
 		print '</div></div>';
1562 1562
 
1563
-	    //unset($form);
1563
+		//unset($form);
1564 1564
 
1565 1565
 		print '<div style="clear: both;"></div>';
1566
-        print "<!-- End top horizontal menu -->\n\n";
1567
-    }
1566
+		print "<!-- End top horizontal menu -->\n\n";
1567
+	}
1568 1568
 
1569
-    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1569
+	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1570 1570
 }
1571 1571
 
1572 1572
 
@@ -1586,73 +1586,73 @@  discard block
 block discarded – undo
1586 1586
  */
1587 1587
 function left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
1588 1588
 {
1589
-    global $user, $conf, $langs, $db, $form;
1590
-    global $hookmanager, $menumanager;
1589
+	global $user, $conf, $langs, $db, $form;
1590
+	global $hookmanager, $menumanager;
1591 1591
 
1592
-    $searchform='';
1593
-    $bookmarks='';
1592
+	$searchform='';
1593
+	$bookmarks='';
1594 1594
 
1595
-    if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1595
+	if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1596 1596
 
1597
-    if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1598
-    {
1599
-	    // Instantiate hooks of thirdparty module
1600
-	    $hookmanager->initHooks(array('searchform','leftblock'));
1597
+	if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1598
+	{
1599
+		// Instantiate hooks of thirdparty module
1600
+		$hookmanager->initHooks(array('searchform','leftblock'));
1601 1601
 
1602 1602
 		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1603 1603
 
1604
-	    print "\n";
1605
-
1606
-	    if ($conf->use_javascript_ajax && $conf->browser->layout != 'phone' && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1607
-	    {
1608
-    	    if (! is_object($form)) $form=new Form($db);
1609
-    	    $selected=-1;
1610
-            $searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1611
-	    }
1612
-	    else
1613
-	    {
1614
-    	    // Define $searchform
1615
-    	    if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && $user->rights->societe->lire)
1616
-    	    {
1617
-    	        $langs->load("companies");
1618
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/societe/list.php', DOL_URL_ROOT.'/societe/list.php', $langs->trans("ThirdParties"), 'maxwidth100', 'sall', 'T', 'searchleftt', img_object('','company'));
1619
-    	    }
1620
-
1621
-    	    if (! empty($conf->societe->enabled) && $user->rights->societe->lire)
1622
-    	    {
1623
-    	        $langs->load("companies");
1624
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/contact/list.php', DOL_URL_ROOT.'/contact/list.php', $langs->trans("Contacts"), 'maxwidth100', 'sall', 'A', 'searchleftc', img_object('','contact'));
1625
-    	    }
1626
-
1627
-    	    if (((! empty($conf->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire))
1628
-    	    )
1629
-    	    {
1630
-    	        $langs->load("products");
1631
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/product/list.php', DOL_URL_ROOT.'/product/list.php', $langs->trans("Products")."/".$langs->trans("Services"), 'maxwidth100', 'sall', 'P', 'searchleftp', img_object('','product'));
1632
-    	    }
1633
-
1634
-            if (! empty($conf->projet->enabled) && $user->rights->projet->lire)
1635
-    	    {
1636
-    	        $langs->load("projects");
1637
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/projet/list.php', DOL_URL_ROOT.'/projet/list.php', $langs->trans("Projects"), 'maxwidth100', 'search_all', 'Q', 'searchleftproj', img_object('','projectpub'));
1638
-    	    }
1639
-
1640
-    	    if (! empty($conf->adherent->enabled) && $user->rights->adherent->lire)
1641
-    	    {
1642
-    	        $langs->load("members");
1643
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/adherents/list.php', DOL_URL_ROOT.'/adherents/list.php', $langs->trans("Members"), 'maxwidth100', 'sall', 'M', 'searchleftm', img_object('','user'));
1644
-    	    }
1645
-
1646
-    		if (! empty($conf->user->enabled) && $user->rights->user->user->lire)
1647
-    	    {
1648
-    	        $langs->load("users");
1649
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/user/list.php', DOL_URL_ROOT.'/user/list.php', $langs->trans("Users"), 'maxwidth100', 'sall', 'M', 'searchleftuser', img_object('','user'));
1650
-    	    }
1651
-	    }
1652
-
1653
-	    // Execute hook printSearchForm
1654
-	    $parameters=array('searchform'=>$searchform);
1655
-	    $reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1604
+		print "\n";
1605
+
1606
+		if ($conf->use_javascript_ajax && $conf->browser->layout != 'phone' && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1607
+		{
1608
+			if (! is_object($form)) $form=new Form($db);
1609
+			$selected=-1;
1610
+			$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1611
+		}
1612
+		else
1613
+		{
1614
+			// Define $searchform
1615
+			if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && $user->rights->societe->lire)
1616
+			{
1617
+				$langs->load("companies");
1618
+				$searchform.=printSearchForm(DOL_URL_ROOT.'/societe/list.php', DOL_URL_ROOT.'/societe/list.php', $langs->trans("ThirdParties"), 'maxwidth100', 'sall', 'T', 'searchleftt', img_object('','company'));
1619
+			}
1620
+
1621
+			if (! empty($conf->societe->enabled) && $user->rights->societe->lire)
1622
+			{
1623
+				$langs->load("companies");
1624
+				$searchform.=printSearchForm(DOL_URL_ROOT.'/contact/list.php', DOL_URL_ROOT.'/contact/list.php', $langs->trans("Contacts"), 'maxwidth100', 'sall', 'A', 'searchleftc', img_object('','contact'));
1625
+			}
1626
+
1627
+			if (((! empty($conf->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire))
1628
+			)
1629
+			{
1630
+				$langs->load("products");
1631
+				$searchform.=printSearchForm(DOL_URL_ROOT.'/product/list.php', DOL_URL_ROOT.'/product/list.php', $langs->trans("Products")."/".$langs->trans("Services"), 'maxwidth100', 'sall', 'P', 'searchleftp', img_object('','product'));
1632
+			}
1633
+
1634
+			if (! empty($conf->projet->enabled) && $user->rights->projet->lire)
1635
+			{
1636
+				$langs->load("projects");
1637
+				$searchform.=printSearchForm(DOL_URL_ROOT.'/projet/list.php', DOL_URL_ROOT.'/projet/list.php', $langs->trans("Projects"), 'maxwidth100', 'search_all', 'Q', 'searchleftproj', img_object('','projectpub'));
1638
+			}
1639
+
1640
+			if (! empty($conf->adherent->enabled) && $user->rights->adherent->lire)
1641
+			{
1642
+				$langs->load("members");
1643
+				$searchform.=printSearchForm(DOL_URL_ROOT.'/adherents/list.php', DOL_URL_ROOT.'/adherents/list.php', $langs->trans("Members"), 'maxwidth100', 'sall', 'M', 'searchleftm', img_object('','user'));
1644
+			}
1645
+
1646
+			if (! empty($conf->user->enabled) && $user->rights->user->user->lire)
1647
+			{
1648
+				$langs->load("users");
1649
+				$searchform.=printSearchForm(DOL_URL_ROOT.'/user/list.php', DOL_URL_ROOT.'/user/list.php', $langs->trans("Users"), 'maxwidth100', 'sall', 'M', 'searchleftuser', img_object('','user'));
1650
+			}
1651
+		}
1652
+
1653
+		// Execute hook printSearchForm
1654
+		$parameters=array('searchform'=>$searchform);
1655
+		$reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1656 1656
 		if (empty($reshook))
1657 1657
 		{
1658 1658
 			$searchform.=$hookmanager->resPrint;
@@ -1660,72 +1660,72 @@  discard block
 block discarded – undo
1660 1660
 		else $searchform=$hookmanager->resPrint;
1661 1661
 
1662 1662
 		if ($conf->use_javascript_ajax && $conf->browser->layout == 'phone')
1663
-	    {
1664
-	        $searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1665
-	        $searchform.='<script type="text/javascript">
1663
+		{
1664
+			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1665
+			$searchform.='<script type="text/javascript">
1666 1666
             	jQuery(document).ready(function () {
1667 1667
             		jQuery("#divsearchforms1").click(function(){
1668 1668
 	                   jQuery("#divsearchforms2").toggle();
1669 1669
 	               });
1670 1670
             	});
1671 1671
                 </script>' . "\n";
1672
-	        $searchform.='</div>';
1673
-	    }
1672
+			$searchform.='</div>';
1673
+		}
1674 1674
 
1675
-	    // Define $bookmarks
1676
-	    if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1677
-	    {
1678
-	        include_once (DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php');
1679
-	        $langs->load("bookmarks");
1675
+		// Define $bookmarks
1676
+		if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1677
+		{
1678
+			include_once (DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php');
1679
+			$langs->load("bookmarks");
1680 1680
 
1681
-	        $bookmarks=printBookmarksList($db, $langs);
1682
-	    }
1681
+			$bookmarks=printBookmarksList($db, $langs);
1682
+		}
1683 1683
 
1684
-	    // Left column
1685
-	    print '<!-- Begin left menu -->'."\n";
1684
+		// Left column
1685
+		print '<!-- Begin left menu -->'."\n";
1686 1686
 
1687
-	    print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1687
+		print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1688 1688
 
1689
-    	// Show left menu with other forms
1690
-	    $menumanager->menu_array = $menu_array_before;
1691
-    	$menumanager->menu_array_after = $menu_array_after;
1692
-	    $menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
1689
+		// Show left menu with other forms
1690
+		$menumanager->menu_array = $menu_array_before;
1691
+		$menumanager->menu_array_after = $menu_array_after;
1692
+		$menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
1693 1693
 
1694
-        // Dolibarr version + help + bug report link
1694
+		// Dolibarr version + help + bug report link
1695 1695
 		print "\n";
1696
-	    print "<!-- Begin Help Block-->\n";
1697
-        print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1698
-
1699
-        // Version
1700
-        if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1701
-        {
1702
-            $doliurl='https://www.dolibarr.org';
1703
-    		//local communities
1704
-    		if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1705
-    		if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1706
-    		if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1707
-    		if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1708
-    		if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1709
-
1710
-            $appli=constant('DOL_APPLICATION_TITLE');
1711
-    	    if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1712
-    	    {
1713
-    	    	$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1714
-    	    	if (preg_match('/\d\.\d/', $appli))
1715
-    	    	{
1716
-    				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1717
-    	    	}
1718
-    	    	else $appli.=" ".DOL_VERSION;
1719
-    	    }
1720
-    	    else $appli.=" ".DOL_VERSION;
1721
-    	    print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1722
-    	    if ($doliurl) print '<a class="help" target="_blank" href="'.$doliurl.'">';
1723
-    	    else print '<span class="help">';
1724
-    	    print $appli;
1725
-    	    if ($doliurl) print '</a>';
1726
-    	    else print '</span>';
1727
-    	    print '</div>'."\n";
1728
-        }
1696
+		print "<!-- Begin Help Block-->\n";
1697
+		print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1698
+
1699
+		// Version
1700
+		if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1701
+		{
1702
+			$doliurl='https://www.dolibarr.org';
1703
+			//local communities
1704
+			if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1705
+			if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1706
+			if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1707
+			if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1708
+			if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1709
+
1710
+			$appli=constant('DOL_APPLICATION_TITLE');
1711
+			if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1712
+			{
1713
+				$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1714
+				if (preg_match('/\d\.\d/', $appli))
1715
+				{
1716
+					if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1717
+				}
1718
+				else $appli.=" ".DOL_VERSION;
1719
+			}
1720
+			else $appli.=" ".DOL_VERSION;
1721
+			print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1722
+			if ($doliurl) print '<a class="help" target="_blank" href="'.$doliurl.'">';
1723
+			else print '<span class="help">';
1724
+			print $appli;
1725
+			if ($doliurl) print '</a>';
1726
+			else print '</span>';
1727
+			print '</div>'."\n";
1728
+		}
1729 1729
 
1730 1730
 		// Link to bugtrack
1731 1731
 		if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
@@ -1753,26 +1753,26 @@  discard block
 block discarded – undo
1753 1753
 			print '</div>';
1754 1754
 		}
1755 1755
 
1756
-        print "</div>\n";
1757
-        print "<!-- End Help Block-->\n";
1758
-        print "\n";
1756
+		print "</div>\n";
1757
+		print "<!-- End Help Block-->\n";
1758
+		print "\n";
1759 1759
 
1760
-        print "</div>\n";
1761
-        print "<!-- End left menu -->\n";
1762
-        print "\n";
1760
+		print "</div>\n";
1761
+		print "<!-- End left menu -->\n";
1762
+		print "\n";
1763 1763
 
1764
-	    // Execute hook printLeftBlock
1765
-	    $parameters=array();
1766
-	    $reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1767
-	    print $hookmanager->resPrint;
1764
+		// Execute hook printLeftBlock
1765
+		$parameters=array();
1766
+		$reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1767
+		print $hookmanager->resPrint;
1768 1768
 
1769
-	    print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1770
-    }
1769
+		print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1770
+	}
1771 1771
 
1772
-    print "\n";
1773
-    print '<!-- Begin right area -->'."\n";
1772
+	print "\n";
1773
+	print '<!-- Begin right area -->'."\n";
1774 1774
 
1775
-    if (empty($leftmenuwithoutmainarea)) main_area($title);
1775
+	if (empty($leftmenuwithoutmainarea)) main_area($title);
1776 1776
 }
1777 1777
 
1778 1778
 
@@ -1784,15 +1784,15 @@  discard block
 block discarded – undo
1784 1784
  */
1785 1785
 function main_area($title='')
1786 1786
 {
1787
-    global $conf, $langs;
1787
+	global $conf, $langs;
1788 1788
 
1789 1789
 	if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
1790 1790
 
1791
-    print "\n";
1791
+	print "\n";
1792 1792
 
1793
-    print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1793
+	print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1794 1794
 
1795
-    if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1795
+	if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1796 1796
 }
1797 1797
 
1798 1798
 
@@ -1809,34 +1809,34 @@  discard block
 block discarded – undo
1809 1809
 	$helppage='';
1810 1810
 	$mode='';
1811 1811
 
1812
-    if (preg_match('/^http/i',$helppagename))
1813
-    {
1814
-        // If complete URL
1815
-        $helpbaseurl='%s';
1816
-        $helppage=$helppagename;
1817
-        $mode='local';
1818
-    }
1819
-    else
1820
-    {
1821
-        // If WIKI URL
1822
-        if (preg_match('/^es/i',$langs->defaultlang))
1823
-        {
1824
-            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1825
-            if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1826
-        }
1827
-        if (preg_match('/^fr/i',$langs->defaultlang))
1828
-        {
1829
-            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1830
-            if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1831
-        }
1832
-        if (empty($helppage))	// If help page not already found
1833
-        {
1834
-            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1835
-            if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1836
-        }
1837
-        $mode='wiki';
1838
-    }
1839
-    return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1812
+	if (preg_match('/^http/i',$helppagename))
1813
+	{
1814
+		// If complete URL
1815
+		$helpbaseurl='%s';
1816
+		$helppage=$helppagename;
1817
+		$mode='local';
1818
+	}
1819
+	else
1820
+	{
1821
+		// If WIKI URL
1822
+		if (preg_match('/^es/i',$langs->defaultlang))
1823
+		{
1824
+			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1825
+			if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1826
+		}
1827
+		if (preg_match('/^fr/i',$langs->defaultlang))
1828
+		{
1829
+			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1830
+			if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1831
+		}
1832
+		if (empty($helppage))	// If help page not already found
1833
+		{
1834
+			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1835
+			if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1836
+		}
1837
+		$mode='wiki';
1838
+	}
1839
+	return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1840 1840
 }
1841 1841
 
1842 1842
 
@@ -1855,120 +1855,120 @@  discard block
 block discarded – undo
1855 1855
  */
1856 1856
 function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='')
1857 1857
 {
1858
-    global $conf,$langs;
1858
+	global $conf,$langs;
1859 1859
 
1860
-    if (empty($htmlinputid)) {
1861
-        $htmlinputid = $htmlinputname;
1862
-    }
1860
+	if (empty($htmlinputid)) {
1861
+		$htmlinputid = $htmlinputname;
1862
+	}
1863 1863
 
1864
-    $ret='';
1865
-    $ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1864
+	$ret='';
1865
+	$ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1866 1866
 	if (empty($conf->global->MAIN_HTML5_PLACEHOLDER))
1867 1867
 	{
1868
-        $ret.='<div class="menu_titre menu_titre_search"';
1869
-    	if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="display: inline-block"';
1870
-    	$ret.='>';
1871
-    	$ret.='<label for="'.$prefhtmlinputname.$htmlinputname.'">';
1872
-    	$ret.='<a class="vsmenu" href="'.$urlobject.'">';
1873
-       	if ($img && ! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=$img;
1874
-       	else if ($img || $title) $ret.=$img.' '.$title;
1875
-    	$ret.='</a>';
1876
-    	$ret.='</label>';
1877
-    	$ret.='</div>';
1868
+		$ret.='<div class="menu_titre menu_titre_search"';
1869
+		if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="display: inline-block"';
1870
+		$ret.='>';
1871
+		$ret.='<label for="'.$prefhtmlinputname.$htmlinputname.'">';
1872
+		$ret.='<a class="vsmenu" href="'.$urlobject.'">';
1873
+	   	if ($img && ! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=$img;
1874
+	   	else if ($img || $title) $ret.=$img.' '.$title;
1875
+		$ret.='</a>';
1876
+		$ret.='</label>';
1877
+		$ret.='</div>';
1878 1878
 	}
1879
-    $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1880
-    $ret.='<input type="hidden" name="mode" value="search">';
1881
-    $ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1882
-    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1883
-    $ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1884
-    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' placeholder="'.strip_tags($title).'"';		// Will work only if MAIN_HTML5_PLACEHOLDER is set to 1
1885
-    else $ret.=' title="'.$langs->trans("SearchOf").''.strip_tags($title).'"';
1886
-    $ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1887
-    $ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1888
-    $ret.="</form>\n";
1889
-    return $ret;
1879
+	$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1880
+	$ret.='<input type="hidden" name="mode" value="search">';
1881
+	$ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1882
+	if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1883
+	$ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1884
+	if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' placeholder="'.strip_tags($title).'"';		// Will work only if MAIN_HTML5_PLACEHOLDER is set to 1
1885
+	else $ret.=' title="'.$langs->trans("SearchOf").''.strip_tags($title).'"';
1886
+	$ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1887
+	$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1888
+	$ret.="</form>\n";
1889
+	return $ret;
1890 1890
 }
1891 1891
 
1892 1892
 
1893 1893
 if (! function_exists("llxFooter"))
1894 1894
 {
1895
-    /**
1896
-     * Show HTML footer
1897
-     * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.
1898
-     * If global var $delayedhtmlcontent was filled, we output it just before closing the body.
1899
-     *
1900
-     * @param	string	$comment    A text to add as HTML comment into HTML generated page
1895
+	/**
1896
+	 * Show HTML footer
1897
+	 * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.
1898
+	 * If global var $delayedhtmlcontent was filled, we output it just before closing the body.
1899
+	 *
1900
+	 * @param	string	$comment    A text to add as HTML comment into HTML generated page
1901 1901
 	 * @param	string	$zone		'private' (for private pages) or 'public' (for public pages)
1902
-     * @return	void
1903
-     */
1904
-    function llxFooter($comment='',$zone='private')
1905
-    {
1906
-        global $conf, $langs, $user, $object;
1907
-        global $delayedhtmlcontent;
1908
-
1909
-        // Global html output events ($mesgs, $errors, $warnings)
1910
-        dol_htmloutput_events();
1911
-
1912
-        // Code for search criteria persistence.
1913
-        // Save $user->lastsearch_values if defined (define on list pages when a form field search_xxx exists)
1914
-        if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1915
-        {
1916
-            // Clean data
1917
-            foreach($user->lastsearch_values_tmp as $key => $val)
1918
-            {
1919
-                unset($_SESSION['lastsearch_values_tmp_'.$key]);
1920
-                if (count($val))
1921
-                {
1922
-                    if (empty($val['sortfield'])) unset($val['sortfield']);
1923
-                    if (empty($val['sortorder'])) unset($val['sortorder']);
1924
-                    dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criteria)");
1925
-                    $_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
1926
-                    unset($_SESSION['lastsearch_values_'.$key]);
1927
-                }
1928
-            }
1929
-        }
1930
-
1931
-        // Core error message
1932
-        if (! empty($conf->global->MAIN_CORE_ERROR))
1933
-        {
1934
-            // Ajax version
1935
-            if ($conf->use_javascript_ajax)
1936
-            {
1937
-                $title = img_warning().' '.$langs->trans('CoreErrorTitle');
1938
-                print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
1939
-            }
1940
-            // html version
1941
-            else
1942
-            {
1943
-                $msg = img_warning().' '.$langs->trans('CoreErrorMessage');
1944
-                print '<div class="error">'.$msg.'</div>';
1945
-            }
1902
+	 * @return	void
1903
+	 */
1904
+	function llxFooter($comment='',$zone='private')
1905
+	{
1906
+		global $conf, $langs, $user, $object;
1907
+		global $delayedhtmlcontent;
1908
+
1909
+		// Global html output events ($mesgs, $errors, $warnings)
1910
+		dol_htmloutput_events();
1911
+
1912
+		// Code for search criteria persistence.
1913
+		// Save $user->lastsearch_values if defined (define on list pages when a form field search_xxx exists)
1914
+		if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1915
+		{
1916
+			// Clean data
1917
+			foreach($user->lastsearch_values_tmp as $key => $val)
1918
+			{
1919
+				unset($_SESSION['lastsearch_values_tmp_'.$key]);
1920
+				if (count($val))
1921
+				{
1922
+					if (empty($val['sortfield'])) unset($val['sortfield']);
1923
+					if (empty($val['sortorder'])) unset($val['sortorder']);
1924
+					dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criteria)");
1925
+					$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
1926
+					unset($_SESSION['lastsearch_values_'.$key]);
1927
+				}
1928
+			}
1929
+		}
1946 1930
 
1947
-            //define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
1948
-        }
1931
+		// Core error message
1932
+		if (! empty($conf->global->MAIN_CORE_ERROR))
1933
+		{
1934
+			// Ajax version
1935
+			if ($conf->use_javascript_ajax)
1936
+			{
1937
+				$title = img_warning().' '.$langs->trans('CoreErrorTitle');
1938
+				print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
1939
+			}
1940
+			// html version
1941
+			else
1942
+			{
1943
+				$msg = img_warning().' '.$langs->trans('CoreErrorMessage');
1944
+				print '<div class="error">'.$msg.'</div>';
1945
+			}
1949 1946
 
1950
-        print "\n\n";
1947
+			//define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
1948
+		}
1949
+
1950
+		print "\n\n";
1951 1951
 
1952
-        print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
1952
+		print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
1953 1953
 
1954 1954
 		if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'; // End div id-right
1955 1955
 
1956
-        print "\n";
1957
-        if ($comment) print '<!-- '.$comment.' -->'."\n";
1956
+		print "\n";
1957
+		if ($comment) print '<!-- '.$comment.' -->'."\n";
1958 1958
 
1959
-        printCommonFooter($zone);
1959
+		printCommonFooter($zone);
1960 1960
 
1961
-        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
1961
+		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
1962 1962
 
1963
-        if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
1963
+		if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
1964 1964
 
1965
-        // TODO Move this in lib_head.js.php
1965
+		// TODO Move this in lib_head.js.php
1966 1966
 
1967
-        // Wrapper to show tooltips (html or onclick popup)
1968
-        if (! empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover))
1969
-        {
1970
-    		print "\n<!-- JS CODE TO ENABLE tipTip on all object with class classfortooltip -->\n";
1971
-    		print '<script type="text/javascript">
1967
+		// Wrapper to show tooltips (html or onclick popup)
1968
+		if (! empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover))
1969
+		{
1970
+			print "\n<!-- JS CODE TO ENABLE tipTip on all object with class classfortooltip -->\n";
1971
+			print '<script type="text/javascript">
1972 1972
             	jQuery(document).ready(function () {
1973 1973
             		jQuery(".classfortooltip").tipTip({maxWidth: "'.dol_size(($conf->browser->layout == 'phone' ? 400 : 700),'width').'px", edgeOffset: 10, delay: 50, fadeIn: 50, fadeOut: 50});
1974 1974
             		jQuery(".classfortooltiponclicktext").dialog({ width: '.($conf->browser->layout == 'phone' ? 400 : 700).', autoOpen: false });
@@ -1982,13 +1982,13 @@  discard block
 block discarded – undo
1982 1982
             		});
1983 1983
                 });
1984 1984
             </script>' . "\n";
1985
-        }
1985
+		}
1986 1986
 
1987
-        // Wrapper to manage document_preview
1988
-        if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
1989
-        {
1990
-            print "\n<!-- JS CODE TO ENABLE document_preview -->\n";
1991
-            print '<script type="text/javascript">
1987
+		// Wrapper to manage document_preview
1988
+		if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
1989
+		{
1990
+			print "\n<!-- JS CODE TO ENABLE document_preview -->\n";
1991
+			print '<script type="text/javascript">
1992 1992
                 jQuery(document).ready(function () {
1993 1993
 			        jQuery(".documentpreview").click(function () {
1994 1994
             		    console.log("We click on preview for element with href="+$(this).attr(\'href\')+" mime="+$(this).attr(\'mime\'));
@@ -1997,13 +1997,13 @@  discard block
 block discarded – undo
1997 1997
         			});
1998 1998
         		});
1999 1999
             </script>' . "\n";
2000
-        }
2000
+		}
2001 2001
 
2002
-        // Wrapper to manage dropdown
2003
-        if (! empty($conf->use_javascript_ajax) && ! defined('JS_JQUERY_DISABLE_DROPDOWN'))
2004
-        {
2005
-            print "\n<!-- JS CODE TO ENABLE dropdown -->\n";
2006
-            print '<script type="text/javascript">
2002
+		// Wrapper to manage dropdown
2003
+		if (! empty($conf->use_javascript_ajax) && ! defined('JS_JQUERY_DISABLE_DROPDOWN'))
2004
+		{
2005
+			print "\n<!-- JS CODE TO ENABLE dropdown -->\n";
2006
+			print '<script type="text/javascript">
2007 2007
                 jQuery(document).ready(function () {
2008 2008
                   $(".dropdown dt a").on(\'click\', function () {
2009 2009
                       //console.log($(this).parent().parent().find(\'dd ul\'));
@@ -2036,15 +2036,15 @@  discard block
 block discarded – undo
2036 2036
                   });
2037 2037
                 });
2038 2038
                 </script>';
2039
-        }
2039
+		}
2040 2040
 
2041
-        // Wrapper to add log when clicking on download or preview
2042
-        if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2043
-        {
2044
-            if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2045
-            {
2046
-                print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2047
-                ?>
2041
+		// Wrapper to add log when clicking on download or preview
2042
+		if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2043
+		{
2044
+			if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2045
+			{
2046
+				print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2047
+				?>
2048 2048
     			<script type="text/javascript">
2049 2049
     			jQuery(document).ready(function () {
2050 2050
     				$('a.documentpreview').click(function() {
@@ -2068,16 +2068,16 @@  discard block
 block discarded – undo
2068 2068
     			});
2069 2069
     			</script>
2070 2070
 				<?php
2071
-    		}
2072
-       	}
2071
+			}
2072
+	   	}
2073 2073
 
2074 2074
 
2075 2075
 		// A div for the address popup
2076 2076
 		print "\n<!-- A div to allow dialog popup -->\n";
2077 2077
 		print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
2078 2078
 
2079
-        print "</body>\n";
2080
-        print "</html>\n";
2081
-    }
2079
+		print "</body>\n";
2080
+		print "</html>\n";
2081
+	}
2082 2082
 }
2083 2083
 
Please login to merge, or discard this patch.
Spacing   +623 added lines, -623 removed lines patch added patch discarded remove patch
@@ -35,11 +35,11 @@  discard block
 block discarded – undo
35 35
 //@ini_set('memory_limit', '128M');	// This may be useless if memory is hard limited by your PHP
36 36
 
37 37
 // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.
38
-$micro_start_time=0;
39
-if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
38
+$micro_start_time = 0;
39
+if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
40 40
 {
41 41
     list($usec, $sec) = explode(" ", microtime());
42
-    $micro_start_time=((float) $usec + (float) $sec);
42
+    $micro_start_time = ((float) $usec + (float) $sec);
43 43
     // Add Xdebug code coverage
44 44
     //define('XDEBUGCOVERAGE',1);
45 45
     if (defined('XDEBUGCOVERAGE')) {
@@ -81,14 +81,14 @@  discard block
 block discarded – undo
81 81
     // For SQL Injection (only GET and POST are used to be included into bad escaped SQL requests)
82 82
     if ($type != 2)
83 83
     {
84
-        $inj += preg_match('/delete\s+from/i',	 $val);
85
-        $inj += preg_match('/create\s+table/i',	 $val);
86
-        $inj += preg_match('/update.+set.+=/i',  $val);
87
-        $inj += preg_match('/insert\s+into/i', 	 $val);
88
-        $inj += preg_match('/select.+from/i', 	 $val);
89
-        $inj += preg_match('/union.+select/i', 	 $val);
90
-        $inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
91
-        $inj += preg_match('/(\.\.%2f)+/i',		 $val);
84
+        $inj += preg_match('/delete\s+from/i', $val);
85
+        $inj += preg_match('/create\s+table/i', $val);
86
+        $inj += preg_match('/update.+set.+=/i', $val);
87
+        $inj += preg_match('/insert\s+into/i', $val);
88
+        $inj += preg_match('/select.+from/i', $val);
89
+        $inj += preg_match('/union.+select/i', $val);
90
+        $inj += preg_match('/into\s+(outfile|dumpfile)/i', $val);
91
+        $inj += preg_match('/(\.\.%2f)+/i', $val);
92 92
     }
93 93
     // For XSS Injection done by adding javascript with script
94 94
     // This is all cases a browser consider text is javascript:
@@ -97,23 +97,23 @@  discard block
 block discarded – undo
97 97
 	// More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
98 98
     $inj += preg_match('/<script/i', $val);
99 99
 	$inj += preg_match('/<iframe/i', $val);
100
-	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
101
-    if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
100
+	$inj += preg_match('/Set\.constructor/i', $val); // ECMA script 6
101
+    if (!defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
102 102
     $inj += preg_match('/base[\s]+href/si', $val);
103
-    $inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
104
-    $inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
105
-    $inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
106
-    $inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
103
+    $inj += preg_match('/<.*onmouse/si', $val); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
104
+    $inj += preg_match('/onerror\s*=/i', $val); // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
105
+    $inj += preg_match('/onfocus\s*=/i', $val); // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
106
+    $inj += preg_match('/onload\s*=/i', $val); // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
107 107
     //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
108
-	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
108
+	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
109 109
     //if ($type == 1)
110 110
     //{
111 111
         $inj += preg_match('/javascript:/i', $val);
112 112
         $inj += preg_match('/vbscript:/i', $val);
113 113
     //}
114 114
     // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
115
-    if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
116
-    if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
115
+    if ($type == 1) $inj += preg_match('/"/i', $val); // We refused " in GET parameters value
116
+    if ($type == 2) $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces.
117 117
     return $inj;
118 118
 }
119 119
 
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
     {
131 131
         foreach ($var as $key => $value)
132 132
         {
133
-            if (analyseVarsForSqlAndScriptsInjection($value,$type))
133
+            if (analyseVarsForSqlAndScriptsInjection($value, $type))
134 134
             {
135 135
                 $var[$key] = $value;
136 136
             }
@@ -144,36 +144,36 @@  discard block
 block discarded – undo
144 144
     }
145 145
     else
146 146
     {
147
-        return (test_sql_and_script_inject($var,$type) <= 0);
147
+        return (test_sql_and_script_inject($var, $type) <= 0);
148 148
     }
149 149
 }
150 150
 
151 151
 
152 152
 // Check consistency of NOREQUIREXXX DEFINES
153
-if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU')) dol_print_error('','If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not use them');
153
+if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU')) dol_print_error('', 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not use them');
154 154
 
155 155
 // Sanity check on URL
156
-if (! empty($_SERVER["PHP_SELF"]))
156
+if (!empty($_SERVER["PHP_SELF"]))
157 157
 {
158
-    $morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
159
-    analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
158
+    $morevaltochecklikepost = array($_SERVER["PHP_SELF"]);
159
+    analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost, 2);
160 160
 }
161 161
 // Sanity check on GET parameters
162
-if (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER["QUERY_STRING"]))
162
+if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"]))
163 163
 {
164
-    $morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
165
-    analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
164
+    $morevaltochecklikeget = array($_SERVER["QUERY_STRING"]);
165
+    analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget, 1);
166 166
 }
167 167
 // Sanity check on POST
168
-if (! defined('NOSCANPOSTFORINJECTION'))
168
+if (!defined('NOSCANPOSTFORINJECTION'))
169 169
 {
170
-	analyseVarsForSqlAndScriptsInjection($_POST,0);
170
+	analyseVarsForSqlAndScriptsInjection($_POST, 0);
171 171
 }
172 172
 
173 173
 // This is to make Dolibarr working with Plesk
174
-if (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
174
+if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
175 175
 {
176
-	set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
176
+	set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs');
177 177
 }
178 178
 
179 179
 // Include the conf.php and functions.lib.php
@@ -182,34 +182,34 @@  discard block
 block discarded – undo
182 182
 // If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.
183 183
 // This is used for example by form of boxes to save personalization of some options.
184 184
 // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and  cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))
185
-if (! empty($_POST["DOL_AUTOSET_COOKIE"]))
185
+if (!empty($_POST["DOL_AUTOSET_COOKIE"]))
186 186
 {
187
-	$tmpautoset=explode(':',$_POST["DOL_AUTOSET_COOKIE"],2);
188
-	$tmplist=explode(',',$tmpautoset[1]);
189
-	$cookiearrayvalue='';
187
+	$tmpautoset = explode(':', $_POST["DOL_AUTOSET_COOKIE"], 2);
188
+	$tmplist = explode(',', $tmpautoset[1]);
189
+	$cookiearrayvalue = '';
190 190
 	foreach ($tmplist as $tmpkey)
191 191
 	{
192
-		$postkey=$tmpautoset[0].'_'.$tmpkey;
192
+		$postkey = $tmpautoset[0].'_'.$tmpkey;
193 193
 		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
194
-		if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
194
+		if (!empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey] = $_POST[$postkey];
195 195
 	}
196
-	$cookiename=$tmpautoset[0];
197
-	$cookievalue=json_encode($cookiearrayvalue);
196
+	$cookiename = $tmpautoset[0];
197
+	$cookievalue = json_encode($cookiearrayvalue);
198 198
 	//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
199
-	setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
199
+	setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : (time() + (86400 * 354)), '/', null, false, true); // keep cookie 1 year and add tag httponly
200 200
 	if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
201 201
 }
202 202
 
203 203
 // Init session. Name of session is specific to Dolibarr instance.
204
-$prefix=dol_getprefix();
205
-$sessionname='DOLSESSID_'.$prefix;
206
-$sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
207
-if (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);
204
+$prefix = dol_getprefix();
205
+$sessionname = 'DOLSESSID_'.$prefix;
206
+$sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
207
+if (!empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]);
208 208
 session_name($sessionname);
209
-session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
209
+session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
210 210
 // This create lock released until session_write_close() or end of page.
211 211
 // We need this lock as long as we read/write $_SESSION ['vars']. We can close released when finished.
212
-if (! defined('NOSESSION'))
212
+if (!defined('NOSESSION'))
213 213
 {
214 214
     session_start();
215 215
     if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
@@ -230,42 +230,42 @@  discard block
 block discarded – undo
230 230
 // Detection browser
231 231
 if (isset($_SERVER["HTTP_USER_AGENT"]))
232 232
 {
233
-    $tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
234
-    $conf->browser->name=$tmp['browsername'];
235
-    $conf->browser->os=$tmp['browseros'];
236
-    $conf->browser->version=$tmp['browserversion'];
237
-    $conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
238
-    $conf->browser->phone=$tmp['phone'];	   // TODO deprecated, use ->layout
239
-    $conf->browser->tablet=$tmp['tablet'];	   // TODO deprecated, use ->layout
233
+    $tmp = getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
234
+    $conf->browser->name = $tmp['browsername'];
235
+    $conf->browser->os = $tmp['browseros'];
236
+    $conf->browser->version = $tmp['browserversion'];
237
+    $conf->browser->layout = $tmp['layout']; // 'classic', 'phone', 'tablet'
238
+    $conf->browser->phone = $tmp['phone']; // TODO deprecated, use ->layout
239
+    $conf->browser->tablet = $tmp['tablet']; // TODO deprecated, use ->layout
240 240
     //var_dump($conf->browser);
241 241
 
242
-    if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
243
-    if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
242
+    if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover = 1;
243
+    if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER = 1;
244 244
 }
245 245
 
246 246
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
247 247
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
248
-if (! empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
248
+if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
249 249
 {
250
-    $newurl='';
250
+    $newurl = '';
251 251
     if (is_numeric($conf->file->main_force_https))
252 252
     {
253
-        if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
253
+        if ($conf->file->main_force_https == '1' && !empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
254 254
         {
255
-            if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
255
+            if (preg_match('/^http:/i', $_SERVER["SCRIPT_URI"]) && !preg_match('/^https:/i', $_SERVER["SCRIPT_URI"]))	// If link is http
256 256
             {
257
-                $newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
257
+                $newurl = preg_replace('/^http:/i', 'https:', $_SERVER["SCRIPT_URI"]);
258 258
             }
259 259
         }
260 260
         else	// Check HTTPS environment variable (Apache/mod_ssl only)
261 261
         {
262
-            $newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
262
+            $newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
263 263
         }
264 264
     }
265 265
     else
266 266
     {
267 267
         // Check HTTPS environment variable (Apache/mod_ssl only)
268
-        $newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
268
+        $newurl = $conf->file->main_force_https.$_SERVER["REQUEST_URI"];
269 269
     }
270 270
     // Start redirect
271 271
     if ($newurl)
@@ -282,25 +282,25 @@  discard block
 block discarded – undo
282 282
 
283 283
 
284 284
 // Loading of additional presentation includes
285
-if (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';	    // Need 660ko memory (800ko in 2.2)
286
-if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';	// Need 22ko memory
285
+if (!defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
286
+if (!defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory
287 287
 
288 288
 // If install or upgrade process not done or not completely finished, we call the install page.
289
-if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
289
+if (!empty($conf->global->MAIN_NOT_INSTALLED) || !empty($conf->global->MAIN_NOT_UPGRADED))
290 290
 {
291 291
     dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
292 292
     header("Location: ".DOL_URL_ROOT."/install/index.php");
293 293
     exit;
294 294
 }
295 295
 // If an upgrade process is required, we call the install page.
296
-if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
297
-|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
296
+if ((!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
297
+|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
298 298
 {
299
-    $versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
300
-    require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
301
-    $dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
302
-    $dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
303
-    $rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
299
+    $versiontocompare = empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE;
300
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
301
+    $dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare);
302
+    $dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION);
303
+    $rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade);
304 304
     if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
305 305
     {
306 306
         dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
@@ -310,18 +310,18 @@  discard block
 block discarded – undo
310 310
 }
311 311
 
312 312
 // Creation of a token against CSRF vulnerabilities
313
-if (! defined('NOTOKENRENEWAL'))
313
+if (!defined('NOTOKENRENEWAL'))
314 314
 {
315 315
     // roulement des jetons car cree a chaque appel
316 316
     if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
317 317
 
318 318
     // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
319
-    $token = dol_hash(uniqid(mt_rand(),TRUE)); // Generates a hash of a random number
319
+    $token = dol_hash(uniqid(mt_rand(), TRUE)); // Generates a hash of a random number
320 320
     $_SESSION['newtoken'] = $token;
321 321
 }
322
-if (! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))	// Check validity of token, only if option enabled (this option breaks some features sometimes)
322
+if (!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))	// Check validity of token, only if option enabled (this option breaks some features sometimes)
323 323
 {
324
-    if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
324
+    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !GETPOST('token', 'alpha')) // Note, offender can still send request by GET
325 325
     {
326 326
         print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
327 327
         print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
     {
332 332
         if (GETPOST('token', 'alpha') != $_SESSION['token'])
333 333
         {
334
-            dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
334
+            dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action', 'aZ09').", _POST['token']=".GETPOST('token', 'alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
335 335
             //print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
336 336
             unset($_POST);
337 337
         }
@@ -339,20 +339,20 @@  discard block
 block discarded – undo
339 339
 }
340 340
 
341 341
 // Disable modules (this must be after session_start and after conf has been loaded)
342
-if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
343
-if (! empty($_SESSION["disablemodules"]))
342
+if (GETPOST('disablemodules', 'alpha'))  $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha');
343
+if (!empty($_SESSION["disablemodules"]))
344 344
 {
345
-    $disabled_modules=explode(',',$_SESSION["disablemodules"]);
346
-    foreach($disabled_modules as $module)
345
+    $disabled_modules = explode(',', $_SESSION["disablemodules"]);
346
+    foreach ($disabled_modules as $module)
347 347
     {
348 348
         if ($module)
349 349
         {
350
-        	if (empty($conf->$module)) $conf->$module=new stdClass();
351
-        	$conf->$module->enabled=false;
350
+        	if (empty($conf->$module)) $conf->$module = new stdClass();
351
+        	$conf->$module->enabled = false;
352 352
         	if ($module == 'fournisseur')		// Special case
353 353
         	{
354
-        		$conf->supplier_order->enabled=0;
355
-        		$conf->supplier_invoice->enabled=0;
354
+        		$conf->supplier_order->enabled = 0;
355
+        		$conf->supplier_invoice->enabled = 0;
356 356
         	}
357 357
         }
358 358
     }
@@ -362,120 +362,120 @@  discard block
 block discarded – undo
362 362
 /*
363 363
  * Phase authentication / login
364 364
  */
365
-$login='';
366
-if (! defined('NOLOGIN'))
365
+$login = '';
366
+if (!defined('NOLOGIN'))
367 367
 {
368 368
     // $authmode lists the different means of identification to be tested in order of preference.
369 369
     // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser'
370 370
 
371 371
     // Authentication mode
372
-    if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
372
+    if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr';
373 373
     // Authentication mode: forceuser
374
-    if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
374
+    if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto';
375 375
     // Set authmode
376
-    $authmode=explode(',',$dolibarr_main_authentication);
376
+    $authmode = explode(',', $dolibarr_main_authentication);
377 377
 
378 378
     // No authentication mode
379
-    if (! count($authmode))
379
+    if (!count($authmode))
380 380
     {
381 381
         $langs->load('main');
382
-        dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
382
+        dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication'));
383 383
         exit;
384 384
     }
385 385
 
386 386
     // If login request was already post, we retrieve login from the session
387 387
     // Call module if not realized that his request.
388 388
     // At the end of this phase, the variable $login is defined.
389
-    $resultFetchUser='';
390
-    $test=true;
391
-    if (! isset($_SESSION["dol_login"]))
389
+    $resultFetchUser = '';
390
+    $test = true;
391
+    if (!isset($_SESSION["dol_login"]))
392 392
     {
393 393
         // It is not already authenticated and it requests the login / password
394 394
         include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
395 395
 
396
-        $dol_dst_observed=GETPOST("dst_observed",'int',3);
397
-        $dol_dst_first=GETPOST("dst_first",'int',3);
398
-        $dol_dst_second=GETPOST("dst_second",'int',3);
399
-        $dol_screenwidth=GETPOST("screenwidth",'int',3);
400
-        $dol_screenheight=GETPOST("screenheight",'int',3);
401
-        $dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
402
-        $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
403
-        $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
404
-        $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
405
-        $dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
396
+        $dol_dst_observed = GETPOST("dst_observed", 'int', 3);
397
+        $dol_dst_first = GETPOST("dst_first", 'int', 3);
398
+        $dol_dst_second = GETPOST("dst_second", 'int', 3);
399
+        $dol_screenwidth = GETPOST("screenwidth", 'int', 3);
400
+        $dol_screenheight = GETPOST("screenheight", 'int', 3);
401
+        $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int', 3);
402
+        $dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int', 3);
403
+        $dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int', 3);
404
+        $dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int', 3);
405
+        $dol_use_jmobile = GETPOST('dol_use_jmobile', 'int', 3);
406 406
         //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
407 407
 
408 408
         // If in demo mode, we check we go to home page through the public/demo/index.php page
409
-        if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
409
+        if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
410 410
         {
411
-            if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
411
+            if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER']))
412 412
             {
413 413
                 dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
414
-                $url='';
415
-                $url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
416
-                $url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
417
-                $url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
418
-                $url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
419
-                $url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
420
-                $url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
414
+                $url = '';
415
+                $url .= ($url ? '&' : '').($dol_hide_topmenu ? 'dol_hide_topmenu='.$dol_hide_topmenu : '');
416
+                $url .= ($url ? '&' : '').($dol_hide_leftmenu ? 'dol_hide_leftmenu='.$dol_hide_leftmenu : '');
417
+                $url .= ($url ? '&' : '').($dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$dol_optimize_smallscreen : '');
418
+                $url .= ($url ? '&' : '').($dol_no_mouse_hover ? 'dol_no_mouse_hover='.$dol_no_mouse_hover : '');
419
+                $url .= ($url ? '&' : '').($dol_use_jmobile ? 'dol_use_jmobile='.$dol_use_jmobile : '');
420
+                $url = DOL_URL_ROOT.'/public/demo/index.php'.($url ? '?'.$url : '');
421 421
                 header("Location: ".$url);
422 422
                 exit;
423 423
             }
424 424
         }
425 425
 
426 426
         // Verification security graphic code
427
-        if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
427
+        if (GETPOST("username", "alpha", 2) && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
428 428
         {
429 429
             $sessionkey = 'dol_antispam_value';
430
-            $ok=(array_key_exists($sessionkey, $_SESSION) === TRUE && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
430
+            $ok = (array_key_exists($sessionkey, $_SESSION) === TRUE && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
431 431
 
432 432
             // Check code
433
-            if (! $ok)
433
+            if (!$ok)
434 434
             {
435 435
                 dol_syslog('Bad value for code, connexion refused');
436 436
                 $langs->load('main');
437 437
                 $langs->load('errors');
438 438
 
439
-                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
440
-                $test=false;
439
+                $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadValueForCode");
440
+                $test = false;
441 441
 
442 442
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
443
-                $user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
443
+                $user->trigger_mesg = 'ErrorBadValueForCode - login='.GETPOST("username", "alpha", 2);
444 444
                 // Call of triggers
445
-                include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
446
-                $interface=new Interfaces($db);
447
-                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
445
+                include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
446
+                $interface = new Interfaces($db);
447
+                $result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf);
448 448
                 if ($result < 0) {
449 449
                     $error++;
450 450
                 }
451 451
                 // End Call of triggers
452 452
 
453 453
                 // Hooks on failed login
454
-		        $action='';
454
+		        $action = '';
455 455
 		        $hookmanager->initHooks(array('login'));
456
-		        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
457
-		        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
456
+		        $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
457
+		        $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
458 458
 		        if ($reshook < 0) $error++;
459 459
 
460 460
 		        // Note: exit is done later
461 461
             }
462 462
         }
463 463
 
464
-        $usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",2));
465
-        $passwordtotest	= GETPOST('password','none',2);
466
-        $entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
464
+        $usertotest = (!empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username", "alpha", 2));
465
+        $passwordtotest = GETPOST('password', 'none', 2);
466
+        $entitytotest = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1));
467 467
 
468 468
         // Define if we received data to test the login.
469
-        $goontestloop=false;
470
-        if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
471
-        if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
472
-        if (GETPOST("username","alpha",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
469
+        $goontestloop = false;
470
+        if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true;
471
+        if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) $goontestloop = true;
472
+        if (GETPOST("username", "alpha", 2) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true;
473 473
 
474
-        if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
474
+        if (!is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
475 475
         {
476 476
             include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
477
-            $langs=new Translate("",$conf);
478
-    		$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
477
+            $langs = new Translate("", $conf);
478
+    		$langcode = (GETPOST('lang', 'aZ09', 1) ?GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT));
479 479
         	$langs->setDefaultLang($langcode);
480 480
         }
481 481
 
@@ -484,53 +484,53 @@  discard block
 block discarded – undo
484 484
         // If error, we will put error message in session under the name dol_loginmesg
485 485
         if ($test && $goontestloop)
486 486
         {
487
-        	$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
487
+        	$login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
488 488
         	if ($login)
489 489
             {
490
-                $dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
491
-                $dol_tz=$_POST["tz"];
492
-                $dol_tz_string=$_POST["tz_string"];
493
-                $dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
494
-                $dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
495
-                $dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
496
-                $dol_dst=0;
490
+                $dol_authmode = $conf->authmode; // This properties is defined only when logged, to say what mode was successfully used
491
+                $dol_tz = $_POST["tz"];
492
+                $dol_tz_string = $_POST["tz_string"];
493
+                $dol_tz_string = preg_replace('/\s*\(.+\)$/', '', $dol_tz_string);
494
+                $dol_tz_string = preg_replace('/,/', '/', $dol_tz_string);
495
+                $dol_tz_string = preg_replace('/\s/', '_', $dol_tz_string);
496
+                $dol_dst = 0;
497 497
                 if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
498 498
                 {
499 499
                     include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
500
-                    $datenow=dol_now();
501
-                    $datefirst=dol_stringtotime($_POST["dst_first"]);
502
-                    $datesecond=dol_stringtotime($_POST["dst_second"]);
503
-                    if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
500
+                    $datenow = dol_now();
501
+                    $datefirst = dol_stringtotime($_POST["dst_first"]);
502
+                    $datesecond = dol_stringtotime($_POST["dst_second"]);
503
+                    if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst = 1;
504 504
                 }
505 505
                 //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
506 506
             }
507 507
 
508
-            if (! $login)
508
+            if (!$login)
509 509
             {
510
-                dol_syslog('Bad password, connexion refused',LOG_DEBUG);
510
+                dol_syslog('Bad password, connexion refused', LOG_DEBUG);
511 511
                 $langs->load('main');
512 512
                 $langs->load('errors');
513 513
 
514 514
                 // Bad password. No authmode has found a good password.
515 515
                 // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
516
-                if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
516
+                if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword");
517 517
 
518 518
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
519
-                $user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
519
+                $user->trigger_mesg = $langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2);
520 520
                 // Call of triggers
521 521
                 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
522
-                $interface=new Interfaces($db);
523
-                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
522
+                $interface = new Interfaces($db);
523
+                $result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf, GETPOST("username", "alpha", 2));
524 524
                 if ($result < 0) {
525 525
                     $error++;
526 526
                 }
527 527
                 // End Call of triggers
528 528
 
529 529
                 // Hooks on failed login
530
-		        $action='';
530
+		        $action = '';
531 531
 		        $hookmanager->initHooks(array('login'));
532
-		        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
533
-		        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
532
+		        $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
533
+		        $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
534 534
 		        if ($reshook < 0) $error++;
535 535
 
536 536
 		        // Note: exit is done in next chapter
@@ -538,123 +538,123 @@  discard block
 block discarded – undo
538 538
         }
539 539
 
540 540
         // End test login / passwords
541
-        if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
541
+        if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
542 542
         {
543 543
             // No data to test login, so we show the login page
544 544
 			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
545 545
 			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
546
-        	else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
546
+        	else dol_loginfunction($langs, $conf, (!empty($mysoc) ? $mysoc : ''));
547 547
             exit;
548 548
         }
549 549
 
550
-        $resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
550
+        $resultFetchUser = $user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
551 551
         if ($resultFetchUser <= 0)
552 552
         {
553 553
             dol_syslog('User not found, connexion refused');
554 554
             session_destroy();
555 555
             session_name($sessionname);
556
-            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
557
-            session_start();    // Fixing the bug of register_globals here is useless since session is empty
556
+            session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie
557
+            session_start(); // Fixing the bug of register_globals here is useless since session is empty
558 558
 
559 559
             if ($resultFetchUser == 0)
560 560
             {
561 561
                 $langs->load('main');
562 562
                 $langs->load('errors');
563 563
 
564
-                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
564
+                $_SESSION["dol_loginmesg"] = $langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
565 565
 
566 566
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
567
-                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
567
+                $user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
568 568
             }
569 569
             if ($resultFetchUser < 0)
570 570
             {
571
-                $_SESSION["dol_loginmesg"]=$user->error;
571
+                $_SESSION["dol_loginmesg"] = $user->error;
572 572
 
573 573
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
574
-                $user->trigger_mesg=$user->error;
574
+                $user->trigger_mesg = $user->error;
575 575
             }
576 576
 
577 577
             // Call triggers
578
-            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
579
-            $interface=new Interfaces($db);
580
-            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
578
+            include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
579
+            $interface = new Interfaces($db);
580
+            $result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf);
581 581
             if ($result < 0) {
582 582
                 $error++;
583 583
             }
584 584
             // End call triggers
585 585
 
586 586
 	        // Hooks on failed login
587
-	        $action='';
587
+	        $action = '';
588 588
 	        $hookmanager->initHooks(array('login'));
589
-	        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
590
-	        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
589
+	        $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
590
+	        $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
591 591
 	        if ($reshook < 0) $error++;
592 592
 
593
-	        $paramsurl=array();
594
-	        if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
595
-	        if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
596
-	        if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
597
-            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
593
+	        $paramsurl = array();
594
+	        if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int');
595
+	        if (GETPOST('nojs', 'int'))        $paramsurl[] = 'nojs='.GETPOST('nojs', 'int');
596
+	        if (GETPOST('lang', 'aZ09'))       $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
597
+            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
598 598
             exit;
599 599
         }
600 600
     }
601 601
     else
602 602
     {
603 603
         // We are already into an authenticated session
604
-        $login=$_SESSION["dol_login"];
605
-        $entity=$_SESSION["dol_entity"];
604
+        $login = $_SESSION["dol_login"];
605
+        $entity = $_SESSION["dol_entity"];
606 606
         dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
607 607
 
608
-        $resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
608
+        $resultFetchUser = $user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
609 609
         if ($resultFetchUser <= 0)
610 610
         {
611 611
             // Account has been removed after login
612 612
             dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
613 613
             session_destroy();
614 614
             session_name($sessionname);
615
-            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
616
-            session_start();    // Fixing the bug of register_globals here is useless since session is empty
615
+            session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie
616
+            session_start(); // Fixing the bug of register_globals here is useless since session is empty
617 617
 
618 618
             if ($resultFetchUser == 0)
619 619
             {
620 620
                 $langs->load('main');
621 621
                 $langs->load('errors');
622 622
 
623
-                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
623
+                $_SESSION["dol_loginmesg"] = $langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
624 624
 
625 625
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
626
-                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
626
+                $user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
627 627
             }
628 628
             if ($resultFetchUser < 0)
629 629
             {
630
-                $_SESSION["dol_loginmesg"]=$user->error;
630
+                $_SESSION["dol_loginmesg"] = $user->error;
631 631
 
632 632
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
633
-                $user->trigger_mesg=$user->error;
633
+                $user->trigger_mesg = $user->error;
634 634
             }
635 635
 
636 636
             // TODO @deprecated Remove this. Hook must be used, not this trigger.
637 637
             // Call triggers
638
-            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
639
-            $interface=new Interfaces($db);
640
-            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
638
+            include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
639
+            $interface = new Interfaces($db);
640
+            $result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf);
641 641
             if ($result < 0) {
642 642
                 $error++;
643 643
             }
644 644
             // End call triggers
645 645
 
646 646
 	        // Hooks on failed login
647
-	        $action='';
647
+	        $action = '';
648 648
 	        $hookmanager->initHooks(array('login'));
649
-	        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
650
-	        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
649
+	        $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
650
+	        $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
651 651
 	        if ($reshook < 0) $error++;
652 652
 
653
-	        $paramsurl=array();
654
-	        if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
655
-	        if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
656
-	        if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
657
-            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
653
+	        $paramsurl = array();
654
+	        if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int');
655
+	        if (GETPOST('nojs', 'int'))        $paramsurl[] = 'nojs='.GETPOST('nojs', 'int');
656
+	        if (GETPOST('lang', 'aZ09'))       $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
657
+            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
658 658
             exit;
659 659
         }
660 660
         else
@@ -663,19 +663,19 @@  discard block
 block discarded – undo
663 663
 	       $hookmanager->initHooks(array('main'));
664 664
 
665 665
 	       // Code for search criteria persistence.
666
-	       if (! empty($_GET['save_lastsearch_values']))    // Keep $_GET here
666
+	       if (!empty($_GET['save_lastsearch_values']))    // Keep $_GET here
667 667
 	       {
668
-               $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
669
-               $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
668
+               $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]);
669
+               $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server
670 670
                // Clean $relativepathstring
671
-   	           if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
671
+   	           if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
672 672
                $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
673 673
                $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
674 674
                //var_dump($relativepathstring);
675 675
 
676
-               if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
676
+               if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
677 677
                {
678
-                   $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
678
+                   $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring];
679 679
                    unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
680 680
                }
681 681
 	       }
@@ -690,30 +690,30 @@  discard block
 block discarded – undo
690 690
 
691 691
     // Is it a new session that has started ?
692 692
     // If we are here, this means authentication was successfull.
693
-    if (! isset($_SESSION["dol_login"]))
693
+    if (!isset($_SESSION["dol_login"]))
694 694
     {
695 695
         // New session for this login has started.
696
-    	$error=0;
696
+    	$error = 0;
697 697
 
698 698
     	// Store value into session (values always stored)
699
-        $_SESSION["dol_login"]=$user->login;
700
-        $_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
701
-        $_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
702
-        $_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
703
-        $_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
704
-        $_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
705
-        $_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
706
-        $_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
707
-        $_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
708
-        $_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
709
-        $_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
710
-        $_SESSION["dol_entity"]=$conf->entity;
699
+        $_SESSION["dol_login"] = $user->login;
700
+        $_SESSION["dol_authmode"] = isset($dol_authmode) ? $dol_authmode : '';
701
+        $_SESSION["dol_tz"] = isset($dol_tz) ? $dol_tz : '';
702
+        $_SESSION["dol_tz_string"] = isset($dol_tz_string) ? $dol_tz_string : '';
703
+        $_SESSION["dol_dst"] = isset($dol_dst) ? $dol_dst : '';
704
+        $_SESSION["dol_dst_observed"] = isset($dol_dst_observed) ? $dol_dst_observed : '';
705
+        $_SESSION["dol_dst_first"] = isset($dol_dst_first) ? $dol_dst_first : '';
706
+        $_SESSION["dol_dst_second"] = isset($dol_dst_second) ? $dol_dst_second : '';
707
+        $_SESSION["dol_screenwidth"] = isset($dol_screenwidth) ? $dol_screenwidth : '';
708
+        $_SESSION["dol_screenheight"] = isset($dol_screenheight) ? $dol_screenheight : '';
709
+        $_SESSION["dol_company"] = $conf->global->MAIN_INFO_SOCIETE_NOM;
710
+        $_SESSION["dol_entity"] = $conf->entity;
711 711
     	// Store value into session (values stored only if defined)
712
-        if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
713
-        if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
714
-        if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
715
-        if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
716
-        if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
712
+        if (!empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu;
713
+        if (!empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu;
714
+        if (!empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen;
715
+        if (!empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover;
716
+        if (!empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile'] = $dol_use_jmobile;
717 717
 
718 718
         dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
719 719
 
@@ -726,26 +726,26 @@  discard block
 block discarded – undo
726 726
         // TODO @deprecated Remove this. Hook must be used, not this trigger.
727 727
         $user->trigger_mesg = $loginfo;
728 728
         // Call triggers
729
-        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
730
-        $interface=new Interfaces($db);
731
-        $result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
729
+        include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
730
+        $interface = new Interfaces($db);
731
+        $result = $interface->run_triggers('USER_LOGIN', $user, $user, $langs, $conf);
732 732
         if ($result < 0) {
733 733
             $error++;
734 734
         }
735 735
         // End call triggers
736 736
 
737 737
         // Hooks on successfull login
738
-        $action='';
738
+        $action = '';
739 739
         $hookmanager->initHooks(array('login'));
740
-        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
741
-        $reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
740
+        $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
741
+        $reshook = $hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
742 742
         if ($reshook < 0) $error++;
743 743
 
744 744
         if ($error)
745 745
         {
746 746
             $db->rollback();
747 747
             session_destroy();
748
-            dol_print_error($db,'Error in some hooks afterLogin (or old trigger USER_LOGIN)');
748
+            dol_print_error($db, 'Error in some hooks afterLogin (or old trigger USER_LOGIN)');
749 749
             exit;
750 750
         }
751 751
         else
@@ -754,10 +754,10 @@  discard block
 block discarded – undo
754 754
         }
755 755
 
756 756
         // Change landing page if defined.
757
-        $landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
758
-        if (! empty($landingpage))    // Example: /index.php
757
+        $landingpage = (empty($user->conf->MAIN_LANDING_PAGE) ? (empty($conf->global->MAIN_LANDING_PAGE) ? '' : $conf->global->MAIN_LANDING_PAGE) : $user->conf->MAIN_LANDING_PAGE);
758
+        if (!empty($landingpage))    // Example: /index.php
759 759
         {
760
-            $newpath=dol_buildpath($landingpage, 1);
760
+            $newpath = dol_buildpath($landingpage, 1);
761 761
             if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
762 762
             {
763 763
                 header('Location: '.$newpath);
@@ -770,12 +770,12 @@  discard block
 block discarded – undo
770 770
     // If user admin, we force the rights-based modules
771 771
     if ($user->admin)
772 772
     {
773
-        $user->rights->user->user->lire=1;
774
-        $user->rights->user->user->creer=1;
775
-        $user->rights->user->user->password=1;
776
-        $user->rights->user->user->supprimer=1;
777
-        $user->rights->user->self->creer=1;
778
-        $user->rights->user->self->password=1;
773
+        $user->rights->user->user->lire = 1;
774
+        $user->rights->user->user->creer = 1;
775
+        $user->rights->user->user->password = 1;
776
+        $user->rights->user->user->supprimer = 1;
777
+        $user->rights->user->self->creer = 1;
778
+        $user->rights->user->self->password = 1;
779 779
     }
780 780
 
781 781
     /*
@@ -783,70 +783,70 @@  discard block
 block discarded – undo
783 783
      */
784 784
 
785 785
     // Set liste_limit
786
-    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
787
-    if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
786
+    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0
787
+    if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0
788 788
 
789 789
     // Replace conf->css by personalized value if theme not forced
790
-    if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
790
+    if (empty($conf->global->MAIN_FORCETHEME) && !empty($user->conf->MAIN_THEME))
791 791
     {
792
-        $conf->theme=$user->conf->MAIN_THEME;
792
+        $conf->theme = $user->conf->MAIN_THEME;
793 793
         $conf->css  = "/theme/".$conf->theme."/style.css.php";
794 794
     }
795 795
 }
796 796
 
797 797
 // Case forcing style from url
798
-if (GETPOST('theme','alpha'))
798
+if (GETPOST('theme', 'alpha'))
799 799
 {
800
-	$conf->theme=GETPOST('theme','alpha',1);
800
+	$conf->theme = GETPOST('theme', 'alpha', 1);
801 801
 	$conf->css  = "/theme/".$conf->theme."/style.css.php";
802 802
 }
803 803
 
804 804
 
805 805
 // Set javascript option
806
-if (! GETPOST('nojs','int'))   // If javascript was not disabled on URL
806
+if (!GETPOST('nojs', 'int'))   // If javascript was not disabled on URL
807 807
 {
808
-	if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
808
+	if (!empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
809 809
 	{
810
-		$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
810
+		$conf->use_javascript_ajax = !$user->conf->MAIN_DISABLE_JAVASCRIPT;
811 811
 	}
812 812
 }
813
-else $conf->use_javascript_ajax=0;
813
+else $conf->use_javascript_ajax = 0;
814 814
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
815
-if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
815
+if (GETPOST('textbrowser', 'int') || (!empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || !empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
816 816
 {
817
-    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
817
+    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = 1;
818 818
 }
819 819
 
820 820
 // Set terminal output option according to conf->browser.
821
-if (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu']))               $conf->dol_hide_leftmenu=1;
822
-if (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu']))                 $conf->dol_hide_topmenu=1;
823
-if (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1;
824
-if (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover']))             $conf->dol_no_mouse_hover=1;
825
-if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile=1;
826
-if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;
827
-if ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')
828
-	|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
829
-	|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
821
+if (GETPOST('dol_hide_leftmenu', 'int') || !empty($_SESSION['dol_hide_leftmenu']))               $conf->dol_hide_leftmenu = 1;
822
+if (GETPOST('dol_hide_topmenu', 'int') || !empty($_SESSION['dol_hide_topmenu']))                 $conf->dol_hide_topmenu = 1;
823
+if (GETPOST('dol_optimize_smallscreen', 'int') || !empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen = 1;
824
+if (GETPOST('dol_no_mouse_hover', 'int') || !empty($_SESSION['dol_no_mouse_hover']))             $conf->dol_no_mouse_hover = 1;
825
+if (GETPOST('dol_use_jmobile', 'int') || !empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile = 1;
826
+if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover = 1;
827
+if ((!empty($conf->browser->layout) && $conf->browser->layout == 'phone')
828
+	|| (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
829
+	|| (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
830 830
 )
831 831
 {
832
-	$conf->dol_optimize_smallscreen=1;
832
+	$conf->dol_optimize_smallscreen = 1;
833 833
 }
834 834
 // If we force to use jmobile, then we reenable javascript
835
-if (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;
835
+if (!empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax = 1;
836 836
 // Replace themes bugged with jmobile with eldy
837
-if (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))
837
+if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok')))
838 838
 {
839
-	$conf->theme='eldy';
840
-	$conf->css  =  "/theme/".$conf->theme."/style.css.php";
839
+	$conf->theme = 'eldy';
840
+	$conf->css  = "/theme/".$conf->theme."/style.css.php";
841 841
 }
842 842
 //var_dump($conf->browser->phone);
843 843
 
844
-if (! defined('NOREQUIRETRAN'))
844
+if (!defined('NOREQUIRETRAN'))
845 845
 {
846
-    if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
846
+    if (!GETPOST('lang', 'aZ09'))	// If language was not forced on URL
847 847
     {
848 848
         // If user has chosen its own language
849
-        if (! empty($user->conf->MAIN_LANG_DEFAULT))
849
+        if (!empty($user->conf->MAIN_LANG_DEFAULT))
850 850
         {
851 851
             // If different than current language
852 852
             //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
@@ -858,11 +858,11 @@  discard block
 block discarded – undo
858 858
     }
859 859
 }
860 860
 
861
-if (! defined('NOLOGIN'))
861
+if (!defined('NOLOGIN'))
862 862
 {
863 863
     // If the login is not recovered, it is identified with an account that does not exist.
864 864
     // Hacking attempt?
865
-    if (! $user->login) accessforbidden();
865
+    if (!$user->login) accessforbidden();
866 866
 
867 867
     // Check if user is active
868 868
     if ($user->statut < 1)
@@ -879,88 +879,88 @@  discard block
 block discarded – undo
879 879
 }
880 880
 
881 881
 
882
-dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.GETPOST('action','az09').', massaction='.GETPOST('massaction','az09'));
882
+dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.GETPOST('action', 'az09').', massaction='.GETPOST('massaction', 'az09'));
883 883
 //Another call for easy debugg
884 884
 //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));
885 885
 
886 886
 // Load main languages files
887
-if (! defined('NOREQUIRETRAN'))
887
+if (!defined('NOREQUIRETRAN'))
888 888
 {
889 889
     $langs->load("main");
890 890
     $langs->load("dict");
891 891
 }
892 892
 
893 893
 // Define some constants used for style of arrays
894
-$bc=array(0=>'class="impair"',1=>'class="pair"');
895
-$bcdd=array(0=>'class="drag drop oddeven"',1=>'class="drag drop oddeven"');
896
-$bcnd=array(0=>'class="nodrag nodrop nohover"',1=>'class="nodrag nodrop nohoverpair"');		// Used for tr to add new lines
897
-$bctag=array(0=>'class="impair tagtr"',1=>'class="pair tagtr"');
894
+$bc = array(0=>'class="impair"', 1=>'class="pair"');
895
+$bcdd = array(0=>'class="drag drop oddeven"', 1=>'class="drag drop oddeven"');
896
+$bcnd = array(0=>'class="nodrag nodrop nohover"', 1=>'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines
897
+$bctag = array(0=>'class="impair tagtr"', 1=>'class="pair tagtr"');
898 898
 
899 899
 // Define messages variables
900
-$mesg=''; $warning=''; $error=0;
900
+$mesg = ''; $warning = ''; $error = 0;
901 901
 // deprecated, see setEventMessages() and dol_htmloutput_events()
902
-$mesgs=array(); $warnings=array(); $errors=array();
902
+$mesgs = array(); $warnings = array(); $errors = array();
903 903
 
904 904
 // Constants used to defined number of lines in textarea
905 905
 if (empty($conf->browser->firefox))
906 906
 {
907
-    define('ROWS_1',1);
908
-    define('ROWS_2',2);
909
-    define('ROWS_3',3);
910
-    define('ROWS_4',4);
911
-    define('ROWS_5',5);
912
-    define('ROWS_6',6);
913
-    define('ROWS_7',7);
914
-    define('ROWS_8',8);
915
-    define('ROWS_9',9);
907
+    define('ROWS_1', 1);
908
+    define('ROWS_2', 2);
909
+    define('ROWS_3', 3);
910
+    define('ROWS_4', 4);
911
+    define('ROWS_5', 5);
912
+    define('ROWS_6', 6);
913
+    define('ROWS_7', 7);
914
+    define('ROWS_8', 8);
915
+    define('ROWS_9', 9);
916 916
 }
917 917
 else
918 918
 {
919
-    define('ROWS_1',0);
920
-    define('ROWS_2',1);
921
-    define('ROWS_3',2);
922
-    define('ROWS_4',3);
923
-    define('ROWS_5',4);
924
-    define('ROWS_6',5);
925
-    define('ROWS_7',6);
926
-    define('ROWS_8',7);
927
-    define('ROWS_9',8);
919
+    define('ROWS_1', 0);
920
+    define('ROWS_2', 1);
921
+    define('ROWS_3', 2);
922
+    define('ROWS_4', 3);
923
+    define('ROWS_5', 4);
924
+    define('ROWS_6', 5);
925
+    define('ROWS_7', 6);
926
+    define('ROWS_8', 7);
927
+    define('ROWS_9', 8);
928 928
 }
929 929
 
930
-$heightforframes=48;
930
+$heightforframes = 48;
931 931
 
932 932
 // Init menu manager
933
-if (! defined('NOREQUIREMENU'))
933
+if (!defined('NOREQUIREMENU'))
934 934
 {
935 935
 	if (empty($user->societe_id))    // If internal user or not defined
936 936
 	{
937
-		$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
937
+		$conf->standard_menu = (empty($conf->global->MAIN_MENU_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENU_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENU_STANDARD) : $conf->global->MAIN_MENU_STANDARD_FORCED);
938 938
 	}
939 939
 	else                        // If external user
940 940
 	{
941
-		$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
941
+		$conf->standard_menu = (empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENUFRONT_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENUFRONT_STANDARD) : $conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
942 942
 	}
943 943
 
944 944
 	// Load the menu manager (only if not already done)
945
-	$file_menu=$conf->standard_menu;
946
-	if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
947
-	if (! class_exists('MenuManager'))
945
+	$file_menu = $conf->standard_menu;
946
+	if (GETPOST('menu', 'alpha')) $file_menu = GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php
947
+	if (!class_exists('MenuManager'))
948 948
 	{
949
-		$menufound=0;
950
-		$dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']);
951
-		foreach($dirmenus as $dirmenu)
949
+		$menufound = 0;
950
+		$dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']);
951
+		foreach ($dirmenus as $dirmenu)
952 952
 		{
953
-			$menufound=dol_include_once($dirmenu."standard/".$file_menu);
953
+			$menufound = dol_include_once($dirmenu."standard/".$file_menu);
954 954
 			if (class_exists('MenuManager')) break;
955 955
 		}
956
-		if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
956
+		if (!class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
957 957
 		{
958 958
 			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
959
-			$file_menu='eldy_menu.php';
959
+			$file_menu = 'eldy_menu.php';
960 960
 			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
961 961
 		}
962 962
 	}
963
-	$menumanager = new MenuManager($db, empty($user->societe_id)?0:1);
963
+	$menumanager = new MenuManager($db, empty($user->societe_id) ? 0 : 1);
964 964
 	$menumanager->loadMenu();
965 965
 }
966 966
 
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
 
969 969
 // Functions
970 970
 
971
-if (! function_exists("llxHeader"))
971
+if (!function_exists("llxHeader"))
972 972
 {
973 973
     /**
974 974
      *	Show HTML header HTML + BODY + Top menu + left menu + DIV
@@ -987,14 +987,14 @@  discard block
 block discarded – undo
987 987
      * @param   string  $morecssonbody      More CSS on body tag.
988 988
      * @return	void
989 989
      */
990
-	function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='')
990
+	function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '')
991 991
 	{
992 992
 	    global $conf;
993 993
 
994 994
 	    // html header
995 995
 		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
996 996
 
997
-        print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
997
+        print '<body id="mainbody"'.($morecssonbody ? ' class="'.$morecssonbody.'"' : '').'>'."\n";
998 998
 
999 999
 		// top menu and left menu area
1000 1000
 		if (empty($conf->dol_hide_topmenu))
@@ -1019,16 +1019,16 @@  discard block
 block discarded – undo
1019 1019
  *  @param  string  $contenttype    Content type. For example, 'text/html'
1020 1020
  *  @return	void
1021 1021
  */
1022
-function top_httphead($contenttype='text/html')
1022
+function top_httphead($contenttype = 'text/html')
1023 1023
 {
1024 1024
     global $conf;
1025 1025
 
1026
-    if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1026
+    if ($contenttype == 'text/html') header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1027 1027
     else header("Content-Type: ".$contenttype);
1028 1028
     // Security options
1029
-    header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1030
-    header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1031
-    if (! empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1029
+    header("X-Content-Type-Options: nosniff"); // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1030
+    header("X-Frame-Options: SAMEORIGIN"); // Frames allowed only if on same domain (stop some XSS attacks)
1031
+    if (!empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1032 1032
     {
1033 1033
         // For example, to restrict script, object, frames or img to some domains
1034 1034
         // script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; child-src https://youtube.com; img-src: https://static.example.com
@@ -1058,73 +1058,73 @@  discard block
 block discarded – undo
1058 1058
  * @param   int     $disablenofollow Disable no follow tag
1059 1059
  * @return	void
1060 1060
  */
1061
-function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)
1061
+function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $disablejmobile = 0, $disablenofollow = 0)
1062 1062
 {
1063 1063
     global $user, $conf, $langs, $db;
1064 1064
 
1065 1065
     top_httphead();
1066 1066
 
1067
-    if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1067
+    if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default
1068 1068
 
1069
-    if (! empty($conf->global->MAIN_ACTIVATE_HTML4)) {
1069
+    if (!empty($conf->global->MAIN_ACTIVATE_HTML4)) {
1070 1070
         $doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
1071
-    }else {
1071
+    } else {
1072 1072
         $doctype = '<!doctype html>';
1073 1073
     }
1074 1074
     print $doctype."\n";
1075
-    if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1076
-    else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1075
+    if (!empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang, 0, 2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1076
+    else print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n";
1077 1077
     //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1078 1078
     if (empty($disablehead))
1079 1079
     {
1080 1080
         print "<head>\n";
1081
-		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1081
+		if (GETPOST('dol_basehref', 'alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n";
1082 1082
         // Displays meta
1083
-        print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";      				// Do not index
1084
-        print '<meta name="viewport" content="width=device-width, initial-scale=1.0">';	// Scale for mobile device
1083
+        print '<meta name="robots" content="noindex'.($disablenofollow ? '' : ',nofollow').'">'."\n"; // Do not index
1084
+        print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'; // Scale for mobile device
1085 1085
         print '<meta name="author" content="Dolibarr Development Team">'."\n";
1086 1086
         // Favicon
1087
-		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1088
-        if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1089
-        if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1087
+		$favicon = dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico', 1);
1088
+        if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL;
1089
+        if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview
1090 1090
         //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1091
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1092
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1091
+        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !GETPOST('textbrowser', 'int')) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1092
+        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !GETPOST('textbrowser', 'int')) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1093 1093
 
1094 1094
         // Displays title
1095
-        $appli=constant('DOL_APPLICATION_TITLE');
1096
-        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1095
+        $appli = constant('DOL_APPLICATION_TITLE');
1096
+        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE;
1097 1097
 
1098
-        if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';
1098
+        if ($title && !empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/', $conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';
1099 1099
         else if ($title) print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';
1100 1100
         else print "<title>".dol_htmlentities($appli)."</title>";
1101 1101
         print "\n";
1102 1102
 
1103 1103
         //$ext='';
1104 1104
         //if (! empty($conf->dol_use_jmobile)) $ext='version='.urlencode(DOL_VERSION);
1105
-        $ext='version='.urlencode(DOL_VERSION);
1105
+        $ext = 'version='.urlencode(DOL_VERSION);
1106 1106
 
1107
-        if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1108
-        if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1107
+        if (GETPOST('version', 'int')) $ext = 'version='.GETPOST('version', 'int'); // usefull to force no cache on css/js
1108
+        if (GETPOST('testmenuhider', 'int') || !empty($conf->global->MAIN_TESTMENUHIDER)) $ext .= '&testmenuhider='.(GETPOST('testmenuhider', 'int') ?GETPOST('testmenuhider', 'int') : $conf->global->MAIN_TESTMENUHIDER);
1109 1109
 
1110
-        $themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1111
-        $themeparam.=($ext?'&amp;'.$ext:'');
1112
-        if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1113
-        if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1114
-        if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1115
-        if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1116
-        if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1117
-        if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1110
+        $themeparam = '?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss', 'aZ09') ? '&amp;optioncss='.GETPOST('optioncss', 'aZ09', 1) : '').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1111
+        $themeparam .= ($ext ? '&amp;'.$ext : '');
1112
+        if (!empty($_SESSION['dol_resetcache'])) $themeparam .= '&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1113
+        if (GETPOST('dol_hide_topmenu', 'int')) { $themeparam .= '&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu', 'int'); }
1114
+        if (GETPOST('dol_hide_leftmenu', 'int')) { $themeparam .= '&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu', 'int'); }
1115
+        if (GETPOST('dol_optimize_smallscreen', 'int')) { $themeparam .= '&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen', 'int'); }
1116
+        if (GETPOST('dol_no_mouse_hover', 'int')) { $themeparam .= '&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover', 'int'); }
1117
+        if (GETPOST('dol_use_jmobile', 'int')) { $themeparam .= '&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile', 'int'); $conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); }
1118 1118
 
1119
-        if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1119
+        if (!defined('DISABLE_JQUERY') && !$disablejs && $conf->use_javascript_ajax)
1120 1120
         {
1121 1121
             print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1122 1122
             $jquerytheme = 'smoothness';
1123 1123
             if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1124
-            if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1125
-            else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1126
-            if (! defined('DISABLE_JQUERY_TIPTIP')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/tipTip.css'.($ext?'?'.$ext:'').'">'."\n";                           // Tooltip
1127
-            if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1124
+            if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery
1125
+            else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery
1126
+            if (!defined('DISABLE_JQUERY_TIPTIP')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/tipTip.css'.($ext ? '?'.$ext : '').'">'."\n"; // Tooltip
1127
+            if (!defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JNotify
1128 1128
             /* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
1129 1129
             if (! empty($conf->global->MAIN_USE_JQUERY_DATATABLES) || (defined('REQUIRE_JQUERY_DATATABLES') && constant('REQUIRE_JQUERY_DATATABLES')))     // jQuery datatables
1130 1130
             {
@@ -1132,58 +1132,58 @@  discard block
 block discarded – undo
1132 1132
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/Buttons/css/buttons.dataTables.min.css'.($ext?'?'.$ext:'').'">'."\n";
1133 1133
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/ColReorder/css/colReorder.dataTables.min.css'.($ext?'?'.$ext:'').'"></script>'."\n";
1134 1134
             }*/
1135
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1135
+            if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1136 1136
             {
1137
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1138
-            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1137
+            	$tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
1138
+            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.css'.($ext ? '?'.$ext : '').'">'."\n";
1139 1139
             }
1140 1140
             // jQuery Timepicker
1141
-            if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1141
+            if (!empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1142 1142
             {
1143
-            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.css'.($ext?'?'.$ext:'').'">'."\n";
1143
+            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.css'.($ext ? '?'.$ext : '').'">'."\n";
1144 1144
             }
1145 1145
         }
1146 1146
 
1147
-        if (! defined('DISABLE_FONT_AWSOME'))
1147
+        if (!defined('DISABLE_FONT_AWSOME'))
1148 1148
         {
1149 1149
             print '<!-- Includes CSS for font awesome -->'."\n";
1150
-            print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1150
+            print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext ? '?'.$ext : '').'">'."\n";
1151 1151
         }
1152 1152
 
1153 1153
         print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1154 1154
         // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1155
-        $themepath=dol_buildpath($conf->css,1);
1156
-        $themesubdir='';
1157
-        if (! empty($conf->modules_parts['theme']))	// This slow down
1155
+        $themepath = dol_buildpath($conf->css, 1);
1156
+        $themesubdir = '';
1157
+        if (!empty($conf->modules_parts['theme']))	// This slow down
1158 1158
         {
1159
-	        foreach($conf->modules_parts['theme'] as $reldir)
1159
+	        foreach ($conf->modules_parts['theme'] as $reldir)
1160 1160
 	        {
1161 1161
 	        	if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1162 1162
 	        	{
1163
-					$themepath=dol_buildpath($reldir.$conf->css, 1);
1164
-					$themesubdir=$reldir;
1163
+					$themepath = dol_buildpath($reldir.$conf->css, 1);
1164
+					$themesubdir = $reldir;
1165 1165
 					break;
1166 1166
 	        	}
1167 1167
 	        }
1168 1168
         }
1169 1169
         //print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1170 1170
         print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1171
-	    if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1171
+	    if (!empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1172 1172
 
1173 1173
         // CSS forced by modules (relative url starting with /)
1174
-        if (! empty($conf->modules_parts['css']))
1174
+        if (!empty($conf->modules_parts['css']))
1175 1175
         {
1176
-        	$arraycss=(array) $conf->modules_parts['css'];
1177
-        	foreach($arraycss as $modcss => $filescss)
1176
+        	$arraycss = (array) $conf->modules_parts['css'];
1177
+        	foreach ($arraycss as $modcss => $filescss)
1178 1178
         	{
1179
-        		$filescss=(array) $filescss;	// To be sure filecss is an array
1180
-        		foreach($filescss as $cssfile)
1179
+        		$filescss = (array) $filescss; // To be sure filecss is an array
1180
+        		foreach ($filescss as $cssfile)
1181 1181
         		{
1182 1182
         			if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1183 1183
         			// cssfile is a relative path
1184
-	        		print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1184
+	        		print '<!-- Includes CSS added by module '.$modcss.' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile, 1);
1185 1185
 	        		// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1186
-	        		if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1186
+	        		if (!preg_match('/\.css$/i', $cssfile)) print $themeparam;
1187 1187
 	        		print '">'."\n";
1188 1188
         		}
1189 1189
         	}
@@ -1191,72 +1191,72 @@  discard block
 block discarded – undo
1191 1191
         // CSS forced by page in top_htmlhead call (relative url starting with /)
1192 1192
         if (is_array($arrayofcss))
1193 1193
         {
1194
-            foreach($arrayofcss as $cssfile)
1194
+            foreach ($arrayofcss as $cssfile)
1195 1195
             {
1196
-            	print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1196
+            	print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile, 1);
1197 1197
                 // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1198
-                if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1198
+                if (!preg_match('/\.css$/i', $cssfile)) print $themeparam;
1199 1199
                 print '">'."\n";
1200 1200
             }
1201 1201
         }
1202 1202
 
1203 1203
         // Output standard javascript links
1204
-        if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1204
+        if (!defined('DISABLE_JQUERY') && !$disablejs && !empty($conf->use_javascript_ajax))
1205 1205
         {
1206 1206
             // JQuery. Must be before other includes
1207 1207
             print '<!-- Includes JS for JQuery -->'."\n";
1208
-            if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1209
-            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1210
-            if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1208
+            if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1209
+            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1210
+            if (!empty($conf->global->MAIN_FEATURES_LEVEL) && !defined('JS_JQUERY_MIGRATE_DISABLED'))
1211 1211
             {
1212
-                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1213
-                else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1212
+                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1213
+                else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1214 1214
             }
1215
-            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1216
-            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1217
-            if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.0.6.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1218
-            if (! defined('DISABLE_JQUERY_TIPTIP')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/jquery.tipTip.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1215
+            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1216
+            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1217
+            if (!defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.0.6.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1218
+            if (!defined('DISABLE_JQUERY_TIPTIP')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/jquery.tipTip.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1219 1219
             // jQuery jnotify
1220
-            if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1220
+            if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY'))
1221 1221
             {
1222
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1223
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/jnotify.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1222
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1223
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/jnotify.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1224 1224
             }
1225 1225
             // Flot
1226
-            if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1226
+            if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && !defined('DISABLE_JQUERY_FLOT'))
1227 1227
             {
1228 1228
                 if (constant('JS_JQUERY_FLOT'))
1229 1229
                 {
1230
-                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1231
-                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1232
-                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1230
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1231
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1232
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1233 1233
                 }
1234 1234
                 else
1235 1235
                 {
1236
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1237
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1238
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1236
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1237
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1238
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1239 1239
                 }
1240 1240
             }
1241 1241
             // jQuery jeditable
1242
-            if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1242
+            if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !defined('DISABLE_JQUERY_JEDITABLE'))
1243 1243
             {
1244 1244
             	print '<!-- JS to manage editInPlace feature -->'."\n";
1245
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1246
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1247
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1245
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1246
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1247
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1248 1248
                 print '<script type="text/javascript">'."\n";
1249 1249
                 print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1250 1250
                 print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1251
-                print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1252
-                print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1251
+                print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n"; // Added in title attribute of span
1252
+                print 'var placeholderInPlace = \'&nbsp;\';'."\n"; // If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1253 1253
                 print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1254 1254
                 print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1255 1255
                 print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1256
-                print 'var withInPlace = 300;';		// width in pixel for default string edit
1256
+                print 'var withInPlace = 300;'; // width in pixel for default string edit
1257 1257
                 print '</script>'."\n";
1258
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1259
-                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1258
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1259
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1260 1260
             }
1261 1261
             // jQuery DataTables
1262 1262
             /* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
@@ -1272,55 +1272,55 @@  discard block
 block discarded – undo
1272 1272
                 print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jszip/jszip.min.js"></script>'."\n";
1273 1273
             }*/
1274 1274
             // jQuery Timepicker
1275
-            if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1275
+            if (!empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1276 1276
             {
1277
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1278
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1277
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1278
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
1279 1279
             }
1280
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1280
+            if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1281 1281
             {
1282
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1283
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1282
+            	$tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
1283
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1284 1284
             }
1285 1285
         }
1286 1286
 
1287
-        if (! $disablejs && ! empty($conf->use_javascript_ajax))
1287
+        if (!$disablejs && !empty($conf->use_javascript_ajax))
1288 1288
         {
1289 1289
             // CKEditor
1290
-            if (! empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && ! defined('DISABLE_CKEDITOR'))
1290
+            if (!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR'))
1291 1291
             {
1292 1292
                 print '<!-- Includes JS for CKEditor -->'."\n";
1293
-                $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
1294
-                $jsckeditor='ckeditor.js';
1293
+                $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/';
1294
+                $jsckeditor = 'ckeditor.js';
1295 1295
                 if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1296 1296
                 {
1297
-                	$pathckeditor=constant('JS_CKEDITOR');
1297
+                	$pathckeditor = constant('JS_CKEDITOR');
1298 1298
                 }
1299 1299
                 print '<script type="text/javascript">';
1300 1300
                 print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1301
-                print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\';'."\n";		// $themesubdir='' in standard usage
1301
+                print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext ? '?'.$ext : ''), 1).'\';'."\n"; // $themesubdir='' in standard usage
1302 1302
                 print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1303 1303
                 print 'var ckeditorFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1304 1304
                 print '</script>'."\n";
1305
-                print '<script type="text/javascript" src="'.$pathckeditor.$jsckeditor.($ext?'?'.$ext:'').'"></script>'."\n";
1305
+                print '<script type="text/javascript" src="'.$pathckeditor.$jsckeditor.($ext ? '?'.$ext : '').'"></script>'."\n";
1306 1306
             }
1307 1307
 
1308 1308
             // Browser notifications
1309
-            if (! defined('DISABLE_BROWSER_NOTIF'))
1309
+            if (!defined('DISABLE_BROWSER_NOTIF'))
1310 1310
             {
1311
-                $enablebrowsernotif=false;
1312
-                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;
1313
-                if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
1311
+                $enablebrowsernotif = false;
1312
+                if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif = true;
1313
+                if ($conf->browser->layout == 'phone') $enablebrowsernotif = false;
1314 1314
                 if ($enablebrowsernotif)
1315 1315
                 {
1316 1316
                     print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
1317
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext?'?'.$ext:'').'"></script>'."\n";
1317
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext ? '?'.$ext : '').'"></script>'."\n";
1318 1318
                 }
1319 1319
             }
1320 1320
 
1321 1321
             // Global js function
1322 1322
             print '<!-- Includes JS of Dolibarr -->'."\n";
1323
-            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1323
+            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
1324 1324
 
1325 1325
             // Add datepicker default options
1326 1326
             /*if (! defined('DISABLE_DATE_PICKER'))
@@ -1329,16 +1329,16 @@  discard block
 block discarded – undo
1329 1329
             }*/
1330 1330
 
1331 1331
             // JS forced by modules (relative url starting with /)
1332
-            if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1332
+            if (!empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1333 1333
         	{
1334
-        		$arrayjs=(array) $conf->modules_parts['js'];
1335
-	            foreach($arrayjs as $modjs => $filesjs)
1334
+        		$arrayjs = (array) $conf->modules_parts['js'];
1335
+	            foreach ($arrayjs as $modjs => $filesjs)
1336 1336
 	            {
1337
-        			$filesjs=(array) $filesjs;	// To be sure filejs is an array
1338
-		            foreach($filesjs as $jsfile)
1337
+        			$filesjs = (array) $filesjs; // To be sure filejs is an array
1338
+		            foreach ($filesjs as $jsfile)
1339 1339
 		            {
1340 1340
 	    	    		// jsfile is a relative path
1341
-	        	    	print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1341
+	        	    	print '<!-- Include JS added by module '.$modjs.'-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile, 1).'"></script>'."\n";
1342 1342
 		            }
1343 1343
 	            }
1344 1344
         	}
@@ -1346,28 +1346,28 @@  discard block
 block discarded – undo
1346 1346
             if (is_array($arrayofjs))
1347 1347
             {
1348 1348
                 print '<!-- Includes JS added by page -->'."\n";
1349
-                foreach($arrayofjs as $jsfile)
1349
+                foreach ($arrayofjs as $jsfile)
1350 1350
                 {
1351
-                    if (preg_match('/^http/i',$jsfile))
1351
+                    if (preg_match('/^http/i', $jsfile))
1352 1352
                     {
1353 1353
                         print '<script type="text/javascript" src="'.$jsfile.'"></script>'."\n";
1354 1354
                     }
1355 1355
                     else
1356 1356
                     {
1357
-                        if (! preg_match('/^\//',$jsfile)) $jsfile='/'.$jsfile;	// For backward compatibility
1358
-                        print '<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1357
+                        if (!preg_match('/^\//', $jsfile)) $jsfile = '/'.$jsfile; // For backward compatibility
1358
+                        print '<script type="text/javascript" src="'.dol_buildpath($jsfile, 1).'"></script>'."\n";
1359 1359
                     }
1360 1360
                 }
1361 1361
             }
1362 1362
         }
1363 1363
 
1364
-        if (! empty($head)) print $head."\n";
1365
-        if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1364
+        if (!empty($head)) print $head."\n";
1365
+        if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1366 1366
 
1367 1367
         print "</head>\n\n";
1368 1368
     }
1369 1369
 
1370
-    $conf->headerdone=1;	// To tell header was output
1370
+    $conf->headerdone = 1; // To tell header was output
1371 1371
 }
1372 1372
 
1373 1373
 
@@ -1387,19 +1387,19 @@  discard block
 block discarded – undo
1387 1387
  * 									                   For other external page: http://server/url
1388 1388
  *  @return		void
1389 1389
  */
1390
-function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')
1390
+function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $helppagename = '')
1391 1391
 {
1392 1392
     global $user, $conf, $langs, $db;
1393 1393
     global $dolibarr_main_authentication, $dolibarr_main_demo;
1394
-    global $hookmanager,$menumanager;
1394
+    global $hookmanager, $menumanager;
1395 1395
 
1396
-    $searchform='';
1397
-    $bookmarks='';
1396
+    $searchform = '';
1397
+    $bookmarks = '';
1398 1398
 
1399 1399
     // Instantiate hooks of thirdparty module
1400 1400
     $hookmanager->initHooks(array('toprightmenu'));
1401 1401
 
1402
-    $toprightmenu='';
1402
+    $toprightmenu = '';
1403 1403
 
1404 1404
     // For backward compatibility with old modules
1405 1405
     if (empty($conf->headerdone))
@@ -1411,49 +1411,49 @@  discard block
 block discarded – undo
1411 1411
     /*
1412 1412
      * Top menu
1413 1413
      */
1414
-    if (empty($conf->dol_hide_topmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1414
+    if (empty($conf->dol_hide_topmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU')))
1415 1415
     {
1416 1416
         print "\n".'<!-- Start top horizontal -->'."\n";
1417 1417
 
1418 1418
         print '<div class="side-nav-vert"><div id="id-top">';
1419 1419
 
1420 1420
 	    // Show menu entries
1421
-    	print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1422
-    	$menumanager->atarget=$target;
1423
-	    $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1421
+    	print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT) ? '' : 'invert').'" class="tmenu">'."\n";
1422
+    	$menumanager->atarget = $target;
1423
+	    $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \n
1424 1424
 	    print "</div>\n";
1425 1425
 
1426 1426
 	    // Define link to login card
1427
-        $appli=constant('DOL_APPLICATION_TITLE');
1428
-	    if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1427
+        $appli = constant('DOL_APPLICATION_TITLE');
1428
+	    if (!empty($conf->global->MAIN_APPLICATION_TITLE))
1429 1429
 	    {
1430
-	    	$appli=$conf->global->MAIN_APPLICATION_TITLE;
1430
+	    	$appli = $conf->global->MAIN_APPLICATION_TITLE;
1431 1431
 	    	if (preg_match('/\d\.\d/', $appli))
1432 1432
 	    	{
1433
-				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1433
+				if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
1434 1434
 	    	}
1435
-	    	else $appli.=" ".DOL_VERSION;
1435
+	    	else $appli .= " ".DOL_VERSION;
1436 1436
 	    }
1437
-	    else $appli.=" ".DOL_VERSION;
1437
+	    else $appli .= " ".DOL_VERSION;
1438 1438
 
1439
-	    if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1439
+	    if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $appli .= "<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1440 1440
 
1441
-	    $logouttext='';
1441
+	    $logouttext = '';
1442 1442
 	    if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1443 1443
 	    {
1444 1444
     	    //$logouthtmltext=$appli.'<br>';
1445 1445
     	    if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1446 1446
     	    {
1447
-    	    	$logouthtmltext.=$langs->trans("Logout").'<br>';
1447
+    	    	$logouthtmltext .= $langs->trans("Logout").'<br>';
1448 1448
 
1449
-    	    	$logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php">';
1449
+    	    	$logouttext .= '<a href="'.DOL_URL_ROOT.'/user/logout.php">';
1450 1450
     	        //$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1451
-    	    	$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1452
-    	        $logouttext .='</a>';
1451
+    	    	$logouttext .= '<span class="fa fa-sign-out atoplogin"></span>';
1452
+    	        $logouttext .= '</a>';
1453 1453
     	    }
1454 1454
     	    else
1455 1455
     	    {
1456
-    	    	$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1456
+    	    	$logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
1457 1457
     	        $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1458 1458
     	    }
1459 1459
 	    }
@@ -1461,55 +1461,55 @@  discard block
 block discarded – undo
1461 1461
 	    print '<div class="login_block">'."\n";
1462 1462
 
1463 1463
 	    // Add login user link
1464
-	    $toprightmenu.='<div class="login_block_user">';
1464
+	    $toprightmenu .= '<div class="login_block_user">';
1465 1465
 
1466 1466
 	    // Login name with photo and tooltip
1467
-		$mode=-1;
1468
-	    $toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1469
-        $toprightmenu.=$user->getNomUrl($mode, '', true, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1470
-        $toprightmenu.='</div></div>';
1467
+		$mode = -1;
1468
+	    $toprightmenu .= '<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1469
+        $toprightmenu .= $user->getNomUrl($mode, '', true, 0, 11, 0, ($user->firstname ? 'firstname' : -1), 'atoplogin');
1470
+        $toprightmenu .= '</div></div>';
1471 1471
 
1472
-		$toprightmenu.='</div>';
1472
+		$toprightmenu .= '</div>';
1473 1473
 
1474
-	    $toprightmenu.='<div class="login_block_other">';
1474
+	    $toprightmenu .= '<div class="login_block_other">';
1475 1475
 
1476 1476
 		// Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1477
-	    $parameters=array();
1478
-	    $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1477
+	    $parameters = array();
1478
+	    $result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
1479 1479
 		if (is_numeric($result))
1480 1480
 		{
1481
-			if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
1482
-			else  $toprightmenu=$hookmanager->resPrint;						// replace
1481
+			if (empty($result)) $toprightmenu .= $hookmanager->resPrint; // add
1482
+			else  $toprightmenu = $hookmanager->resPrint; // replace
1483 1483
 		}
1484
-		else $toprightmenu.=$result;	// For backward compatibility
1484
+		else $toprightmenu .= $result; // For backward compatibility
1485 1485
 
1486 1486
     	// Link to module builder
1487
-	    if (! empty($conf->modulebuilder->enabled))
1487
+	    if (!empty($conf->modulebuilder->enabled))
1488 1488
 	    {
1489
-	        $text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1489
+	        $text = '<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1490 1490
 	        //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1491
-	        $text.='<span class="fa fa-bug atoplogin"></span>';
1492
-	        $text.='</a>';
1493
-	        $toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1491
+	        $text .= '<span class="fa fa-bug atoplogin"></span>';
1492
+	        $text .= '</a>';
1493
+	        $toprightmenu .= @Form::textwithtooltip('', $langs->trans("ModuleBuilder"), 2, 1, $text, 'login_block_elem', 2);
1494 1494
 	    }
1495 1495
 
1496 1496
 		// Link to print main content area
1497 1497
 	    if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && empty($conf->browser->phone))
1498 1498
 	    {
1499
-	        $qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1499
+	        $qs = dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1500 1500
 
1501 1501
 	        if (is_array($_POST))
1502 1502
 	        {
1503
-    			foreach($_POST as $key=>$value) {
1504
-    				if ($key!=='action' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1503
+    			foreach ($_POST as $key=>$value) {
1504
+    				if ($key !== 'action' && !is_array($value)) $qs .= '&'.$key.'='.urlencode($value);
1505 1505
     			}
1506 1506
 	        }
1507
-			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1508
-	        $text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1507
+			$qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring;
1508
+	        $text = '<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank">';
1509 1509
 	        //$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1510
-	        $text.='<span class="fa fa-print atoplogin"></span>';
1511
-	        $text.='</a>';
1512
-	        $toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1510
+	        $text .= '<span class="fa fa-print atoplogin"></span>';
1511
+	        $text .= '</a>';
1512
+	        $toprightmenu .= @Form::textwithtooltip('', $langs->trans("PrintContentArea"), 2, 1, $text, 'login_block_elem', 2);
1513 1513
 	    }
1514 1514
 
1515 1515
 	    // Link to Dolibarr wiki pages
@@ -1517,43 +1517,43 @@  discard block
 block discarded – undo
1517 1517
 	    {
1518 1518
 	        $langs->load("help");
1519 1519
 
1520
-	        $helpbaseurl='';
1521
-	        $helppage='';
1522
-	        $mode='';
1520
+	        $helpbaseurl = '';
1521
+	        $helppage = '';
1522
+	        $mode = '';
1523 1523
 
1524
-	        if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1524
+	        if (empty($helppagename)) $helppagename = 'EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1525 1525
 
1526 1526
 	        // Get helpbaseurl, helppage and mode from helppagename and langs
1527
-	        $arrayres=getHelpParamFor($helppagename,$langs);
1528
-	        $helpbaseurl=$arrayres['helpbaseurl'];
1529
-	        $helppage=$arrayres['helppage'];
1530
-	        $mode=$arrayres['mode'];
1527
+	        $arrayres = getHelpParamFor($helppagename, $langs);
1528
+	        $helpbaseurl = $arrayres['helpbaseurl'];
1529
+	        $helppage = $arrayres['helppage'];
1530
+	        $mode = $arrayres['mode'];
1531 1531
 
1532 1532
 	        // Link to help pages
1533 1533
 	        if ($helpbaseurl && $helppage)
1534 1534
 	        {
1535
-	            $text='';
1536
-	            $title=$appli.'<br>';
1537
-	            $title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1538
-	            if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1539
-	            $text.='<a class="help" target="_blank" href="';
1540
-	            if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1541
-	            else $text.=sprintf($helpbaseurl,$helppage);
1542
-	            $text.='">';
1535
+	            $text = '';
1536
+	            $title = $appli.'<br>';
1537
+	            $title .= $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage');
1538
+	            if ($mode == 'wiki') $title .= ' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage, '_', ' ')).'&quot;';
1539
+	            $text .= '<a class="help" target="_blank" href="';
1540
+	            if ($mode == 'wiki') $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage)));
1541
+	            else $text .= sprintf($helpbaseurl, $helppage);
1542
+	            $text .= '">';
1543 1543
 	            //$text.=img_picto('', 'helpdoc_top').' ';
1544
-	            $text.='<span class="fa fa-question-circle atoplogin"></span>';
1544
+	            $text .= '<span class="fa fa-question-circle atoplogin"></span>';
1545 1545
 	            //$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1546 1546
 	            //if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1547
-	            $text.='</a>';
1547
+	            $text .= '</a>';
1548 1548
 	            //$toprightmenu.='</div>'."\n";
1549
-	            $toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1549
+	            $toprightmenu .= @Form::textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2);
1550 1550
 	        }
1551 1551
 	    }
1552 1552
 
1553 1553
 		// Logout link
1554
-	    $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1554
+	    $toprightmenu .= @Form::textwithtooltip('', $logouthtmltext, 2, 1, $logouttext, 'login_block_elem', 2);
1555 1555
 
1556
-	    $toprightmenu.='</div>';
1556
+	    $toprightmenu .= '</div>';
1557 1557
 
1558 1558
 	    print $toprightmenu;
1559 1559
 
@@ -1566,7 +1566,7 @@  discard block
 block discarded – undo
1566 1566
         print "<!-- End top horizontal menu -->\n\n";
1567 1567
     }
1568 1568
 
1569
-    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1569
+    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss ? ' '.$morecss : '').'">';
1570 1570
 }
1571 1571
 
1572 1572
 
@@ -1584,20 +1584,20 @@  discard block
 block discarded – undo
1584 1584
  *  @param  string  $acceptdelayedhtml          1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
1585 1585
  *  @return	void
1586 1586
  */
1587
-function left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
1587
+function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_array_after = '', $leftmenuwithoutmainarea = 0, $title = '', $acceptdelayedhtml = 0)
1588 1588
 {
1589 1589
     global $user, $conf, $langs, $db, $form;
1590 1590
     global $hookmanager, $menumanager;
1591 1591
 
1592
-    $searchform='';
1593
-    $bookmarks='';
1592
+    $searchform = '';
1593
+    $bookmarks = '';
1594 1594
 
1595
-    if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1595
+    if (!empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1596 1596
 
1597
-    if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1597
+    if (empty($conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU')))
1598 1598
     {
1599 1599
 	    // Instantiate hooks of thirdparty module
1600
-	    $hookmanager->initHooks(array('searchform','leftblock'));
1600
+	    $hookmanager->initHooks(array('searchform', 'leftblock'));
1601 1601
 
1602 1602
 		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1603 1603
 
@@ -1605,86 +1605,86 @@  discard block
 block discarded – undo
1605 1605
 
1606 1606
 	    if ($conf->use_javascript_ajax && $conf->browser->layout != 'phone' && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1607 1607
 	    {
1608
-    	    if (! is_object($form)) $form=new Form($db);
1609
-    	    $selected=-1;
1610
-            $searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1608
+    	    if (!is_object($form)) $form = new Form($db);
1609
+    	    $selected = -1;
1610
+            $searchform .= $form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1611 1611
 	    }
1612 1612
 	    else
1613 1613
 	    {
1614 1614
     	    // Define $searchform
1615
-    	    if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && $user->rights->societe->lire)
1615
+    	    if (((!empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || !empty($conf->fournisseur->enabled)) && $user->rights->societe->lire)
1616 1616
     	    {
1617 1617
     	        $langs->load("companies");
1618
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/societe/list.php', DOL_URL_ROOT.'/societe/list.php', $langs->trans("ThirdParties"), 'maxwidth100', 'sall', 'T', 'searchleftt', img_object('','company'));
1618
+    	        $searchform .= printSearchForm(DOL_URL_ROOT.'/societe/list.php', DOL_URL_ROOT.'/societe/list.php', $langs->trans("ThirdParties"), 'maxwidth100', 'sall', 'T', 'searchleftt', img_object('', 'company'));
1619 1619
     	    }
1620 1620
 
1621
-    	    if (! empty($conf->societe->enabled) && $user->rights->societe->lire)
1621
+    	    if (!empty($conf->societe->enabled) && $user->rights->societe->lire)
1622 1622
     	    {
1623 1623
     	        $langs->load("companies");
1624
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/contact/list.php', DOL_URL_ROOT.'/contact/list.php', $langs->trans("Contacts"), 'maxwidth100', 'sall', 'A', 'searchleftc', img_object('','contact'));
1624
+    	        $searchform .= printSearchForm(DOL_URL_ROOT.'/contact/list.php', DOL_URL_ROOT.'/contact/list.php', $langs->trans("Contacts"), 'maxwidth100', 'sall', 'A', 'searchleftc', img_object('', 'contact'));
1625 1625
     	    }
1626 1626
 
1627
-    	    if (((! empty($conf->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire))
1627
+    	    if (((!empty($conf->product->enabled) && $user->rights->produit->lire) || (!empty($conf->service->enabled) && $user->rights->service->lire))
1628 1628
     	    )
1629 1629
     	    {
1630 1630
     	        $langs->load("products");
1631
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/product/list.php', DOL_URL_ROOT.'/product/list.php', $langs->trans("Products")."/".$langs->trans("Services"), 'maxwidth100', 'sall', 'P', 'searchleftp', img_object('','product'));
1631
+    	        $searchform .= printSearchForm(DOL_URL_ROOT.'/product/list.php', DOL_URL_ROOT.'/product/list.php', $langs->trans("Products")."/".$langs->trans("Services"), 'maxwidth100', 'sall', 'P', 'searchleftp', img_object('', 'product'));
1632 1632
     	    }
1633 1633
 
1634
-            if (! empty($conf->projet->enabled) && $user->rights->projet->lire)
1634
+            if (!empty($conf->projet->enabled) && $user->rights->projet->lire)
1635 1635
     	    {
1636 1636
     	        $langs->load("projects");
1637
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/projet/list.php', DOL_URL_ROOT.'/projet/list.php', $langs->trans("Projects"), 'maxwidth100', 'search_all', 'Q', 'searchleftproj', img_object('','projectpub'));
1637
+    	        $searchform .= printSearchForm(DOL_URL_ROOT.'/projet/list.php', DOL_URL_ROOT.'/projet/list.php', $langs->trans("Projects"), 'maxwidth100', 'search_all', 'Q', 'searchleftproj', img_object('', 'projectpub'));
1638 1638
     	    }
1639 1639
 
1640
-    	    if (! empty($conf->adherent->enabled) && $user->rights->adherent->lire)
1640
+    	    if (!empty($conf->adherent->enabled) && $user->rights->adherent->lire)
1641 1641
     	    {
1642 1642
     	        $langs->load("members");
1643
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/adherents/list.php', DOL_URL_ROOT.'/adherents/list.php', $langs->trans("Members"), 'maxwidth100', 'sall', 'M', 'searchleftm', img_object('','user'));
1643
+    	        $searchform .= printSearchForm(DOL_URL_ROOT.'/adherents/list.php', DOL_URL_ROOT.'/adherents/list.php', $langs->trans("Members"), 'maxwidth100', 'sall', 'M', 'searchleftm', img_object('', 'user'));
1644 1644
     	    }
1645 1645
 
1646
-    		if (! empty($conf->user->enabled) && $user->rights->user->user->lire)
1646
+    		if (!empty($conf->user->enabled) && $user->rights->user->user->lire)
1647 1647
     	    {
1648 1648
     	        $langs->load("users");
1649
-    	        $searchform.=printSearchForm(DOL_URL_ROOT.'/user/list.php', DOL_URL_ROOT.'/user/list.php', $langs->trans("Users"), 'maxwidth100', 'sall', 'M', 'searchleftuser', img_object('','user'));
1649
+    	        $searchform .= printSearchForm(DOL_URL_ROOT.'/user/list.php', DOL_URL_ROOT.'/user/list.php', $langs->trans("Users"), 'maxwidth100', 'sall', 'M', 'searchleftuser', img_object('', 'user'));
1650 1650
     	    }
1651 1651
 	    }
1652 1652
 
1653 1653
 	    // Execute hook printSearchForm
1654
-	    $parameters=array('searchform'=>$searchform);
1655
-	    $reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1654
+	    $parameters = array('searchform'=>$searchform);
1655
+	    $reshook = $hookmanager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks
1656 1656
 		if (empty($reshook))
1657 1657
 		{
1658
-			$searchform.=$hookmanager->resPrint;
1658
+			$searchform .= $hookmanager->resPrint;
1659 1659
 		}
1660
-		else $searchform=$hookmanager->resPrint;
1660
+		else $searchform = $hookmanager->resPrint;
1661 1661
 
1662 1662
 		if ($conf->use_javascript_ajax && $conf->browser->layout == 'phone')
1663 1663
 	    {
1664
-	        $searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1665
-	        $searchform.='<script type="text/javascript">
1664
+	        $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1665
+	        $searchform .= '<script type="text/javascript">
1666 1666
             	jQuery(document).ready(function () {
1667 1667
             		jQuery("#divsearchforms1").click(function(){
1668 1668
 	                   jQuery("#divsearchforms2").toggle();
1669 1669
 	               });
1670 1670
             	});
1671 1671
                 </script>' . "\n";
1672
-	        $searchform.='</div>';
1672
+	        $searchform .= '</div>';
1673 1673
 	    }
1674 1674
 
1675 1675
 	    // Define $bookmarks
1676
-	    if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1676
+	    if (!empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1677 1677
 	    {
1678 1678
 	        include_once (DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php');
1679 1679
 	        $langs->load("bookmarks");
1680 1680
 
1681
-	        $bookmarks=printBookmarksList($db, $langs);
1681
+	        $bookmarks = printBookmarksList($db, $langs);
1682 1682
 	    }
1683 1683
 
1684 1684
 	    // Left column
1685 1685
 	    print '<!-- Begin left menu -->'."\n";
1686 1686
 
1687
-	    print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1687
+	    print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"').'>'."\n\n";
1688 1688
 
1689 1689
     	// Show left menu with other forms
1690 1690
 	    $menumanager->menu_array = $menu_array_before;
@@ -1699,25 +1699,25 @@  discard block
 block discarded – undo
1699 1699
         // Version
1700 1700
         if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1701 1701
         {
1702
-            $doliurl='https://www.dolibarr.org';
1702
+            $doliurl = 'https://www.dolibarr.org';
1703 1703
     		//local communities
1704
-    		if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1705
-    		if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1706
-    		if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1707
-    		if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1708
-    		if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1709
-
1710
-            $appli=constant('DOL_APPLICATION_TITLE');
1711
-    	    if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1704
+    		if (preg_match('/fr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.fr';
1705
+    		if (preg_match('/es/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.es';
1706
+    		if (preg_match('/de/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.de';
1707
+    		if (preg_match('/it/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.it';
1708
+    		if (preg_match('/gr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.gr';
1709
+
1710
+            $appli = constant('DOL_APPLICATION_TITLE');
1711
+    	    if (!empty($conf->global->MAIN_APPLICATION_TITLE))
1712 1712
     	    {
1713
-    	    	$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1713
+    	    	$appli = $conf->global->MAIN_APPLICATION_TITLE; $doliurl = '';
1714 1714
     	    	if (preg_match('/\d\.\d/', $appli))
1715 1715
     	    	{
1716
-    				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1716
+    				if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
1717 1717
     	    	}
1718
-    	    	else $appli.=" ".DOL_VERSION;
1718
+    	    	else $appli .= " ".DOL_VERSION;
1719 1719
     	    }
1720
-    	    else $appli.=" ".DOL_VERSION;
1720
+    	    else $appli .= " ".DOL_VERSION;
1721 1721
     	    print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1722 1722
     	    if ($doliurl) print '<a class="help" target="_blank" href="'.$doliurl.'">';
1723 1723
     	    else print '<span class="help">';
@@ -1728,26 +1728,26 @@  discard block
 block discarded – undo
1728 1728
         }
1729 1729
 
1730 1730
 		// Link to bugtrack
1731
-		if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1731
+		if (!empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1732 1732
 		{
1733 1733
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1734 1734
 
1735 1735
 			$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
1736
-			$bugbaseurl.= '?title=';
1737
-			$bugbaseurl.= urlencode("Bug: ");
1738
-			$bugbaseurl.= '&body=';
1736
+			$bugbaseurl .= '?title=';
1737
+			$bugbaseurl .= urlencode("Bug: ");
1738
+			$bugbaseurl .= '&body=';
1739 1739
 			// TODO use .github/ISSUE_TEMPLATE.md to generate?
1740 1740
 			$bugbaseurl .= urlencode("# Bug\n");
1741 1741
 			$bugbaseurl .= urlencode("\n");
1742
-			$bugbaseurl.= urlencode("## Environment\n");
1743
-			$bugbaseurl.= urlencode("- **Version**: " . DOL_VERSION . "\n");
1744
-			$bugbaseurl.= urlencode("- **OS**: " . php_uname('s') . "\n");
1745
-			$bugbaseurl.= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
1746
-			$bugbaseurl.= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
1747
-			$bugbaseurl.= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
1748
-			$bugbaseurl.= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
1749
-			$bugbaseurl.= urlencode("\n");
1750
-			$bugbaseurl.= urlencode("## Report\n");
1742
+			$bugbaseurl .= urlencode("## Environment\n");
1743
+			$bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
1744
+			$bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
1745
+			$bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
1746
+			$bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
1747
+			$bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
1748
+			$bugbaseurl .= urlencode("- **URL**: ".$_SERVER["REQUEST_URI"]."\n");
1749
+			$bugbaseurl .= urlencode("\n");
1750
+			$bugbaseurl .= urlencode("## Report\n");
1751 1751
 			print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
1752 1752
 			print '<a class="help" target="_blank" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
1753 1753
 			print '</div>';
@@ -1762,11 +1762,11 @@  discard block
 block discarded – undo
1762 1762
         print "\n";
1763 1763
 
1764 1764
 	    // Execute hook printLeftBlock
1765
-	    $parameters=array();
1766
-	    $reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1765
+	    $parameters = array();
1766
+	    $reshook = $hookmanager->executeHooks('printLeftBlock', $parameters); // Note that $action and $object may have been modified by some hooks
1767 1767
 	    print $hookmanager->resPrint;
1768 1768
 
1769
-	    print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1769
+	    print '</div></div> <!-- End side-nav id-left -->'; // End div id="side-nav" div id="id-left"
1770 1770
     }
1771 1771
 
1772 1772
     print "\n";
@@ -1782,7 +1782,7 @@  discard block
 block discarded – undo
1782 1782
  *  @param	string	$title		Title
1783 1783
  *  @return	void
1784 1784
  */
1785
-function main_area($title='')
1785
+function main_area($title = '')
1786 1786
 {
1787 1787
     global $conf, $langs;
1788 1788
 
@@ -1792,7 +1792,7 @@  discard block
 block discarded – undo
1792 1792
 
1793 1793
     print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1794 1794
 
1795
-    if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1795
+    if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1796 1796
 }
1797 1797
 
1798 1798
 
@@ -1803,40 +1803,40 @@  discard block
 block discarded – undo
1803 1803
  *  @param  Translate	$langs				Language
1804 1804
  *  @return	array		Array of help urls
1805 1805
  */
1806
-function getHelpParamFor($helppagename,$langs)
1806
+function getHelpParamFor($helppagename, $langs)
1807 1807
 {
1808
-	$helpbaseurl='';
1809
-	$helppage='';
1810
-	$mode='';
1808
+	$helpbaseurl = '';
1809
+	$helppage = '';
1810
+	$mode = '';
1811 1811
 
1812
-    if (preg_match('/^http/i',$helppagename))
1812
+    if (preg_match('/^http/i', $helppagename))
1813 1813
     {
1814 1814
         // If complete URL
1815
-        $helpbaseurl='%s';
1816
-        $helppage=$helppagename;
1817
-        $mode='local';
1815
+        $helpbaseurl = '%s';
1816
+        $helppage = $helppagename;
1817
+        $mode = 'local';
1818 1818
     }
1819 1819
     else
1820 1820
     {
1821 1821
         // If WIKI URL
1822
-        if (preg_match('/^es/i',$langs->defaultlang))
1822
+        if (preg_match('/^es/i', $langs->defaultlang))
1823 1823
         {
1824
-            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1825
-            if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1824
+            $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
1825
+            if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
1826 1826
         }
1827
-        if (preg_match('/^fr/i',$langs->defaultlang))
1827
+        if (preg_match('/^fr/i', $langs->defaultlang))
1828 1828
         {
1829
-            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1830
-            if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1829
+            $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
1830
+            if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
1831 1831
         }
1832 1832
         if (empty($helppage))	// If help page not already found
1833 1833
         {
1834
-            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1835
-            if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1834
+            $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
1835
+            if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
1836 1836
         }
1837
-        $mode='wiki';
1837
+        $mode = 'wiki';
1838 1838
     }
1839
-    return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1839
+    return array('helpbaseurl'=>$helpbaseurl, 'helppage'=>$helppage, 'mode'=>$mode);
1840 1840
 }
1841 1841
 
1842 1842
 
@@ -1853,44 +1853,44 @@  discard block
 block discarded – undo
1853 1853
  *  @param	string	$img				Image to use
1854 1854
  *  @return	string
1855 1855
  */
1856
-function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='')
1856
+function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey = '', $prefhtmlinputname = '', $img = '')
1857 1857
 {
1858
-    global $conf,$langs;
1858
+    global $conf, $langs;
1859 1859
 
1860 1860
     if (empty($htmlinputid)) {
1861 1861
         $htmlinputid = $htmlinputname;
1862 1862
     }
1863 1863
 
1864
-    $ret='';
1865
-    $ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1864
+    $ret = '';
1865
+    $ret .= '<form action="'.$urlaction.'" method="post" class="searchform">';
1866 1866
 	if (empty($conf->global->MAIN_HTML5_PLACEHOLDER))
1867 1867
 	{
1868
-        $ret.='<div class="menu_titre menu_titre_search"';
1869
-    	if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="display: inline-block"';
1870
-    	$ret.='>';
1871
-    	$ret.='<label for="'.$prefhtmlinputname.$htmlinputname.'">';
1872
-    	$ret.='<a class="vsmenu" href="'.$urlobject.'">';
1873
-       	if ($img && ! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=$img;
1874
-       	else if ($img || $title) $ret.=$img.' '.$title;
1875
-    	$ret.='</a>';
1876
-    	$ret.='</label>';
1877
-    	$ret.='</div>';
1868
+        $ret .= '<div class="menu_titre menu_titre_search"';
1869
+    	if (!empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret .= ' style="display: inline-block"';
1870
+    	$ret .= '>';
1871
+    	$ret .= '<label for="'.$prefhtmlinputname.$htmlinputname.'">';
1872
+    	$ret .= '<a class="vsmenu" href="'.$urlobject.'">';
1873
+       	if ($img && !empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret .= $img;
1874
+       	else if ($img || $title) $ret .= $img.' '.$title;
1875
+    	$ret .= '</a>';
1876
+    	$ret .= '</label>';
1877
+    	$ret .= '</div>';
1878 1878
 	}
1879
-    $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1880
-    $ret.='<input type="hidden" name="mode" value="search">';
1881
-    $ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1882
-    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1883
-    $ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1884
-    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' placeholder="'.strip_tags($title).'"';		// Will work only if MAIN_HTML5_PLACEHOLDER is set to 1
1885
-    else $ret.=' title="'.$langs->trans("SearchOf").''.strip_tags($title).'"';
1886
-    $ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1887
-    $ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1888
-    $ret.="</form>\n";
1879
+    $ret .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1880
+    $ret .= '<input type="hidden" name="mode" value="search">';
1881
+    $ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
1882
+    if (!empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret .= ' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1883
+    $ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
1884
+    if (!empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret .= ' placeholder="'.strip_tags($title).'"'; // Will work only if MAIN_HTML5_PLACEHOLDER is set to 1
1885
+    else $ret .= ' title="'.$langs->trans("SearchOf").''.strip_tags($title).'"';
1886
+    $ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1887
+    $ret .= '<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1888
+    $ret .= "</form>\n";
1889 1889
     return $ret;
1890 1890
 }
1891 1891
 
1892 1892
 
1893
-if (! function_exists("llxFooter"))
1893
+if (!function_exists("llxFooter"))
1894 1894
 {
1895 1895
     /**
1896 1896
      * Show HTML footer
@@ -1901,7 +1901,7 @@  discard block
 block discarded – undo
1901 1901
 	 * @param	string	$zone		'private' (for private pages) or 'public' (for public pages)
1902 1902
      * @return	void
1903 1903
      */
1904
-    function llxFooter($comment='',$zone='private')
1904
+    function llxFooter($comment = '', $zone = 'private')
1905 1905
     {
1906 1906
         global $conf, $langs, $user, $object;
1907 1907
         global $delayedhtmlcontent;
@@ -1911,10 +1911,10 @@  discard block
 block discarded – undo
1911 1911
 
1912 1912
         // Code for search criteria persistence.
1913 1913
         // Save $user->lastsearch_values if defined (define on list pages when a form field search_xxx exists)
1914
-        if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1914
+        if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1915 1915
         {
1916 1916
             // Clean data
1917
-            foreach($user->lastsearch_values_tmp as $key => $val)
1917
+            foreach ($user->lastsearch_values_tmp as $key => $val)
1918 1918
             {
1919 1919
                 unset($_SESSION['lastsearch_values_tmp_'.$key]);
1920 1920
                 if (count($val))
@@ -1922,14 +1922,14 @@  discard block
 block discarded – undo
1922 1922
                     if (empty($val['sortfield'])) unset($val['sortfield']);
1923 1923
                     if (empty($val['sortorder'])) unset($val['sortorder']);
1924 1924
                     dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criteria)");
1925
-                    $_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
1925
+                    $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
1926 1926
                     unset($_SESSION['lastsearch_values_'.$key]);
1927 1927
                 }
1928 1928
             }
1929 1929
         }
1930 1930
 
1931 1931
         // Core error message
1932
-        if (! empty($conf->global->MAIN_CORE_ERROR))
1932
+        if (!empty($conf->global->MAIN_CORE_ERROR))
1933 1933
         {
1934 1934
             // Ajax version
1935 1935
             if ($conf->use_javascript_ajax)
@@ -1958,19 +1958,19 @@  discard block
 block discarded – undo
1958 1958
 
1959 1959
         printCommonFooter($zone);
1960 1960
 
1961
-        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
1961
+        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n"; // End div container
1962 1962
 
1963
-        if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
1963
+        if (!empty($delayedhtmlcontent)) print $delayedhtmlcontent;
1964 1964
 
1965 1965
         // TODO Move this in lib_head.js.php
1966 1966
 
1967 1967
         // Wrapper to show tooltips (html or onclick popup)
1968
-        if (! empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover))
1968
+        if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover))
1969 1969
         {
1970 1970
     		print "\n<!-- JS CODE TO ENABLE tipTip on all object with class classfortooltip -->\n";
1971 1971
     		print '<script type="text/javascript">
1972 1972
             	jQuery(document).ready(function () {
1973
-            		jQuery(".classfortooltip").tipTip({maxWidth: "'.dol_size(($conf->browser->layout == 'phone' ? 400 : 700),'width').'px", edgeOffset: 10, delay: 50, fadeIn: 50, fadeOut: 50});
1973
+            		jQuery(".classfortooltip").tipTip({maxWidth: "'.dol_size(($conf->browser->layout == 'phone' ? 400 : 700), 'width').'px", edgeOffset: 10, delay: 50, fadeIn: 50, fadeOut: 50});
1974 1974
             		jQuery(".classfortooltiponclicktext").dialog({ width: '.($conf->browser->layout == 'phone' ? 400 : 700).', autoOpen: false });
1975 1975
             		jQuery(".classfortooltiponclick").click(function () {
1976 1976
             		    console.log("We click on tooltip for element with dolid="+$(this).attr(\'dolid\'));
@@ -1985,7 +1985,7 @@  discard block
 block discarded – undo
1985 1985
         }
1986 1986
 
1987 1987
         // Wrapper to manage document_preview
1988
-        if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
1988
+        if (!empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
1989 1989
         {
1990 1990
             print "\n<!-- JS CODE TO ENABLE document_preview -->\n";
1991 1991
             print '<script type="text/javascript">
@@ -2000,7 +2000,7 @@  discard block
 block discarded – undo
2000 2000
         }
2001 2001
 
2002 2002
         // Wrapper to manage dropdown
2003
-        if (! empty($conf->use_javascript_ajax) && ! defined('JS_JQUERY_DISABLE_DROPDOWN'))
2003
+        if (!empty($conf->use_javascript_ajax) && !defined('JS_JQUERY_DISABLE_DROPDOWN'))
2004 2004
         {
2005 2005
             print "\n<!-- JS CODE TO ENABLE dropdown -->\n";
2006 2006
             print '<script type="text/javascript">
@@ -2039,7 +2039,7 @@  discard block
 block discarded – undo
2039 2039
         }
2040 2040
 
2041 2041
         // Wrapper to add log when clicking on download or preview
2042
-        if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2042
+        if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2043 2043
         {
2044 2044
             if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2045 2045
             {
Please login to merge, or discard this patch.
Braces   +516 added lines, -199 removed lines patch added patch discarded remove patch
@@ -48,7 +48,8 @@  discard block
 block discarded – undo
48 48
 }
49 49
 
50 50
 // Removed magic_quotes
51
-if (function_exists('get_magic_quotes_gpc'))	// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
51
+if (function_exists('get_magic_quotes_gpc')) {
52
+	// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
52 53
 {
53 54
     if (get_magic_quotes_gpc())
54 55
     {
@@ -59,6 +60,7 @@  discard block
 block discarded – undo
59 60
         function stripslashes_deep($value)
60 61
         {
61 62
             return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
63
+}
62 64
         }
63 65
         $_GET     = array_map('stripslashes_deep', $_GET);
64 66
         $_POST    = array_map('stripslashes_deep', $_POST);
@@ -98,7 +100,9 @@  discard block
 block discarded – undo
98 100
     $inj += preg_match('/<script/i', $val);
99 101
 	$inj += preg_match('/<iframe/i', $val);
100 102
 	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
101
-    if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
103
+    if (! defined('NOSTYLECHECK')) {
104
+    	$inj += preg_match('/<style/i', $val);
105
+    }
102 106
     $inj += preg_match('/base[\s]+href/si', $val);
103 107
     $inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
104 108
     $inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
@@ -112,8 +116,14 @@  discard block
 block discarded – undo
112 116
         $inj += preg_match('/vbscript:/i', $val);
113 117
     //}
114 118
     // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
115
-    if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
116
-    if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
119
+    if ($type == 1) {
120
+    	$inj += preg_match('/"/i', $val);
121
+    }
122
+    // We refused " in GET parameters value
123
+    if ($type == 2) {
124
+    	$inj += preg_match('/[;"]/', $val);
125
+    }
126
+    // PHP_SELF is a file system path. It can contains spaces.
117 127
     return $inj;
118 128
 }
119 129
 
@@ -133,16 +143,14 @@  discard block
 block discarded – undo
133 143
             if (analyseVarsForSqlAndScriptsInjection($value,$type))
134 144
             {
135 145
                 $var[$key] = $value;
136
-            }
137
-            else
146
+            } else
138 147
 			{
139 148
                 print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
140 149
                 exit;
141 150
             }
142 151
         }
143 152
         return true;
144
-    }
145
-    else
153
+    } else
146 154
     {
147 155
         return (test_sql_and_script_inject($var,$type) <= 0);
148 156
     }
@@ -150,7 +158,9 @@  discard block
 block discarded – undo
150 158
 
151 159
 
152 160
 // Check consistency of NOREQUIREXXX DEFINES
153
-if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU')) dol_print_error('','If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not use them');
161
+if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU')) {
162
+	dol_print_error('','If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not use them');
163
+}
154 164
 
155 165
 // Sanity check on URL
156 166
 if (! empty($_SERVER["PHP_SELF"]))
@@ -191,20 +201,26 @@  discard block
 block discarded – undo
191 201
 	{
192 202
 		$postkey=$tmpautoset[0].'_'.$tmpkey;
193 203
 		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
194
-		if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
204
+		if (! empty($_POST[$postkey])) {
205
+			$cookiearrayvalue[$tmpkey]=$_POST[$postkey];
206
+		}
195 207
 	}
196 208
 	$cookiename=$tmpautoset[0];
197 209
 	$cookievalue=json_encode($cookiearrayvalue);
198 210
 	//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
199 211
 	setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
200
-	if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
201
-}
212
+	if (empty($cookievalue)) {
213
+		unset($_COOKIE[$cookiename]);
214
+	}
215
+	}
202 216
 
203 217
 // Init session. Name of session is specific to Dolibarr instance.
204 218
 $prefix=dol_getprefix();
205 219
 $sessionname='DOLSESSID_'.$prefix;
206 220
 $sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
207
-if (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);
221
+if (! empty($_COOKIE[$sessiontimeout])) {
222
+	ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);
223
+}
208 224
 session_name($sessionname);
209 225
 session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
210 226
 // This create lock released until session_write_close() or end of page.
@@ -212,11 +228,13 @@  discard block
 block discarded – undo
212 228
 if (! defined('NOSESSION'))
213 229
 {
214 230
     session_start();
215
-    if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
231
+    if (ini_get('register_globals')) {
232
+    	// Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
216 233
     {
217 234
         foreach ($_SESSION as $key=>$value)
218 235
         {
219 236
             if (isset($GLOBALS[$key])) unset($GLOBALS[$key]);
237
+    }
220 238
         }
221 239
     }
222 240
 }
@@ -239,9 +257,13 @@  discard block
 block discarded – undo
239 257
     $conf->browser->tablet=$tmp['tablet'];	   // TODO deprecated, use ->layout
240 258
     //var_dump($conf->browser);
241 259
 
242
-    if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
243
-    if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
244
-}
260
+    if ($conf->browser->layout == 'phone') {
261
+    	$conf->dol_no_mouse_hover=1;
262
+    }
263
+    if ($conf->browser->layout == 'phone') {
264
+    	$conf->global->MAIN_TESTMENUHIDER=1;
265
+    }
266
+    }
245 267
 
246 268
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
247 269
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
@@ -250,19 +272,19 @@  discard block
 block discarded – undo
250 272
     $newurl='';
251 273
     if (is_numeric($conf->file->main_force_https))
252 274
     {
253
-        if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
275
+        if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"])) {
276
+        	// If SCRIPT_URI supported by server
254 277
         {
255 278
             if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
256 279
             {
257 280
                 $newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
258
-            }
259 281
         }
260
-        else	// Check HTTPS environment variable (Apache/mod_ssl only)
282
+            }
283
+        } else	// Check HTTPS environment variable (Apache/mod_ssl only)
261 284
         {
262 285
             $newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
263 286
         }
264
-    }
265
-    else
287
+    } else
266 288
     {
267 289
         // Check HTTPS environment variable (Apache/mod_ssl only)
268 290
         $newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
@@ -273,8 +295,7 @@  discard block
 block discarded – undo
273 295
         dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
274 296
         header("Location: ".$newurl);
275 297
         exit;
276
-    }
277
-    else
298
+    } else
278 299
     {
279 300
         dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
280 301
     }
@@ -282,8 +303,14 @@  discard block
 block discarded – undo
282 303
 
283 304
 
284 305
 // Loading of additional presentation includes
285
-if (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';	    // Need 660ko memory (800ko in 2.2)
286
-if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';	// Need 22ko memory
306
+if (! defined('NOREQUIREHTML')) {
307
+	require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
308
+}
309
+// Need 660ko memory (800ko in 2.2)
310
+if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) {
311
+	require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
312
+}
313
+// Need 22ko memory
287 314
 
288 315
 // If install or upgrade process not done or not completely finished, we call the install page.
289 316
 if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
@@ -301,9 +328,11 @@  discard block
 block discarded – undo
301 328
     $dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
302 329
     $dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
303 330
     $rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
304
-    if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
331
+    if ($rescomp > 0) {
332
+    	// Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
305 333
     {
306 334
         dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
335
+    }
307 336
         header("Location: ".DOL_URL_ROOT."/install/index.php");
308 337
         exit;
309 338
     }
@@ -313,25 +342,31 @@  discard block
 block discarded – undo
313 342
 if (! defined('NOTOKENRENEWAL'))
314 343
 {
315 344
     // roulement des jetons car cree a chaque appel
316
-    if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
345
+    if (isset($_SESSION['newtoken'])) {
346
+    	$_SESSION['token'] = $_SESSION['newtoken'];
347
+    }
317 348
 
318 349
     // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
319 350
     $token = dol_hash(uniqid(mt_rand(),TRUE)); // Generates a hash of a random number
320 351
     $_SESSION['newtoken'] = $token;
321 352
 }
322
-if (! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))	// Check validity of token, only if option enabled (this option breaks some features sometimes)
353
+if (! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN)) {
354
+	// Check validity of token, only if option enabled (this option breaks some features sometimes)
323 355
 {
324 356
     if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
325 357
     {
326 358
         print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
359
+}
327 360
         print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
328 361
         die;
329 362
     }
330
-    if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
363
+    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
364
+    	// This test must be after loading $_SESSION['token'].
331 365
     {
332 366
         if (GETPOST('token', 'alpha') != $_SESSION['token'])
333 367
         {
334 368
             dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
369
+    }
335 370
             //print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
336 371
             unset($_POST);
337 372
         }
@@ -339,7 +374,9 @@  discard block
 block discarded – undo
339 374
 }
340 375
 
341 376
 // Disable modules (this must be after session_start and after conf has been loaded)
342
-if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
377
+if (GETPOST('disablemodules','alpha')) {
378
+	$_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
379
+}
343 380
 if (! empty($_SESSION["disablemodules"]))
344 381
 {
345 382
     $disabled_modules=explode(',',$_SESSION["disablemodules"]);
@@ -347,11 +384,15 @@  discard block
 block discarded – undo
347 384
     {
348 385
         if ($module)
349 386
         {
350
-        	if (empty($conf->$module)) $conf->$module=new stdClass();
387
+        	if (empty($conf->$module)) {
388
+        		$conf->$module=new stdClass();
389
+        	}
351 390
         	$conf->$module->enabled=false;
352
-        	if ($module == 'fournisseur')		// Special case
391
+        	if ($module == 'fournisseur') {
392
+        		// Special case
353 393
         	{
354 394
         		$conf->supplier_order->enabled=0;
395
+        	}
355 396
         		$conf->supplier_invoice->enabled=0;
356 397
         	}
357 398
         }
@@ -369,9 +410,13 @@  discard block
 block discarded – undo
369 410
     // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser'
370 411
 
371 412
     // Authentication mode
372
-    if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
413
+    if (empty($dolibarr_main_authentication)) {
414
+    	$dolibarr_main_authentication='http,dolibarr';
415
+    }
373 416
     // Authentication mode: forceuser
374
-    if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
417
+    if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) {
418
+    	$dolibarr_auto_user='auto';
419
+    }
375 420
     // Set authmode
376 421
     $authmode=explode(',',$dolibarr_main_authentication);
377 422
 
@@ -406,11 +451,13 @@  discard block
 block discarded – undo
406 451
         //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
407 452
 
408 453
         // If in demo mode, we check we go to home page through the public/demo/index.php page
409
-        if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
454
+        if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') {
455
+        	// We ask index page
410 456
         {
411 457
             if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
412 458
             {
413 459
                 dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
460
+        }
414 461
                 $url='';
415 462
                 $url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
416 463
                 $url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
@@ -455,7 +502,9 @@  discard block
 block discarded – undo
455 502
 		        $hookmanager->initHooks(array('login'));
456 503
 		        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
457 504
 		        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
458
-		        if ($reshook < 0) $error++;
505
+		        if ($reshook < 0) {
506
+		        	$error++;
507
+		        }
459 508
 
460 509
 		        // Note: exit is done later
461 510
             }
@@ -467,13 +516,21 @@  discard block
 block discarded – undo
467 516
 
468 517
         // Define if we received data to test the login.
469 518
         $goontestloop=false;
470
-        if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
471
-        if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
472
-        if (GETPOST("username","alpha",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
519
+        if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) {
520
+        	$goontestloop=true;
521
+        }
522
+        if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) {
523
+        	$goontestloop=true;
524
+        }
525
+        if (GETPOST("username","alpha",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) {
526
+        	$goontestloop=true;
527
+        }
473 528
 
474
-        if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
529
+        if (! is_object($langs)) {
530
+        	// This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
475 531
         {
476 532
             include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
533
+        }
477 534
             $langs=new Translate("",$conf);
478 535
     		$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
479 536
         	$langs->setDefaultLang($langcode);
@@ -500,7 +557,9 @@  discard block
 block discarded – undo
500 557
                     $datenow=dol_now();
501 558
                     $datefirst=dol_stringtotime($_POST["dst_first"]);
502 559
                     $datesecond=dol_stringtotime($_POST["dst_second"]);
503
-                    if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
560
+                    if ($datenow >= $datefirst && $datenow < $datesecond) {
561
+                    	$dol_dst=1;
562
+                    }
504 563
                 }
505 564
                 //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
506 565
             }
@@ -513,7 +572,9 @@  discard block
 block discarded – undo
513 572
 
514 573
                 // Bad password. No authmode has found a good password.
515 574
                 // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
516
-                if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
575
+                if (empty($_SESSION["dol_loginmesg"])) {
576
+                	$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
577
+                }
517 578
 
518 579
                 // TODO @deprecated Remove this. Hook must be used, not this trigger.
519 580
                 $user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
@@ -531,19 +592,26 @@  discard block
 block discarded – undo
531 592
 		        $hookmanager->initHooks(array('login'));
532 593
 		        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
533 594
 		        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
534
-		        if ($reshook < 0) $error++;
595
+		        if ($reshook < 0) {
596
+		        	$error++;
597
+		        }
535 598
 
536 599
 		        // Note: exit is done in next chapter
537 600
             }
538 601
         }
539 602
 
540 603
         // End test login / passwords
541
-        if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
604
+        if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest))) {
605
+        	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
542 606
         {
543 607
             // No data to test login, so we show the login page
544 608
 			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
545
-			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
546
-        	else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
609
+        }
610
+			if (defined('NOREDIRECTBYMAINTOLOGIN')) {
611
+				return 'ERROR_NOT_LOGGED';
612
+			} else {
613
+        		dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
614
+        	}
547 615
             exit;
548 616
         }
549 617
 
@@ -588,17 +656,24 @@  discard block
 block discarded – undo
588 656
 	        $hookmanager->initHooks(array('login'));
589 657
 	        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
590 658
 	        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
591
-	        if ($reshook < 0) $error++;
659
+	        if ($reshook < 0) {
660
+	        	$error++;
661
+	        }
592 662
 
593 663
 	        $paramsurl=array();
594
-	        if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
595
-	        if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
596
-	        if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
664
+	        if (GETPOST('textbrowser','int')) {
665
+	        	$paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
666
+	        }
667
+	        if (GETPOST('nojs','int')) {
668
+	        	$paramsurl[]='nojs='.GETPOST('nojs','int');
669
+	        }
670
+	        if (GETPOST('lang','aZ09')) {
671
+	        	$paramsurl[]='lang='.GETPOST('lang','aZ09');
672
+	        }
597 673
             header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
598 674
             exit;
599 675
         }
600
-    }
601
-    else
676
+    } else
602 677
     {
603 678
         // We are already into an authenticated session
604 679
         $login=$_SESSION["dol_login"];
@@ -648,27 +723,38 @@  discard block
 block discarded – undo
648 723
 	        $hookmanager->initHooks(array('login'));
649 724
 	        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
650 725
 	        $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
651
-	        if ($reshook < 0) $error++;
726
+	        if ($reshook < 0) {
727
+	        	$error++;
728
+	        }
652 729
 
653 730
 	        $paramsurl=array();
654
-	        if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
655
-	        if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
656
-	        if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
731
+	        if (GETPOST('textbrowser','int')) {
732
+	        	$paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
733
+	        }
734
+	        if (GETPOST('nojs','int')) {
735
+	        	$paramsurl[]='nojs='.GETPOST('nojs','int');
736
+	        }
737
+	        if (GETPOST('lang','aZ09')) {
738
+	        	$paramsurl[]='lang='.GETPOST('lang','aZ09');
739
+	        }
657 740
             header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
658 741
             exit;
659
-        }
660
-        else
742
+        } else
661 743
 		{
662 744
 	       // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
663 745
 	       $hookmanager->initHooks(array('main'));
664 746
 
665 747
 	       // Code for search criteria persistence.
666
-	       if (! empty($_GET['save_lastsearch_values']))    // Keep $_GET here
748
+	       if (! empty($_GET['save_lastsearch_values'])) {
749
+	       	// Keep $_GET here
667 750
 	       {
668 751
                $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
752
+	       }
669 753
                $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
670 754
                // Clean $relativepathstring
671
-   	           if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
755
+   	           if (constant('DOL_URL_ROOT')) {
756
+   	           	$relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
757
+   	           }
672 758
                $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
673 759
                $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
674 760
                //var_dump($relativepathstring);
@@ -709,11 +795,21 @@  discard block
 block discarded – undo
709 795
         $_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
710 796
         $_SESSION["dol_entity"]=$conf->entity;
711 797
     	// Store value into session (values stored only if defined)
712
-        if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
713
-        if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
714
-        if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
715
-        if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
716
-        if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
798
+        if (! empty($dol_hide_topmenu)) {
799
+        	$_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
800
+        }
801
+        if (! empty($dol_hide_leftmenu)) {
802
+        	$_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
803
+        }
804
+        if (! empty($dol_optimize_smallscreen)) {
805
+        	$_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
806
+        }
807
+        if (! empty($dol_no_mouse_hover)) {
808
+        	$_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
809
+        }
810
+        if (! empty($dol_use_jmobile)) {
811
+        	$_SESSION['dol_use_jmobile']=$dol_use_jmobile;
812
+        }
717 813
 
718 814
         dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
719 815
 
@@ -739,7 +835,9 @@  discard block
 block discarded – undo
739 835
         $hookmanager->initHooks(array('login'));
740 836
         $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
741 837
         $reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
742
-        if ($reshook < 0) $error++;
838
+        if ($reshook < 0) {
839
+        	$error++;
840
+        }
743 841
 
744 842
         if ($error)
745 843
         {
@@ -747,20 +845,23 @@  discard block
 block discarded – undo
747 845
             session_destroy();
748 846
             dol_print_error($db,'Error in some hooks afterLogin (or old trigger USER_LOGIN)');
749 847
             exit;
750
-        }
751
-        else
848
+        } else
752 849
 		{
753 850
             $db->commit();
754 851
         }
755 852
 
756 853
         // Change landing page if defined.
757 854
         $landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
758
-        if (! empty($landingpage))    // Example: /index.php
855
+        if (! empty($landingpage)) {
856
+        	// Example: /index.php
759 857
         {
760 858
             $newpath=dol_buildpath($landingpage, 1);
761
-            if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
859
+        }
860
+            if ($_SERVER["PHP_SELF"] != $newpath) {
861
+            	// not already on landing page (avoid infinite loop)
762 862
             {
763 863
                 header('Location: '.$newpath);
864
+            }
764 865
                 exit;
765 866
             }
766 867
         }
@@ -783,8 +884,14 @@  discard block
 block discarded – undo
783 884
      */
784 885
 
785 886
     // Set liste_limit
786
-    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
787
-    if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
887
+    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) {
888
+    	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;
889
+    }
890
+    // Can be 0
891
+    if (isset($user->conf->PRODUIT_LIMIT_SIZE)) {
892
+    	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;
893
+    }
894
+    // Can be 0
788 895
 
789 896
     // Replace conf->css by personalized value if theme not forced
790 897
     if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
@@ -803,27 +910,44 @@  discard block
 block discarded – undo
803 910
 
804 911
 
805 912
 // Set javascript option
806
-if (! GETPOST('nojs','int'))   // If javascript was not disabled on URL
913
+if (! GETPOST('nojs','int')) {
914
+	// If javascript was not disabled on URL
807 915
 {
808 916
 	if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
809 917
 	{
810 918
 		$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
919
+}
811 920
 	}
921
+} else {
922
+	$conf->use_javascript_ajax=0;
812 923
 }
813
-else $conf->use_javascript_ajax=0;
814 924
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
815
-if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
925
+if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER)) {
926
+	// If we must enable text browser
816 927
 {
817 928
     $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
818 929
 }
930
+}
819 931
 
820 932
 // Set terminal output option according to conf->browser.
821
-if (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu']))               $conf->dol_hide_leftmenu=1;
822
-if (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu']))                 $conf->dol_hide_topmenu=1;
823
-if (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1;
824
-if (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover']))             $conf->dol_no_mouse_hover=1;
825
-if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile=1;
826
-if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;
933
+if (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu'])) {
934
+	$conf->dol_hide_leftmenu=1;
935
+}
936
+if (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu'])) {
937
+	$conf->dol_hide_topmenu=1;
938
+}
939
+if (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) {
940
+	$conf->dol_optimize_smallscreen=1;
941
+}
942
+if (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover'])) {
943
+	$conf->dol_no_mouse_hover=1;
944
+}
945
+if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile'])) {
946
+	$conf->dol_use_jmobile=1;
947
+}
948
+if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') {
949
+	$conf->dol_no_mouse_hover=1;
950
+}
827 951
 if ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')
828 952
 	|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
829 953
 	|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
@@ -832,7 +956,9 @@  discard block
 block discarded – undo
832 956
 	$conf->dol_optimize_smallscreen=1;
833 957
 }
834 958
 // If we force to use jmobile, then we reenable javascript
835
-if (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;
959
+if (! empty($conf->dol_use_jmobile)) {
960
+	$conf->use_javascript_ajax=1;
961
+}
836 962
 // Replace themes bugged with jmobile with eldy
837 963
 if (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))
838 964
 {
@@ -843,7 +969,8 @@  discard block
 block discarded – undo
843 969
 
844 970
 if (! defined('NOREQUIRETRAN'))
845 971
 {
846
-    if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
972
+    if (! GETPOST('lang','aZ09')) {
973
+    	// If language was not forced on URL
847 974
     {
848 975
         // If user has chosen its own language
849 976
         if (! empty($user->conf->MAIN_LANG_DEFAULT))
@@ -853,6 +980,7 @@  discard block
 block discarded – undo
853 980
             if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
854 981
             {
855 982
                 $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
983
+    }
856 984
             }
857 985
         }
858 986
     }
@@ -862,7 +990,9 @@  discard block
 block discarded – undo
862 990
 {
863 991
     // If the login is not recovered, it is identified with an account that does not exist.
864 992
     // Hacking attempt?
865
-    if (! $user->login) accessforbidden();
993
+    if (! $user->login) {
994
+    	accessforbidden();
995
+    }
866 996
 
867 997
     // Check if user is active
868 998
     if ($user->statut < 1)
@@ -913,8 +1043,7 @@  discard block
 block discarded – undo
913 1043
     define('ROWS_7',7);
914 1044
     define('ROWS_8',8);
915 1045
     define('ROWS_9',9);
916
-}
917
-else
1046
+} else
918 1047
 {
919 1048
     define('ROWS_1',0);
920 1049
     define('ROWS_2',1);
@@ -932,18 +1061,22 @@  discard block
 block discarded – undo
932 1061
 // Init menu manager
933 1062
 if (! defined('NOREQUIREMENU'))
934 1063
 {
935
-	if (empty($user->societe_id))    // If internal user or not defined
1064
+	if (empty($user->societe_id)) {
1065
+		// If internal user or not defined
936 1066
 	{
937 1067
 		$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
938 1068
 	}
939
-	else                        // If external user
1069
+	} else                        // If external user
940 1070
 	{
941 1071
 		$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
942 1072
 	}
943 1073
 
944 1074
 	// Load the menu manager (only if not already done)
945 1075
 	$file_menu=$conf->standard_menu;
946
-	if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1076
+	if (GETPOST('menu','alpha')) {
1077
+		$file_menu=GETPOST('menu','alpha');
1078
+	}
1079
+	// example: menu=eldy_menu.php
947 1080
 	if (! class_exists('MenuManager'))
948 1081
 	{
949 1082
 		$menufound=0;
@@ -951,11 +1084,15 @@  discard block
 block discarded – undo
951 1084
 		foreach($dirmenus as $dirmenu)
952 1085
 		{
953 1086
 			$menufound=dol_include_once($dirmenu."standard/".$file_menu);
954
-			if (class_exists('MenuManager')) break;
1087
+			if (class_exists('MenuManager')) {
1088
+				break;
1089
+			}
955 1090
 		}
956
-		if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1091
+		if (! class_exists('MenuManager')) {
1092
+			// If failed to include, we try with standard eldy_menu.php
957 1093
 		{
958 1094
 			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1095
+		}
959 1096
 			$file_menu='eldy_menu.php';
960 1097
 			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
961 1098
 		}
@@ -1023,8 +1160,11 @@  discard block
 block discarded – undo
1023 1160
 {
1024 1161
     global $conf;
1025 1162
 
1026
-    if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1027
-    else header("Content-Type: ".$contenttype);
1163
+    if ($contenttype == 'text/html' ) {
1164
+    	header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1165
+    } else {
1166
+    	header("Content-Type: ".$contenttype);
1167
+    }
1028 1168
     // Security options
1029 1169
     header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1030 1170
     header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
@@ -1064,52 +1204,82 @@  discard block
 block discarded – undo
1064 1204
 
1065 1205
     top_httphead();
1066 1206
 
1067
-    if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1207
+    if (empty($conf->css)) {
1208
+    	$conf->css = '/theme/eldy/style.css.php';
1209
+    }
1210
+    // If not defined, eldy by default
1068 1211
 
1069 1212
     if (! empty($conf->global->MAIN_ACTIVATE_HTML4)) {
1070 1213
         $doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
1071
-    }else {
1214
+    } else {
1072 1215
         $doctype = '<!doctype html>';
1073 1216
     }
1074 1217
     print $doctype."\n";
1075
-    if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1076
-    else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1218
+    if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) {
1219
+    	print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1220
+    } else {
1221
+    	print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1222
+    }
1077 1223
     //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1078 1224
     if (empty($disablehead))
1079 1225
     {
1080 1226
         print "<head>\n";
1081
-		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1227
+		if (GETPOST('dol_basehref','alpha')) {
1228
+			print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1229
+		}
1082 1230
         // Displays meta
1083 1231
         print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";      				// Do not index
1084 1232
         print '<meta name="viewport" content="width=device-width, initial-scale=1.0">';	// Scale for mobile device
1085 1233
         print '<meta name="author" content="Dolibarr Development Team">'."\n";
1086 1234
         // Favicon
1087 1235
 		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1088
-        if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1089
-        if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1236
+        if (! empty($conf->global->MAIN_FAVICON_URL)) {
1237
+        	$favicon=$conf->global->MAIN_FAVICON_URL;
1238
+        }
1239
+        if (empty($conf->dol_use_jmobile)) {
1240
+        	print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";
1241
+        }
1242
+        // Not required into an Android webview
1090 1243
         //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1091
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1092
-        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1244
+        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) {
1245
+        	print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1246
+        }
1247
+        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && ! GETPOST('textbrowser','int')) {
1248
+        	print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1249
+        }
1093 1250
 
1094 1251
         // Displays title
1095 1252
         $appli=constant('DOL_APPLICATION_TITLE');
1096
-        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1253
+        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
1254
+        	$appli=$conf->global->MAIN_APPLICATION_TITLE;
1255
+        }
1097 1256
 
1098
-        if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';
1099
-        else if ($title) print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';
1100
-        else print "<title>".dol_htmlentities($appli)."</title>";
1257
+        if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) {
1258
+        	print '<title>'.dol_htmlentities($title).'</title>';
1259
+        } else if ($title) {
1260
+        	print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';
1261
+        } else {
1262
+        	print "<title>".dol_htmlentities($appli)."</title>";
1263
+        }
1101 1264
         print "\n";
1102 1265
 
1103 1266
         //$ext='';
1104 1267
         //if (! empty($conf->dol_use_jmobile)) $ext='version='.urlencode(DOL_VERSION);
1105 1268
         $ext='version='.urlencode(DOL_VERSION);
1106 1269
 
1107
-        if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1108
-        if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1270
+        if (GETPOST('version','int')) {
1271
+        	$ext='version='.GETPOST('version','int');
1272
+        }
1273
+        // usefull to force no cache on css/js
1274
+        if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) {
1275
+        	$ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1276
+        }
1109 1277
 
1110 1278
         $themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1111 1279
         $themeparam.=($ext?'&amp;'.$ext:'');
1112
-        if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1280
+        if (! empty($_SESSION['dol_resetcache'])) {
1281
+        	$themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1282
+        }
1113 1283
         if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1114 1284
         if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1115 1285
         if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
@@ -1120,11 +1290,25 @@  discard block
 block discarded – undo
1120 1290
         {
1121 1291
             print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1122 1292
             $jquerytheme = 'smoothness';
1123
-            if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1124
-            if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1125
-            else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1126
-            if (! defined('DISABLE_JQUERY_TIPTIP')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/tipTip.css'.($ext?'?'.$ext:'').'">'."\n";                           // Tooltip
1127
-            if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1293
+            if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) {
1294
+            	$jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1295
+            }
1296
+            if (constant('JS_JQUERY_UI')) {
1297
+            	print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";
1298
+            }
1299
+            // JQuery
1300
+            else {
1301
+            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";
1302
+            }
1303
+            // JQuery
1304
+            if (! defined('DISABLE_JQUERY_TIPTIP')) {
1305
+            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/tipTip.css'.($ext?'?'.$ext:'').'">'."\n";
1306
+            }
1307
+            // Tooltip
1308
+            if (! defined('DISABLE_JQUERY_JNOTIFY')) {
1309
+            	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";
1310
+            }
1311
+            // JNotify
1128 1312
             /* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components
1129 1313
             if (! empty($conf->global->MAIN_USE_JQUERY_DATATABLES) || (defined('REQUIRE_JQUERY_DATATABLES') && constant('REQUIRE_JQUERY_DATATABLES')))     // jQuery datatables
1130 1314
             {
@@ -1132,9 +1316,11 @@  discard block
 block discarded – undo
1132 1316
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/Buttons/css/buttons.dataTables.min.css'.($ext?'?'.$ext:'').'">'."\n";
1133 1317
                 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/datatables/extensions/ColReorder/css/colReorder.dataTables.min.css'.($ext?'?'.$ext:'').'"></script>'."\n";
1134 1318
             }*/
1135
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1319
+            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) {
1320
+            	// jQuery plugin "mutiselect", "multiple-select", "select2"...
1136 1321
             {
1137 1322
             	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1323
+            }
1138 1324
             	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1139 1325
             }
1140 1326
             // jQuery Timepicker
@@ -1154,13 +1340,15 @@  discard block
 block discarded – undo
1154 1340
         // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1155 1341
         $themepath=dol_buildpath($conf->css,1);
1156 1342
         $themesubdir='';
1157
-        if (! empty($conf->modules_parts['theme']))	// This slow down
1343
+        if (! empty($conf->modules_parts['theme'])) {
1344
+        	// This slow down
1158 1345
         {
1159 1346
 	        foreach($conf->modules_parts['theme'] as $reldir)
1160 1347
 	        {
1161 1348
 	        	if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1162 1349
 	        	{
1163 1350
 					$themepath=dol_buildpath($reldir.$conf->css, 1);
1351
+        }
1164 1352
 					$themesubdir=$reldir;
1165 1353
 					break;
1166 1354
 	        	}
@@ -1168,7 +1356,9 @@  discard block
 block discarded – undo
1168 1356
         }
1169 1357
         //print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1170 1358
         print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1171
-	    if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1359
+	    if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) {
1360
+	    	print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1361
+	    }
1172 1362
 
1173 1363
         // CSS forced by modules (relative url starting with /)
1174 1364
         if (! empty($conf->modules_parts['css']))
@@ -1179,11 +1369,15 @@  discard block
 block discarded – undo
1179 1369
         		$filescss=(array) $filescss;	// To be sure filecss is an array
1180 1370
         		foreach($filescss as $cssfile)
1181 1371
         		{
1182
-        			if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1372
+        			if (empty($cssfile)) {
1373
+        				dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1374
+        			}
1183 1375
         			// cssfile is a relative path
1184 1376
 	        		print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1185 1377
 	        		// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1186
-	        		if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1378
+	        		if (!preg_match('/\.css$/i',$cssfile)) {
1379
+	        			print $themeparam;
1380
+	        		}
1187 1381
 	        		print '">'."\n";
1188 1382
         		}
1189 1383
         	}
@@ -1195,7 +1389,9 @@  discard block
 block discarded – undo
1195 1389
             {
1196 1390
             	print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1197 1391
                 // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1198
-                if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1392
+                if (!preg_match('/\.css$/i',$cssfile)) {
1393
+                	print $themeparam;
1394
+                }
1199 1395
                 print '">'."\n";
1200 1396
             }
1201 1397
         }
@@ -1205,17 +1401,30 @@  discard block
 block discarded – undo
1205 1401
         {
1206 1402
             // JQuery. Must be before other includes
1207 1403
             print '<!-- Includes JS for JQuery -->'."\n";
1208
-            if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1209
-            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1404
+            if (defined('JS_JQUERY') && constant('JS_JQUERY')) {
1405
+            	print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1406
+            } else {
1407
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1408
+            }
1210 1409
             if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1211 1410
             {
1212
-                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1213
-                else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1411
+                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) {
1412
+                	print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1413
+                } else {
1414
+                	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1415
+                }
1416
+            }
1417
+            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) {
1418
+            	print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1419
+            } else {
1420
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1421
+            }
1422
+            if (! defined('DISABLE_JQUERY_TABLEDND')) {
1423
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.0.6.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1424
+            }
1425
+            if (! defined('DISABLE_JQUERY_TIPTIP')) {
1426
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/jquery.tipTip.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1214 1427
             }
1215
-            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1216
-            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1217
-            if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.0.6.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1218
-            if (! defined('DISABLE_JQUERY_TIPTIP')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tiptip/jquery.tipTip.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1219 1428
             // jQuery jnotify
1220 1429
             if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1221 1430
             {
@@ -1230,8 +1439,7 @@  discard block
 block discarded – undo
1230 1439
                     print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1231 1440
                     print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1232 1441
                     print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1233
-                }
1234
-                else
1442
+                } else
1235 1443
                 {
1236 1444
                     print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1237 1445
                     print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
@@ -1277,9 +1485,11 @@  discard block
 block discarded – undo
1277 1485
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1278 1486
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1279 1487
             }
1280
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1488
+            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) {
1489
+            	// jQuery plugin "mutiselect", "multiple-select", "select2", ...
1281 1490
             {
1282 1491
             	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1492
+            }
1283 1493
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/'.$tmpplugin.'.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1284 1494
             }
1285 1495
         }
@@ -1292,10 +1502,12 @@  discard block
 block discarded – undo
1292 1502
                 print '<!-- Includes JS for CKEditor -->'."\n";
1293 1503
                 $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
1294 1504
                 $jsckeditor='ckeditor.js';
1295
-                if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1505
+                if (constant('JS_CKEDITOR')) {
1506
+                	// To use external ckeditor 4 js lib
1296 1507
                 {
1297 1508
                 	$pathckeditor=constant('JS_CKEDITOR');
1298 1509
                 }
1510
+                }
1299 1511
                 print '<script type="text/javascript">';
1300 1512
                 print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1301 1513
                 print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\';'."\n";		// $themesubdir='' in standard usage
@@ -1309,8 +1521,12 @@  discard block
 block discarded – undo
1309 1521
             if (! defined('DISABLE_BROWSER_NOTIF'))
1310 1522
             {
1311 1523
                 $enablebrowsernotif=false;
1312
-                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;
1313
-                if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
1524
+                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) {
1525
+                	$enablebrowsernotif=true;
1526
+                }
1527
+                if ($conf->browser->layout == 'phone') {
1528
+                	$enablebrowsernotif=false;
1529
+                }
1314 1530
                 if ($enablebrowsernotif)
1315 1531
                 {
1316 1532
                     print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
@@ -1329,9 +1545,11 @@  discard block
 block discarded – undo
1329 1545
             }*/
1330 1546
 
1331 1547
             // JS forced by modules (relative url starting with /)
1332
-            if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1548
+            if (! empty($conf->modules_parts['js'])) {
1549
+            	// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1333 1550
         	{
1334 1551
         		$arrayjs=(array) $conf->modules_parts['js'];
1552
+            }
1335 1553
 	            foreach($arrayjs as $modjs => $filesjs)
1336 1554
 	            {
1337 1555
         			$filesjs=(array) $filesjs;	// To be sure filejs is an array
@@ -1351,18 +1569,24 @@  discard block
 block discarded – undo
1351 1569
                     if (preg_match('/^http/i',$jsfile))
1352 1570
                     {
1353 1571
                         print '<script type="text/javascript" src="'.$jsfile.'"></script>'."\n";
1354
-                    }
1355
-                    else
1572
+                    } else
1356 1573
                     {
1357
-                        if (! preg_match('/^\//',$jsfile)) $jsfile='/'.$jsfile;	// For backward compatibility
1574
+                        if (! preg_match('/^\//',$jsfile)) {
1575
+                        	$jsfile='/'.$jsfile;
1576
+                        }
1577
+                        // For backward compatibility
1358 1578
                         print '<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1359 1579
                     }
1360 1580
                 }
1361 1581
             }
1362 1582
         }
1363 1583
 
1364
-        if (! empty($head)) print $head."\n";
1365
-        if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1584
+        if (! empty($head)) {
1585
+        	print $head."\n";
1586
+        }
1587
+        if (! empty($conf->global->MAIN_HTML_HEADER)) {
1588
+        	print $conf->global->MAIN_HTML_HEADER."\n";
1589
+        }
1366 1590
 
1367 1591
         print "</head>\n\n";
1368 1592
     }
@@ -1430,13 +1654,20 @@  discard block
 block discarded – undo
1430 1654
 	    	$appli=$conf->global->MAIN_APPLICATION_TITLE;
1431 1655
 	    	if (preg_match('/\d\.\d/', $appli))
1432 1656
 	    	{
1433
-				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1657
+				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
1658
+					$appli.=" (".DOL_VERSION.")";
1659
+				}
1660
+				// If new title contains a version that is different than core
1661
+	    	} else {
1662
+	    		$appli.=" ".DOL_VERSION;
1434 1663
 	    	}
1435
-	    	else $appli.=" ".DOL_VERSION;
1664
+	    } else {
1665
+	    	$appli.=" ".DOL_VERSION;
1436 1666
 	    }
1437
-	    else $appli.=" ".DOL_VERSION;
1438 1667
 
1439
-	    if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1668
+	    if (! empty($conf->global->MAIN_FEATURES_LEVEL)) {
1669
+	    	$appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1670
+	    }
1440 1671
 
1441 1672
 	    $logouttext='';
1442 1673
 	    if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
@@ -1450,8 +1681,7 @@  discard block
 block discarded – undo
1450 1681
     	        //$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1451 1682
     	    	$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1452 1683
     	        $logouttext .='</a>';
1453
-    	    }
1454
-    	    else
1684
+    	    } else
1455 1685
     	    {
1456 1686
     	    	$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1457 1687
     	        $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
@@ -1478,10 +1708,18 @@  discard block
 block discarded – undo
1478 1708
 	    $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1479 1709
 		if (is_numeric($result))
1480 1710
 		{
1481
-			if (empty($result)) $toprightmenu.=$hookmanager->resPrint;		// add
1482
-			else  $toprightmenu=$hookmanager->resPrint;						// replace
1711
+			if (empty($result)) {
1712
+				$toprightmenu.=$hookmanager->resPrint;
1713
+			}
1714
+			// add
1715
+			else {
1716
+				$toprightmenu=$hookmanager->resPrint;
1717
+			}
1718
+			// replace
1719
+		} else {
1720
+			$toprightmenu.=$result;
1483 1721
 		}
1484
-		else $toprightmenu.=$result;	// For backward compatibility
1722
+		// For backward compatibility
1485 1723
 
1486 1724
     	// Link to module builder
1487 1725
 	    if (! empty($conf->modulebuilder->enabled))
@@ -1501,7 +1739,9 @@  discard block
 block discarded – undo
1501 1739
 	        if (is_array($_POST))
1502 1740
 	        {
1503 1741
     			foreach($_POST as $key=>$value) {
1504
-    				if ($key!=='action' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1742
+    				if ($key!=='action' && !is_array($value)) {
1743
+    					$qs.='&'.$key.'='.urlencode($value);
1744
+    				}
1505 1745
     			}
1506 1746
 	        }
1507 1747
 			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
@@ -1521,7 +1761,9 @@  discard block
 block discarded – undo
1521 1761
 	        $helppage='';
1522 1762
 	        $mode='';
1523 1763
 
1524
-	        if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1764
+	        if (empty($helppagename)) {
1765
+	        	$helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1766
+	        }
1525 1767
 
1526 1768
 	        // Get helpbaseurl, helppage and mode from helppagename and langs
1527 1769
 	        $arrayres=getHelpParamFor($helppagename,$langs);
@@ -1535,10 +1777,15 @@  discard block
 block discarded – undo
1535 1777
 	            $text='';
1536 1778
 	            $title=$appli.'<br>';
1537 1779
 	            $title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1538
-	            if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1780
+	            if ($mode == 'wiki') {
1781
+	            	$title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1782
+	            }
1539 1783
 	            $text.='<a class="help" target="_blank" href="';
1540
-	            if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1541
-	            else $text.=sprintf($helpbaseurl,$helppage);
1784
+	            if ($mode == 'wiki') {
1785
+	            	$text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1786
+	            } else {
1787
+	            	$text.=sprintf($helpbaseurl,$helppage);
1788
+	            }
1542 1789
 	            $text.='">';
1543 1790
 	            //$text.=img_picto('', 'helpdoc_top').' ';
1544 1791
 	            $text.='<span class="fa fa-question-circle atoplogin"></span>';
@@ -1566,8 +1813,10 @@  discard block
 block discarded – undo
1566 1813
         print "<!-- End top horizontal menu -->\n\n";
1567 1814
     }
1568 1815
 
1569
-    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1570
-}
1816
+    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
1817
+    	print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1818
+    }
1819
+    }
1571 1820
 
1572 1821
 
1573 1822
 /**
@@ -1592,7 +1841,9 @@  discard block
 block discarded – undo
1592 1841
     $searchform='';
1593 1842
     $bookmarks='';
1594 1843
 
1595
-    if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1844
+    if (! empty($menu_array_before)) {
1845
+    	dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1846
+    }
1596 1847
 
1597 1848
     if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1598 1849
     {
@@ -1605,11 +1856,12 @@  discard block
 block discarded – undo
1605 1856
 
1606 1857
 	    if ($conf->use_javascript_ajax && $conf->browser->layout != 'phone' && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1607 1858
 	    {
1608
-    	    if (! is_object($form)) $form=new Form($db);
1859
+    	    if (! is_object($form)) {
1860
+    	    	$form=new Form($db);
1861
+    	    }
1609 1862
     	    $selected=-1;
1610 1863
             $searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1611
-	    }
1612
-	    else
1864
+	    } else
1613 1865
 	    {
1614 1866
     	    // Define $searchform
1615 1867
     	    if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && $user->rights->societe->lire)
@@ -1656,8 +1908,9 @@  discard block
 block discarded – undo
1656 1908
 		if (empty($reshook))
1657 1909
 		{
1658 1910
 			$searchform.=$hookmanager->resPrint;
1911
+		} else {
1912
+			$searchform=$hookmanager->resPrint;
1659 1913
 		}
1660
-		else $searchform=$hookmanager->resPrint;
1661 1914
 
1662 1915
 		if ($conf->use_javascript_ajax && $conf->browser->layout == 'phone')
1663 1916
 	    {
@@ -1697,15 +1950,27 @@  discard block
 block discarded – undo
1697 1950
         print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1698 1951
 
1699 1952
         // Version
1700
-        if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1953
+        if (empty($conf->global->MAIN_HIDE_VERSION)) {
1954
+        	// Version is already on help picto and on login page.
1701 1955
         {
1702 1956
             $doliurl='https://www.dolibarr.org';
1957
+        }
1703 1958
     		//local communities
1704
-    		if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1705
-    		if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1706
-    		if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1707
-    		if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1708
-    		if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1959
+    		if (preg_match('/fr/i',$langs->defaultlang)) {
1960
+    			$doliurl='https://www.dolibarr.fr';
1961
+    		}
1962
+    		if (preg_match('/es/i',$langs->defaultlang)) {
1963
+    			$doliurl='https://www.dolibarr.es';
1964
+    		}
1965
+    		if (preg_match('/de/i',$langs->defaultlang)) {
1966
+    			$doliurl='https://www.dolibarr.de';
1967
+    		}
1968
+    		if (preg_match('/it/i',$langs->defaultlang)) {
1969
+    			$doliurl='https://www.dolibarr.it';
1970
+    		}
1971
+    		if (preg_match('/gr/i',$langs->defaultlang)) {
1972
+    			$doliurl='https://www.dolibarr.gr';
1973
+    		}
1709 1974
 
1710 1975
             $appli=constant('DOL_APPLICATION_TITLE');
1711 1976
     	    if (! empty($conf->global->MAIN_APPLICATION_TITLE))
@@ -1713,17 +1978,28 @@  discard block
 block discarded – undo
1713 1978
     	    	$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1714 1979
     	    	if (preg_match('/\d\.\d/', $appli))
1715 1980
     	    	{
1716
-    				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1981
+    				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
1982
+    					$appli.=" (".DOL_VERSION.")";
1983
+    				}
1984
+    				// If new title contains a version that is different than core
1985
+    	    	} else {
1986
+    	    		$appli.=" ".DOL_VERSION;
1717 1987
     	    	}
1718
-    	    	else $appli.=" ".DOL_VERSION;
1988
+    	    } else {
1989
+    	    	$appli.=" ".DOL_VERSION;
1719 1990
     	    }
1720
-    	    else $appli.=" ".DOL_VERSION;
1721 1991
     	    print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1722
-    	    if ($doliurl) print '<a class="help" target="_blank" href="'.$doliurl.'">';
1723
-    	    else print '<span class="help">';
1992
+    	    if ($doliurl) {
1993
+    	    	print '<a class="help" target="_blank" href="'.$doliurl.'">';
1994
+    	    } else {
1995
+    	    	print '<span class="help">';
1996
+    	    }
1724 1997
     	    print $appli;
1725
-    	    if ($doliurl) print '</a>';
1726
-    	    else print '</span>';
1998
+    	    if ($doliurl) {
1999
+    	    	print '</a>';
2000
+    	    } else {
2001
+    	    	print '</span>';
2002
+    	    }
1727 2003
     	    print '</div>'."\n";
1728 2004
         }
1729 2005
 
@@ -1772,8 +2048,10 @@  discard block
 block discarded – undo
1772 2048
     print "\n";
1773 2049
     print '<!-- Begin right area -->'."\n";
1774 2050
 
1775
-    if (empty($leftmenuwithoutmainarea)) main_area($title);
1776
-}
2051
+    if (empty($leftmenuwithoutmainarea)) {
2052
+    	main_area($title);
2053
+    }
2054
+    }
1777 2055
 
1778 2056
 
1779 2057
 /**
@@ -1786,14 +2064,18 @@  discard block
 block discarded – undo
1786 2064
 {
1787 2065
     global $conf, $langs;
1788 2066
 
1789
-	if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
2067
+	if (empty($conf->dol_hide_leftmenu)) {
2068
+		print '<div id="id-right">';
2069
+	}
1790 2070
 
1791 2071
     print "\n";
1792 2072
 
1793 2073
     print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1794 2074
 
1795
-    if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1796
-}
2075
+    if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) {
2076
+    	print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
2077
+    }
2078
+    }
1797 2079
 
1798 2080
 
1799 2081
 /**
@@ -1815,24 +2097,31 @@  discard block
 block discarded – undo
1815 2097
         $helpbaseurl='%s';
1816 2098
         $helppage=$helppagename;
1817 2099
         $mode='local';
1818
-    }
1819
-    else
2100
+    } else
1820 2101
     {
1821 2102
         // If WIKI URL
1822 2103
         if (preg_match('/^es/i',$langs->defaultlang))
1823 2104
         {
1824 2105
             $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1825
-            if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
2106
+            if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) {
2107
+            	$helppage=$reg[1];
2108
+            }
1826 2109
         }
1827 2110
         if (preg_match('/^fr/i',$langs->defaultlang))
1828 2111
         {
1829 2112
             $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1830
-            if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
2113
+            if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) {
2114
+            	$helppage=$reg[1];
2115
+            }
1831 2116
         }
1832
-        if (empty($helppage))	// If help page not already found
2117
+        if (empty($helppage)) {
2118
+        	// If help page not already found
1833 2119
         {
1834 2120
             $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1835
-            if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
2121
+        }
2122
+            if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) {
2123
+            	$helppage=$reg[1];
2124
+            }
1836 2125
         }
1837 2126
         $mode='wiki';
1838 2127
     }
@@ -1866,12 +2155,17 @@  discard block
 block discarded – undo
1866 2155
 	if (empty($conf->global->MAIN_HTML5_PLACEHOLDER))
1867 2156
 	{
1868 2157
         $ret.='<div class="menu_titre menu_titre_search"';
1869
-    	if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="display: inline-block"';
2158
+    	if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) {
2159
+    		$ret.=' style="display: inline-block"';
2160
+    	}
1870 2161
     	$ret.='>';
1871 2162
     	$ret.='<label for="'.$prefhtmlinputname.$htmlinputname.'">';
1872 2163
     	$ret.='<a class="vsmenu" href="'.$urlobject.'">';
1873
-       	if ($img && ! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=$img;
1874
-       	else if ($img || $title) $ret.=$img.' '.$title;
2164
+       	if ($img && ! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) {
2165
+       		$ret.=$img;
2166
+       	} else if ($img || $title) {
2167
+       		$ret.=$img.' '.$title;
2168
+       	}
1875 2169
     	$ret.='</a>';
1876 2170
     	$ret.='</label>';
1877 2171
     	$ret.='</div>';
@@ -1879,10 +2173,17 @@  discard block
 block discarded – undo
1879 2173
     $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1880 2174
     $ret.='<input type="hidden" name="mode" value="search">';
1881 2175
     $ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1882
-    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
2176
+    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) {
2177
+    	$ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
2178
+    }
1883 2179
     $ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1884
-    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $ret.=' placeholder="'.strip_tags($title).'"';		// Will work only if MAIN_HTML5_PLACEHOLDER is set to 1
1885
-    else $ret.=' title="'.$langs->trans("SearchOf").''.strip_tags($title).'"';
2180
+    if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) {
2181
+    	$ret.=' placeholder="'.strip_tags($title).'"';
2182
+    }
2183
+    // Will work only if MAIN_HTML5_PLACEHOLDER is set to 1
2184
+    else {
2185
+    	$ret.=' title="'.$langs->trans("SearchOf").''.strip_tags($title).'"';
2186
+    }
1886 2187
     $ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1887 2188
     $ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1888 2189
     $ret.="</form>\n";
@@ -1919,8 +2220,12 @@  discard block
 block discarded – undo
1919 2220
                 unset($_SESSION['lastsearch_values_tmp_'.$key]);
1920 2221
                 if (count($val))
1921 2222
                 {
1922
-                    if (empty($val['sortfield'])) unset($val['sortfield']);
1923
-                    if (empty($val['sortorder'])) unset($val['sortorder']);
2223
+                    if (empty($val['sortfield'])) {
2224
+                    	unset($val['sortfield']);
2225
+                    }
2226
+                    if (empty($val['sortorder'])) {
2227
+                    	unset($val['sortorder']);
2228
+                    }
1924 2229
                     dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criteria)");
1925 2230
                     $_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
1926 2231
                     unset($_SESSION['lastsearch_values_'.$key]);
@@ -1951,16 +2256,26 @@  discard block
 block discarded – undo
1951 2256
 
1952 2257
         print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
1953 2258
 
1954
-		if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'; // End div id-right
2259
+		if (empty($conf->dol_hide_leftmenu)) {
2260
+			print '</div> <!-- End div id-right -->';
2261
+		}
2262
+		// End div id-right
1955 2263
 
1956 2264
         print "\n";
1957
-        if ($comment) print '<!-- '.$comment.' -->'."\n";
2265
+        if ($comment) {
2266
+        	print '<!-- '.$comment.' -->'."\n";
2267
+        }
1958 2268
 
1959 2269
         printCommonFooter($zone);
1960 2270
 
1961
-        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2271
+        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
2272
+        	print '</div> <!-- End div id-container -->'."\n";
2273
+        }
2274
+        // End div container
1962 2275
 
1963
-        if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2276
+        if (! empty($delayedhtmlcontent)) {
2277
+        	print $delayedhtmlcontent;
2278
+        }
1964 2279
 
1965 2280
         // TODO Move this in lib_head.js.php
1966 2281
 
@@ -2041,9 +2356,11 @@  discard block
 block discarded – undo
2041 2356
         // Wrapper to add log when clicking on download or preview
2042 2357
         if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2043 2358
         {
2044
-            if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2359
+            if (in_array($object->element, array('facture'))) {
2360
+            	// Restrict for the moment to element 'facture'
2045 2361
             {
2046 2362
                 print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2363
+            }
2047 2364
                 ?>
2048 2365
     			<script type="text/javascript">
2049 2366
     			jQuery(document).ready(function () {
Please login to merge, or discard this patch.
htdocs/product/class/productcustomerprice.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -507,7 +507,7 @@
 block discarded – undo
507 507
 	/**
508 508
 	 * Update object into database
509 509
 	 *
510
-	 * @param User $user that modifies
510
+	 * @param integer $user that modifies
511 511
 	 * @param int $notrigger triggers after, 1=disable triggers
512 512
 	 * @param int $forceupdateaffiliate update price on each soc child
513 513
 	 * @return int <0 if KO, >0 if OK
Please login to merge, or discard this patch.
Braces   +108 added lines, -64 removed lines patch added patch discarded remove patch
@@ -75,34 +75,48 @@  discard block
 block discarded – undo
75 75
 
76 76
 		// Clean parameters
77 77
 
78
-		if (isset($this->entity))
79
-			$this->entity = trim($this->entity);
80
-		if (isset($this->fk_product))
81
-			$this->fk_product = trim($this->fk_product);
82
-		if (isset($this->fk_soc))
83
-			$this->fk_soc = trim($this->fk_soc);
84
-		if (isset($this->price))
85
-			$this->price = trim($this->price);
86
-		if (isset($this->price_ttc))
87
-			$this->price_ttc = trim($this->price_ttc);
88
-		if (isset($this->price_min))
89
-			$this->price_min = trim($this->price_min);
90
-		if (isset($this->price_min_ttc))
91
-			$this->price_min_ttc = trim($this->price_min_ttc);
92
-		if (isset($this->price_base_type))
93
-			$this->price_base_type = trim($this->price_base_type);
94
-		if (isset($this->tva_tx))
95
-			$this->tva_tx = trim($this->tva_tx);
96
-		if (isset($this->recuperableonly))
97
-			$this->recuperableonly = trim($this->recuperableonly);
98
-		if (isset($this->localtax1_tx))
99
-			$this->localtax1_tx = trim($this->localtax1_tx);
100
-		if (isset($this->localtax2_tx))
101
-			$this->localtax2_tx = trim($this->localtax2_tx);
102
-		if (isset($this->fk_user))
103
-			$this->fk_user = trim($this->fk_user);
104
-		if (isset($this->import_key))
105
-			$this->import_key = trim($this->import_key);
78
+		if (isset($this->entity)) {
79
+					$this->entity = trim($this->entity);
80
+		}
81
+		if (isset($this->fk_product)) {
82
+					$this->fk_product = trim($this->fk_product);
83
+		}
84
+		if (isset($this->fk_soc)) {
85
+					$this->fk_soc = trim($this->fk_soc);
86
+		}
87
+		if (isset($this->price)) {
88
+					$this->price = trim($this->price);
89
+		}
90
+		if (isset($this->price_ttc)) {
91
+					$this->price_ttc = trim($this->price_ttc);
92
+		}
93
+		if (isset($this->price_min)) {
94
+					$this->price_min = trim($this->price_min);
95
+		}
96
+		if (isset($this->price_min_ttc)) {
97
+					$this->price_min_ttc = trim($this->price_min_ttc);
98
+		}
99
+		if (isset($this->price_base_type)) {
100
+					$this->price_base_type = trim($this->price_base_type);
101
+		}
102
+		if (isset($this->tva_tx)) {
103
+					$this->tva_tx = trim($this->tva_tx);
104
+		}
105
+		if (isset($this->recuperableonly)) {
106
+					$this->recuperableonly = trim($this->recuperableonly);
107
+		}
108
+		if (isset($this->localtax1_tx)) {
109
+					$this->localtax1_tx = trim($this->localtax1_tx);
110
+		}
111
+		if (isset($this->localtax2_tx)) {
112
+					$this->localtax2_tx = trim($this->localtax2_tx);
113
+		}
114
+		if (isset($this->fk_user)) {
115
+					$this->fk_user = trim($this->fk_user);
116
+		}
117
+		if (isset($this->import_key)) {
118
+					$this->import_key = trim($this->import_key);
119
+		}
106 120
 
107 121
 			// Check parameters
108 122
 			// Put here code to add control on parameters values
@@ -308,8 +322,12 @@  discard block
 block discarded – undo
308 322
 	{
309 323
 		global $langs;
310 324
 
311
-		if ( empty($sortfield)) $sortfield = "t.rowid";
312
-		if ( empty($sortorder)) $sortorder = "DESC";
325
+		if ( empty($sortfield)) {
326
+			$sortfield = "t.rowid";
327
+		}
328
+		if ( empty($sortorder)) {
329
+			$sortorder = "DESC";
330
+		}
313 331
 
314 332
 		$sql = "SELECT";
315 333
 		$sql .= " t.rowid,";
@@ -343,9 +361,11 @@  discard block
 block discarded – undo
343 361
 		// Manage filter
344 362
 		if (count($filter) > 0) {
345 363
 			foreach ( $filter as $key => $value ) {
346
-				if (strpos($key, 'date')) 				// To allow $filter['YEAR(s.dated)']=>$year
364
+				if (strpos($key, 'date')) {
365
+					// To allow $filter['YEAR(s.dated)']=>$year
347 366
 				{
348 367
 					$sql .= ' AND ' . $key . ' = \'' . $value . '\'';
368
+				}
349 369
 				} elseif ($key == 'soc.nom') {
350 370
 					$sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\'';
351 371
 				} elseif ($key == 'prod.ref') {
@@ -356,7 +376,9 @@  discard block
 block discarded – undo
356 376
 			}
357 377
 		}
358 378
 		$sql.= $this->db->order($sortfield, $sortorder);
359
-		if (! empty($limit)) $sql .= ' ' . $this->db->plimit($limit + 1, $offset);
379
+		if (! empty($limit)) {
380
+			$sql .= ' ' . $this->db->plimit($limit + 1, $offset);
381
+		}
360 382
 
361 383
 		dol_syslog(get_class($this) . "::fetch_all", LOG_DEBUG);
362 384
 		$resql = $this->db->query($sql);
@@ -416,8 +438,12 @@  discard block
 block discarded – undo
416 438
 	{
417 439
 		global $langs;
418 440
 
419
-		if (! empty($sortfield)) $sortfield = "t.rowid";
420
-		if (! empty($sortorder)) $sortorder = "DESC";
441
+		if (! empty($sortfield)) {
442
+			$sortfield = "t.rowid";
443
+		}
444
+		if (! empty($sortorder)) {
445
+			$sortorder = "DESC";
446
+		}
421 447
 
422 448
 		$sql = "SELECT";
423 449
 		$sql .= " t.rowid,";
@@ -450,9 +476,11 @@  discard block
 block discarded – undo
450 476
 		// Manage filter
451 477
 		if (count($filter) > 0) {
452 478
 			foreach ( $filter as $key => $value ) {
453
-				if (strpos($key, 'date')) 				// To allow $filter['YEAR(s.dated)']=>$year
479
+				if (strpos($key, 'date')) {
480
+					// To allow $filter['YEAR(s.dated)']=>$year
454 481
 				{
455 482
 					$sql .= ' AND ' . $key . ' = \'' . $value . '\'';
483
+				}
456 484
 				} elseif ($key == 'soc.nom') {
457 485
 					$sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\'';
458 486
 				} else {
@@ -462,7 +490,9 @@  discard block
 block discarded – undo
462 490
 		}
463 491
 
464 492
 		$sql.= $this->db->order($sortfield, $sortorder);
465
-		if (! empty($limit)) $sql .= ' ' . $this->db->plimit($limit + 1, $offset);
493
+		if (! empty($limit)) {
494
+			$sql .= ' ' . $this->db->plimit($limit + 1, $offset);
495
+		}
466 496
 
467 497
 		dol_syslog(get_class($this) . "::fetch_all_log", LOG_DEBUG);
468 498
 		$resql = $this->db->query($sql);
@@ -523,34 +553,48 @@  discard block
 block discarded – undo
523 553
 
524 554
 		// Clean parameters
525 555
 
526
-		if (isset($this->entity))
527
-			$this->entity = trim($this->entity);
528
-		if (isset($this->fk_product))
529
-			$this->fk_product = trim($this->fk_product);
530
-		if (isset($this->fk_soc))
531
-			$this->fk_soc = trim($this->fk_soc);
532
-		if (isset($this->price))
533
-			$this->price = trim($this->price);
534
-		if (isset($this->price_ttc))
535
-			$this->price_ttc = trim($this->price_ttc);
536
-		if (isset($this->price_min))
537
-			$this->price_min = trim($this->price_min);
538
-		if (isset($this->price_min_ttc))
539
-			$this->price_min_ttc = trim($this->price_min_ttc);
540
-		if (isset($this->price_base_type))
541
-			$this->price_base_type = trim($this->price_base_type);
542
-		if (isset($this->tva_tx))
543
-			$this->tva_tx = trim($this->tva_tx);
544
-		if (isset($this->recuperableonly))
545
-			$this->recuperableonly = trim($this->recuperableonly);
546
-		if (isset($this->localtax1_tx))
547
-			$this->localtax1_tx = trim($this->localtax1_tx);
548
-		if (isset($this->localtax2_tx))
549
-			$this->localtax2_tx = trim($this->localtax2_tx);
550
-		if (isset($this->fk_user))
551
-			$this->fk_user = trim($this->fk_user);
552
-		if (isset($this->import_key))
553
-			$this->import_key = trim($this->import_key);
556
+		if (isset($this->entity)) {
557
+					$this->entity = trim($this->entity);
558
+		}
559
+		if (isset($this->fk_product)) {
560
+					$this->fk_product = trim($this->fk_product);
561
+		}
562
+		if (isset($this->fk_soc)) {
563
+					$this->fk_soc = trim($this->fk_soc);
564
+		}
565
+		if (isset($this->price)) {
566
+					$this->price = trim($this->price);
567
+		}
568
+		if (isset($this->price_ttc)) {
569
+					$this->price_ttc = trim($this->price_ttc);
570
+		}
571
+		if (isset($this->price_min)) {
572
+					$this->price_min = trim($this->price_min);
573
+		}
574
+		if (isset($this->price_min_ttc)) {
575
+					$this->price_min_ttc = trim($this->price_min_ttc);
576
+		}
577
+		if (isset($this->price_base_type)) {
578
+					$this->price_base_type = trim($this->price_base_type);
579
+		}
580
+		if (isset($this->tva_tx)) {
581
+					$this->tva_tx = trim($this->tva_tx);
582
+		}
583
+		if (isset($this->recuperableonly)) {
584
+					$this->recuperableonly = trim($this->recuperableonly);
585
+		}
586
+		if (isset($this->localtax1_tx)) {
587
+					$this->localtax1_tx = trim($this->localtax1_tx);
588
+		}
589
+		if (isset($this->localtax2_tx)) {
590
+					$this->localtax2_tx = trim($this->localtax2_tx);
591
+		}
592
+		if (isset($this->fk_user)) {
593
+					$this->fk_user = trim($this->fk_user);
594
+		}
595
+		if (isset($this->import_key)) {
596
+					$this->import_key = trim($this->import_key);
597
+		}
554 598
 
555 599
 			// Check parameters
556 600
 			// Put here code to add a control on parameters values
Please login to merge, or discard this patch.
Spacing   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
  * \ingroup produit
22 22
  * \brief File of class to manage predefined price products or services by customer
23 23
  */
24
-require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
24
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
25 25
 
26 26
 /**
27 27
  * File of class to manage predefined price products or services by customer
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 	var $localtax2_type;
48 48
 	var $localtax2_tx;
49 49
 	var $fk_user;
50
-	var $lines = array ();
50
+	var $lines = array();
51 51
 
52 52
 	/**
53 53
 	 * Constructor
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 		}
140 140
 
141 141
 		// Insert request
142
-		$sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_customer_price(";
142
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_customer_price(";
143 143
 		$sql .= "entity,";
144 144
 		$sql .= "datec,";
145 145
 		$sql .= "fk_product,";
@@ -159,39 +159,39 @@  discard block
 block discarded – undo
159 159
 		$sql .= "fk_user,";
160 160
 		$sql .= "import_key";
161 161
 		$sql .= ") VALUES (";
162
-		$sql .= " " . $conf->entity . ",";
163
-		$sql .= " '" . $this->db->idate(dol_now()) . "',";
164
-		$sql .= " " . (! isset($this->fk_product) ? 'NULL' : "'" . $this->db->escape($this->fk_product) . "'") . ",";
165
-		$sql .= " " . (! isset($this->fk_soc) ? 'NULL' : "'" . $this->db->escape($this->fk_soc) . "'") . ",";
166
-		$sql .= " " . (empty($this->price) ? '0' : "'" . $this->db->escape($this->price) . "'") . ",";
167
-		$sql .= " " . (empty($this->price_ttc) ? '0' : "'" . $this->db->escape($this->price_ttc) . "'") . ",";
168
-		$sql .= " " . (empty($this->price_min) ? '0' : "'" . $this->db->escape($this->price_min) . "'") . ",";
169
-		$sql .= " " . (empty($this->price_min_ttc) ? '0' : "'" . $this->db->escape($this->price_min_ttc) . "'") . ",";
170
-		$sql .= " " . (! isset($this->price_base_type) ? 'NULL' : "'" . $this->db->escape($this->price_base_type) . "'") . ",";
162
+		$sql .= " ".$conf->entity.",";
163
+		$sql .= " '".$this->db->idate(dol_now())."',";
164
+		$sql .= " ".(!isset($this->fk_product) ? 'NULL' : "'".$this->db->escape($this->fk_product)."'").",";
165
+		$sql .= " ".(!isset($this->fk_soc) ? 'NULL' : "'".$this->db->escape($this->fk_soc)."'").",";
166
+		$sql .= " ".(empty($this->price) ? '0' : "'".$this->db->escape($this->price)."'").",";
167
+		$sql .= " ".(empty($this->price_ttc) ? '0' : "'".$this->db->escape($this->price_ttc)."'").",";
168
+		$sql .= " ".(empty($this->price_min) ? '0' : "'".$this->db->escape($this->price_min)."'").",";
169
+		$sql .= " ".(empty($this->price_min_ttc) ? '0' : "'".$this->db->escape($this->price_min_ttc)."'").",";
170
+		$sql .= " ".(!isset($this->price_base_type) ? 'NULL' : "'".$this->db->escape($this->price_base_type)."'").",";
171 171
 		$sql .= " ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null").",";
172
-		$sql .= " " . (! isset($this->tva_tx) ? 'NULL' : (empty($this->tva_tx)?0:$this->tva_tx)) . ",";
173
-		$sql .= " " . (! isset($this->recuperableonly) ? 'NULL' : "'" . $this->db->escape($this->recuperableonly) . "'") . ",";
174
-		$sql .= " " . (empty($this->localtax1_type) ? "'0'" : "'" . $this->db->escape($this->localtax1_type) . "'") . ",";
175
-		$sql .= " " . (! isset($this->localtax1_tx) ? 'NULL' : (empty($this->localtax1_tx)?0:$this->localtax1_tx)) . ",";
176
-		$sql .= " " . (empty($this->localtax2_type) ? "'0'" : "'" . $this->db->escape($this->localtax2_type) . "'") . ",";
177
-		$sql .= " " . (! isset($this->localtax2_tx) ? 'NULL' : (empty($this->localtax2_tx)?0:$this->localtax2_tx)) . ",";
178
-		$sql .= " " . $user->id . ",";
179
-		$sql .= " " . (! isset($this->import_key) ? 'NULL' : "'" . $this->db->escape($this->import_key) . "'") . "";
172
+		$sql .= " ".(!isset($this->tva_tx) ? 'NULL' : (empty($this->tva_tx) ? 0 : $this->tva_tx)).",";
173
+		$sql .= " ".(!isset($this->recuperableonly) ? 'NULL' : "'".$this->db->escape($this->recuperableonly)."'").",";
174
+		$sql .= " ".(empty($this->localtax1_type) ? "'0'" : "'".$this->db->escape($this->localtax1_type)."'").",";
175
+		$sql .= " ".(!isset($this->localtax1_tx) ? 'NULL' : (empty($this->localtax1_tx) ? 0 : $this->localtax1_tx)).",";
176
+		$sql .= " ".(empty($this->localtax2_type) ? "'0'" : "'".$this->db->escape($this->localtax2_type)."'").",";
177
+		$sql .= " ".(!isset($this->localtax2_tx) ? 'NULL' : (empty($this->localtax2_tx) ? 0 : $this->localtax2_tx)).",";
178
+		$sql .= " ".$user->id.",";
179
+		$sql .= " ".(!isset($this->import_key) ? 'NULL' : "'".$this->db->escape($this->import_key)."'")."";
180 180
 		$sql .= ")";
181 181
 
182 182
 		$this->db->begin();
183 183
 
184
-		dol_syslog(get_class($this) . "::create", LOG_DEBUG);
184
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
185 185
 		$resql = $this->db->query($sql);
186
-		if (! $resql) {
187
-			$error ++;
188
-			$this->errors [] = "Error " . $this->db->lasterror();
186
+		if (!$resql) {
187
+			$error++;
188
+			$this->errors [] = "Error ".$this->db->lasterror();
189 189
 		}
190 190
 
191
-		if (! $error) {
192
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "product_customer_price");
191
+		if (!$error) {
192
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."product_customer_price");
193 193
 
194
-			if (! $notrigger) {
194
+			if (!$notrigger) {
195 195
 				// Uncomment this and change MYOBJECT to your own tag if you
196 196
 				// want this action calls a trigger.
197 197
 
@@ -204,21 +204,21 @@  discard block
 block discarded – undo
204 204
 			}
205 205
 		}
206 206
 
207
-		if (! $error) {
207
+		if (!$error) {
208 208
 			$result = $this->setPriceOnAffiliateThirdparty($user, $forceupdateaffiliate);
209 209
 			if ($result < 0) {
210
-				$error ++;
210
+				$error++;
211 211
 			}
212 212
 		}
213 213
 
214 214
 		// Commit or rollback
215 215
 		if ($error) {
216
-			foreach ( $this->errors as $errmsg ) {
217
-				dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR);
218
-				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
216
+			foreach ($this->errors as $errmsg) {
217
+				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
218
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
219 219
 			}
220 220
 			$this->db->rollback();
221
-			return - 1 * $error;
221
+			return -1 * $error;
222 222
 		} else {
223 223
 			$this->db->commit();
224 224
 			return $this->id;
@@ -256,10 +256,10 @@  discard block
 block discarded – undo
256 256
 		$sql .= " t.fk_user,";
257 257
 		$sql .= " t.import_key";
258 258
 
259
-		$sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price as t";
260
-		$sql .= " WHERE t.rowid = " . $id;
259
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price as t";
260
+		$sql .= " WHERE t.rowid = ".$id;
261 261
 
262
-		dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
262
+		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
263 263
 		$resql = $this->db->query($sql);
264 264
 		if ($resql) {
265 265
 			if ($this->db->num_rows($resql)) {
@@ -289,8 +289,8 @@  discard block
 block discarded – undo
289 289
 
290 290
 			return 1;
291 291
 		} else {
292
-			$this->error = "Error " . $this->db->lasterror();
293
-			return - 1;
292
+			$this->error = "Error ".$this->db->lasterror();
293
+			return -1;
294 294
 		}
295 295
 	}
296 296
 
@@ -308,8 +308,8 @@  discard block
 block discarded – undo
308 308
 	{
309 309
 		global $langs;
310 310
 
311
-		if ( empty($sortfield)) $sortfield = "t.rowid";
312
-		if ( empty($sortorder)) $sortorder = "DESC";
311
+		if (empty($sortfield)) $sortfield = "t.rowid";
312
+		if (empty($sortorder)) $sortorder = "DESC";
313 313
 
314 314
 		$sql = "SELECT";
315 315
 		$sql .= " t.rowid,";
@@ -333,39 +333,39 @@  discard block
 block discarded – undo
333 333
 		$sql .= " t.import_key,";
334 334
 		$sql .= " soc.nom as socname,";
335 335
 		$sql .= " prod.ref as prodref";
336
-		$sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price as t ";
337
-		$sql .= " ," . MAIN_DB_PREFIX . "product as prod ";
338
-		$sql .= " ," . MAIN_DB_PREFIX . "societe as soc ";
336
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price as t ";
337
+		$sql .= " ,".MAIN_DB_PREFIX."product as prod ";
338
+		$sql .= " ,".MAIN_DB_PREFIX."societe as soc ";
339 339
 		$sql .= " WHERE soc.rowid=t.fk_soc ";
340 340
 		$sql .= " AND prod.rowid=t.fk_product ";
341
-		$sql .= " AND prod.entity IN (" . getEntity('product') . ")";
341
+		$sql .= " AND prod.entity IN (".getEntity('product').")";
342 342
 
343 343
 		// Manage filter
344 344
 		if (count($filter) > 0) {
345
-			foreach ( $filter as $key => $value ) {
345
+			foreach ($filter as $key => $value) {
346 346
 				if (strpos($key, 'date')) 				// To allow $filter['YEAR(s.dated)']=>$year
347 347
 				{
348
-					$sql .= ' AND ' . $key . ' = \'' . $value . '\'';
348
+					$sql .= ' AND '.$key.' = \''.$value.'\'';
349 349
 				} elseif ($key == 'soc.nom') {
350
-					$sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\'';
350
+					$sql .= ' AND '.$key.' LIKE \'%'.$value.'%\'';
351 351
 				} elseif ($key == 'prod.ref') {
352
-					$sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\'';
352
+					$sql .= ' AND '.$key.' LIKE \'%'.$value.'%\'';
353 353
 				} else {
354
-					$sql .= ' AND ' . $key . ' = ' . $value;
354
+					$sql .= ' AND '.$key.' = '.$value;
355 355
 				}
356 356
 			}
357 357
 		}
358
-		$sql.= $this->db->order($sortfield, $sortorder);
359
-		if (! empty($limit)) $sql .= ' ' . $this->db->plimit($limit + 1, $offset);
358
+		$sql .= $this->db->order($sortfield, $sortorder);
359
+		if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset);
360 360
 
361
-		dol_syslog(get_class($this) . "::fetch_all", LOG_DEBUG);
361
+		dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
362 362
 		$resql = $this->db->query($sql);
363 363
 		if ($resql) {
364 364
 
365
-			$this->lines = array ();
365
+			$this->lines = array();
366 366
 			$num = $this->db->num_rows($resql);
367 367
 
368
-			while ( $obj = $this->db->fetch_object($resql) ) {
368
+			while ($obj = $this->db->fetch_object($resql)) {
369 369
 
370 370
 				$line = new PriceByCustomerLine();
371 371
 
@@ -397,8 +397,8 @@  discard block
 block discarded – undo
397 397
 
398 398
 			return $num;
399 399
 		} else {
400
-			$this->error = "Error " . $this->db->lasterror();
401
-			return - 1;
400
+			$this->error = "Error ".$this->db->lasterror();
401
+			return -1;
402 402
 		}
403 403
 	}
404 404
 
@@ -416,8 +416,8 @@  discard block
 block discarded – undo
416 416
 	{
417 417
 		global $langs;
418 418
 
419
-		if (! empty($sortfield)) $sortfield = "t.rowid";
420
-		if (! empty($sortorder)) $sortorder = "DESC";
419
+		if (!empty($sortfield)) $sortfield = "t.rowid";
420
+		if (!empty($sortorder)) $sortorder = "DESC";
421 421
 
422 422
 		$sql = "SELECT";
423 423
 		$sql .= " t.rowid,";
@@ -440,38 +440,38 @@  discard block
 block discarded – undo
440 440
 		$sql .= " t.import_key,";
441 441
 		$sql .= " soc.nom as socname,";
442 442
 		$sql .= " prod.ref as prodref";
443
-		$sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price_log as t ";
444
-		$sql .= " ," . MAIN_DB_PREFIX . "product as prod ";
445
-		$sql .= " ," . MAIN_DB_PREFIX . "societe as soc ";
443
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price_log as t ";
444
+		$sql .= " ,".MAIN_DB_PREFIX."product as prod ";
445
+		$sql .= " ,".MAIN_DB_PREFIX."societe as soc ";
446 446
 		$sql .= " WHERE soc.rowid=t.fk_soc ";
447 447
 		$sql .= " AND prod.rowid=t.fk_product ";
448
-		$sql .= " AND prod.entity IN (" . getEntity('product') . ")";
448
+		$sql .= " AND prod.entity IN (".getEntity('product').")";
449 449
 
450 450
 		// Manage filter
451 451
 		if (count($filter) > 0) {
452
-			foreach ( $filter as $key => $value ) {
452
+			foreach ($filter as $key => $value) {
453 453
 				if (strpos($key, 'date')) 				// To allow $filter['YEAR(s.dated)']=>$year
454 454
 				{
455
-					$sql .= ' AND ' . $key . ' = \'' . $value . '\'';
455
+					$sql .= ' AND '.$key.' = \''.$value.'\'';
456 456
 				} elseif ($key == 'soc.nom') {
457
-					$sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\'';
457
+					$sql .= ' AND '.$key.' LIKE \'%'.$value.'%\'';
458 458
 				} else {
459
-					$sql .= ' AND ' . $key . ' = ' . $value;
459
+					$sql .= ' AND '.$key.' = '.$value;
460 460
 				}
461 461
 			}
462 462
 		}
463 463
 
464
-		$sql.= $this->db->order($sortfield, $sortorder);
465
-		if (! empty($limit)) $sql .= ' ' . $this->db->plimit($limit + 1, $offset);
464
+		$sql .= $this->db->order($sortfield, $sortorder);
465
+		if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset);
466 466
 
467
-		dol_syslog(get_class($this) . "::fetch_all_log", LOG_DEBUG);
467
+		dol_syslog(get_class($this)."::fetch_all_log", LOG_DEBUG);
468 468
 		$resql = $this->db->query($sql);
469 469
 		if ($resql) {
470 470
 
471
-			$this->lines = array ();
471
+			$this->lines = array();
472 472
 			$num = $this->db->num_rows($resql);
473 473
 
474
-			while ( $obj = $this->db->fetch_object($resql) ) {
474
+			while ($obj = $this->db->fetch_object($resql)) {
475 475
 
476 476
 				$line = new PriceByCustomerLine();
477 477
 
@@ -503,8 +503,8 @@  discard block
 block discarded – undo
503 503
 
504 504
 			return $num;
505 505
 		} else {
506
-			$this->error = "Error " . $this->db->lasterror();
507
-			return - 1;
506
+			$this->error = "Error ".$this->db->lasterror();
507
+			return -1;
508 508
 		}
509 509
 	}
510 510
 
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
 
589 589
 		// Do a copy of current record into log table
590 590
 		// Insert request
591
-		$sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_customer_price_log(";
591
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_customer_price_log(";
592 592
 
593 593
 		$sql .= "entity,";
594 594
 		$sql .= "datec,";
@@ -631,75 +631,75 @@  discard block
 block discarded – undo
631 631
 		$sql .= " t.fk_user,";
632 632
 		$sql .= " t.import_key";
633 633
 
634
-		$sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price as t";
635
-		$sql .= " WHERE t.rowid = " . $this->id;
634
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price as t";
635
+		$sql .= " WHERE t.rowid = ".$this->id;
636 636
 
637 637
 		$this->db->begin();
638
-		dol_syslog(get_class($this) . "::update", LOG_DEBUG);
638
+		dol_syslog(get_class($this)."::update", LOG_DEBUG);
639 639
 		$resql = $this->db->query($sql);
640
-		if (! $resql) {
641
-			$error ++;
642
-			$this->errors [] = "Error " . $this->db->lasterror();
640
+		if (!$resql) {
641
+			$error++;
642
+			$this->errors [] = "Error ".$this->db->lasterror();
643 643
 		}
644 644
 
645 645
 		// Update request
646
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "product_customer_price SET";
647
-
648
-		$sql .= " entity=" . $conf->entity . ",";
649
-		$sql .= " datec='" . $this->db->idate(dol_now()) . "',";
650
-		$sql .= " tms=" . (dol_strlen($this->tms) != 0 ? "'" . $this->db->idate($this->tms) . "'" : 'null') . ",";
651
-		$sql .= " fk_product=" . (isset($this->fk_product) ? $this->fk_product : "null") . ",";
652
-		$sql .= " fk_soc=" . (isset($this->fk_soc) ? $this->fk_soc : "null") . ",";
653
-		$sql .= " price=" . (isset($this->price) ? $this->price : "null") . ",";
654
-		$sql .= " price_ttc=" . (isset($this->price_ttc) ? $this->price_ttc : "null") . ",";
655
-		$sql .= " price_min=" . (isset($this->price_min) ? $this->price_min : "null") . ",";
656
-		$sql .= " price_min_ttc=" . (isset($this->price_min_ttc) ? $this->price_min_ttc : "null") . ",";
657
-		$sql .= " price_base_type=" . (isset($this->price_base_type) ? "'" . $this->db->escape($this->price_base_type) . "'" : "null") . ",";
646
+		$sql = "UPDATE ".MAIN_DB_PREFIX."product_customer_price SET";
647
+
648
+		$sql .= " entity=".$conf->entity.",";
649
+		$sql .= " datec='".$this->db->idate(dol_now())."',";
650
+		$sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
651
+		$sql .= " fk_product=".(isset($this->fk_product) ? $this->fk_product : "null").",";
652
+		$sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").",";
653
+		$sql .= " price=".(isset($this->price) ? $this->price : "null").",";
654
+		$sql .= " price_ttc=".(isset($this->price_ttc) ? $this->price_ttc : "null").",";
655
+		$sql .= " price_min=".(isset($this->price_min) ? $this->price_min : "null").",";
656
+		$sql .= " price_min_ttc=".(isset($this->price_min_ttc) ? $this->price_min_ttc : "null").",";
657
+		$sql .= " price_base_type=".(isset($this->price_base_type) ? "'".$this->db->escape($this->price_base_type)."'" : "null").",";
658 658
 		$sql .= " default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null").",";
659
-		$sql .= " tva_tx=" . (isset($this->tva_tx) ? (empty($this->tva_tx)?0:$this->tva_tx) : "null") . ",";
660
-		$sql .= " recuperableonly=" . (isset($this->recuperableonly) ? $this->recuperableonly : "null") . ",";
661
-		$sql .= " localtax1_tx=" . (isset($this->localtax1_tx) ? (empty($this->localtax1_tx)?0:$this->localtax1_tx) : "null") . ",";
662
-		$sql .= " localtax2_tx=" . (isset($this->localtax2_tx) ? (empty($this->localtax2_tx)?0:$this->localtax2_tx) : "null") . ",";
663
-		$sql .= " localtax1_type=" . (! empty($this->localtax1_type) ? "'".$this->db->escape($this->localtax1_type)."'": "'0'") . ",";
664
-		$sql .= " localtax2_type=" . (! empty($this->localtax2_type) ? "'".$this->db->escape($this->localtax2_type)."'": "'0'") . ",";
665
-		$sql .= " fk_user=" . $user->id . ",";
666
-		$sql .= " import_key=" . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . "";
667
-
668
-		$sql .= " WHERE rowid=" . $this->id;
669
-
670
-		dol_syslog(get_class($this) . "::update", LOG_DEBUG);
659
+		$sql .= " tva_tx=".(isset($this->tva_tx) ? (empty($this->tva_tx) ? 0 : $this->tva_tx) : "null").",";
660
+		$sql .= " recuperableonly=".(isset($this->recuperableonly) ? $this->recuperableonly : "null").",";
661
+		$sql .= " localtax1_tx=".(isset($this->localtax1_tx) ? (empty($this->localtax1_tx) ? 0 : $this->localtax1_tx) : "null").",";
662
+		$sql .= " localtax2_tx=".(isset($this->localtax2_tx) ? (empty($this->localtax2_tx) ? 0 : $this->localtax2_tx) : "null").",";
663
+		$sql .= " localtax1_type=".(!empty($this->localtax1_type) ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'").",";
664
+		$sql .= " localtax2_type=".(!empty($this->localtax2_type) ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'").",";
665
+		$sql .= " fk_user=".$user->id.",";
666
+		$sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
667
+
668
+		$sql .= " WHERE rowid=".$this->id;
669
+
670
+		dol_syslog(get_class($this)."::update", LOG_DEBUG);
671 671
 		$resql = $this->db->query($sql);
672
-		if (! $resql) {
673
-			$error ++;
674
-			$this->errors [] = "Error " . $this->db->lasterror();
672
+		if (!$resql) {
673
+			$error++;
674
+			$this->errors [] = "Error ".$this->db->lasterror();
675 675
 		}
676 676
 
677
-		if (! $error) {
678
-			if (! $notrigger) {
677
+		if (!$error) {
678
+			if (!$notrigger) {
679 679
 				// Call triggers
680
-				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
681
-				$interface=new Interfaces($this->db);
682
-				$result=$interface->run_triggers('PRODUCT_CUSTOMER_PRICE_UPDATE',$this,$user,$langs,$conf);
683
-				if ($result < 0) { $error++; $this->errors=$interface->errors; }
680
+				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
681
+				$interface = new Interfaces($this->db);
682
+				$result = $interface->run_triggers('PRODUCT_CUSTOMER_PRICE_UPDATE', $this, $user, $langs, $conf);
683
+				if ($result < 0) { $error++; $this->errors = $interface->errors; }
684 684
 				// End call triggers
685 685
 			}
686 686
 		}
687 687
 
688
-		if (! $error) {
688
+		if (!$error) {
689 689
 			$result = $this->setPriceOnAffiliateThirdparty($user, $forceupdateaffiliate);
690 690
 			if ($result < 0) {
691
-				$error ++;
691
+				$error++;
692 692
 			}
693 693
 		}
694 694
 
695 695
 		// Commit or rollback
696 696
 		if ($error) {
697
-			foreach ( $this->errors as $errmsg ) {
698
-				dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
699
-				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
697
+			foreach ($this->errors as $errmsg) {
698
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
699
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
700 700
 			}
701 701
 			$this->db->rollback();
702
-			return - 1 * $error;
702
+			return -1 * $error;
703 703
 		} else {
704 704
 			$this->db->commit();
705 705
 			return 1;
@@ -719,37 +719,37 @@  discard block
 block discarded – undo
719 719
 
720 720
 		// Find all susidiaries
721 721
 		$sql = "SELECT s.rowid";
722
-		$sql .= " FROM " . MAIN_DB_PREFIX . "societe as s";
723
-		$sql .= " WHERE s.parent = " . $this->fk_soc;
724
-		$sql .= " AND s.entity IN (" . getEntity('societe') . ")";
722
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
723
+		$sql .= " WHERE s.parent = ".$this->fk_soc;
724
+		$sql .= " AND s.entity IN (".getEntity('societe').")";
725 725
 
726
-		dol_syslog(get_class($this) . "::setPriceOnAffiliateThirdparty", LOG_DEBUG);
726
+		dol_syslog(get_class($this)."::setPriceOnAffiliateThirdparty", LOG_DEBUG);
727 727
 		$resql = $this->db->query($sql);
728 728
 
729 729
 		if ($resql) {
730 730
 
731
-			$this->lines = array ();
731
+			$this->lines = array();
732 732
 			$num = $this->db->num_rows($resql);
733 733
 
734
-			while ( ($obj = $this->db->fetch_object($resql)) && (empty($error)) ) {
734
+			while (($obj = $this->db->fetch_object($resql)) && (empty($error))) {
735 735
 
736 736
 				// find if there is an existing line for the product and the subsidiaries
737 737
 				$prodsocprice = new Productcustomerprice($this->db);
738 738
 
739
-				$filter = array (
740
-					't.fk_product' => $this->fk_product,'t.fk_soc' => $obj->rowid
739
+				$filter = array(
740
+					't.fk_product' => $this->fk_product, 't.fk_soc' => $obj->rowid
741 741
 				);
742 742
 
743 743
 				$result = $prodsocprice->fetch_all('', '', 0, 0, $filter);
744 744
 				if ($result < 0) {
745
-					$error ++;
745
+					$error++;
746 746
 					$this->error = $prodsocprice->error;
747 747
 				} else {
748 748
 
749 749
 					// There is one line
750 750
 					if (count($prodsocprice->lines) > 0) {
751 751
 						// If force update => Update
752
-						if (! empty($forceupdateaffiliate)) {
752
+						if (!empty($forceupdateaffiliate)) {
753 753
 
754 754
 							$prodsocpriceupd = new Productcustomerprice($this->db);
755 755
 							$prodsocpriceupd->fetch($prodsocprice->lines [0]->id);
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 
763 763
 							$resultupd = $prodsocpriceupd->update($user, 0, $forceupdateaffiliate);
764 764
 							if ($result < 0) {
765
-								$error ++;
765
+								$error++;
766 766
 								$this->error = $prodsocpriceupd->error;
767 767
 							}
768 768
 						}
@@ -779,7 +779,7 @@  discard block
 block discarded – undo
779 779
 
780 780
 						$resultupd = $prodsocpricenew->create($user, 0, $forceupdateaffiliate);
781 781
 						if ($result < 0) {
782
-							$error ++;
782
+							$error++;
783 783
 							$this->error = $prodsocpriceupd->error;
784 784
 						}
785 785
 					}
@@ -790,11 +790,11 @@  discard block
 block discarded – undo
790 790
 			if (empty($error)) {
791 791
 				return 1;
792 792
 			} else {
793
-				return - 1;
793
+				return -1;
794 794
 			}
795 795
 		} else {
796
-			$this->error = "Error " . $this->db->lasterror();
797
-			return - 1;
796
+			$this->error = "Error ".$this->db->lasterror();
797
+			return -1;
798 798
 		}
799 799
 	}
800 800
 
@@ -812,8 +812,8 @@  discard block
 block discarded – undo
812 812
 
813 813
 		$this->db->begin();
814 814
 
815
-		if (! $error) {
816
-			if (! $notrigger) {
815
+		if (!$error) {
816
+			if (!$notrigger) {
817 817
 				// Uncomment this and change MYOBJECT to your own tag if you
818 818
 				// want this action calls a trigger.
819 819
 
@@ -826,26 +826,26 @@  discard block
 block discarded – undo
826 826
 			}
827 827
 		}
828 828
 
829
-		if (! $error) {
830
-			$sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_customer_price";
831
-			$sql .= " WHERE rowid=" . $this->id;
829
+		if (!$error) {
830
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_customer_price";
831
+			$sql .= " WHERE rowid=".$this->id;
832 832
 
833
-			dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
833
+			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
834 834
 			$resql = $this->db->query($sql);
835
-			if (! $resql) {
836
-				$error ++;
837
-				$this->errors [] = "Error " . $this->db->lasterror();
835
+			if (!$resql) {
836
+				$error++;
837
+				$this->errors [] = "Error ".$this->db->lasterror();
838 838
 			}
839 839
 		}
840 840
 
841 841
 		// Commit or rollback
842 842
 		if ($error) {
843
-			foreach ( $this->errors as $errmsg ) {
844
-				dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
845
-				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
843
+			foreach ($this->errors as $errmsg) {
844
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
845
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
846 846
 			}
847 847
 			$this->db->rollback();
848
-			return - 1 * $error;
848
+			return -1 * $error;
849 849
 		} else {
850 850
 			$this->db->commit();
851 851
 			return 1;
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 
867 867
 		$object = new Productcustomerprice($this->db);
868 868
 
869
-		$object->context['createfromclone']='createfromclone';
869
+		$object->context['createfromclone'] = 'createfromclone';
870 870
 
871 871
 		$this->db->begin();
872 872
 
@@ -884,21 +884,21 @@  discard block
 block discarded – undo
884 884
 		// Other options
885 885
 		if ($result < 0) {
886 886
 			$this->error = $object->error;
887
-			$error ++;
887
+			$error++;
888 888
 		}
889 889
 
890
-		if (! $error) {
890
+		if (!$error) {
891 891
 		}
892 892
 
893 893
 		unset($object->context['createfromclone']);
894 894
 
895 895
 		// End
896
-		if (! $error) {
896
+		if (!$error) {
897 897
 			$this->db->commit();
898 898
 			return $object->id;
899 899
 		} else {
900 900
 			$this->db->rollback();
901
-			return - 1;
901
+			return -1;
902 902
 		}
903 903
 	}
904 904
 
Please login to merge, or discard this patch.
htdocs/product/class/propalmergepdfproduct.class.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -297,7 +297,7 @@
 block discarded – undo
297 297
     /**
298 298
      *  Update object into database
299 299
      *
300
-     *  @param	User	$user        User that modifies
300
+     *  @param	integer	$user        User that modifies
301 301
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
302 302
      *  @return int     		   	 <0 if KO, >0 if OK
303 303
      */
Please login to merge, or discard this patch.
Braces   +39 added lines, -27 removed lines patch added patch discarded remove patch
@@ -73,12 +73,24 @@  discard block
 block discarded – undo
73 73
 
74 74
 		// Clean parameters
75 75
         
76
-		if (isset($this->fk_product)) $this->fk_product=trim($this->fk_product);
77
-		if (isset($this->file_name)) $this->file_name=trim($this->file_name);
78
-		if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
79
-		if (isset($this->fk_user_mod)) $this->fk_user_mod=trim($this->fk_user_mod);
80
-		if (isset($this->lang)) $this->lang=trim($this->lang);
81
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
76
+		if (isset($this->fk_product)) {
77
+			$this->fk_product=trim($this->fk_product);
78
+		}
79
+		if (isset($this->file_name)) {
80
+			$this->file_name=trim($this->file_name);
81
+		}
82
+		if (isset($this->fk_user_author)) {
83
+			$this->fk_user_author=trim($this->fk_user_author);
84
+		}
85
+		if (isset($this->fk_user_mod)) {
86
+			$this->fk_user_mod=trim($this->fk_user_mod);
87
+		}
88
+		if (isset($this->lang)) {
89
+			$this->lang=trim($this->lang);
90
+		}
91
+		if (isset($this->import_key)) {
92
+			$this->import_key=trim($this->import_key);
93
+		}
82 94
 
83 95
         
84 96
 
@@ -146,8 +158,7 @@  discard block
 block discarded – undo
146 158
 			}
147 159
 			$this->db->rollback();
148 160
 			return -1*$error;
149
-		}
150
-		else
161
+		} else
151 162
 		{
152 163
 			$this->db->commit();
153 164
             return $this->id;
@@ -207,8 +218,7 @@  discard block
 block discarded – undo
207 218
             $this->db->free($resql);
208 219
 
209 220
             return 1;
210
-        }
211
-        else
221
+        } else
212 222
         {
213 223
       	    $this->error="Error ".$this->db->lasterror();
214 224
             dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
@@ -272,7 +282,7 @@  discard block
 block discarded – undo
272 282
 	    			
273 283
 	    			if ($conf->global->MAIN_MULTILANGS) {
274 284
 	    				$this->lines[$obj->file_name.'_'.$obj->lang]=$line;
275
-	    			}else {
285
+	    			} else {
276 286
 	    				$this->lines[$obj->file_name]=$line;
277 287
 	    			}
278 288
 	    			
@@ -284,8 +294,7 @@  discard block
 block discarded – undo
284 294
     		$this->db->free($resql);
285 295
     
286 296
     		return 1;
287
-    	}
288
-    	else
297
+    	} else
289 298
     	{
290 299
     		$this->error="Error ".$this->db->lasterror();
291 300
     		dol_syslog(get_class($this)."::fetch_by_product ".$this->error, LOG_ERR);
@@ -308,10 +317,18 @@  discard block
 block discarded – undo
308 317
 
309 318
 		// Clean parameters
310 319
         
311
-		if (isset($this->fk_product)) $this->fk_product=trim($this->fk_product);
312
-		if (isset($this->file_name)) $this->file_name=trim($this->file_name);
313
-		if (isset($this->fk_user_mod)) $this->fk_user_mod=trim($this->fk_user_mod);
314
-		if (isset($this->lang)) $this->lang=trim($this->lang);
320
+		if (isset($this->fk_product)) {
321
+			$this->fk_product=trim($this->fk_product);
322
+		}
323
+		if (isset($this->file_name)) {
324
+			$this->file_name=trim($this->file_name);
325
+		}
326
+		if (isset($this->fk_user_mod)) {
327
+			$this->fk_user_mod=trim($this->fk_user_mod);
328
+		}
329
+		if (isset($this->lang)) {
330
+			$this->lang=trim($this->lang);
331
+		}
315 332
 		
316 333
 
317 334
         
@@ -364,8 +381,7 @@  discard block
 block discarded – undo
364 381
 			}
365 382
 			$this->db->rollback();
366 383
 			return -1*$error;
367
-		}
368
-		else
384
+		} else
369 385
 		{
370 386
 			$this->db->commit();
371 387
 			return 1;
@@ -423,8 +439,7 @@  discard block
 block discarded – undo
423 439
 			}
424 440
 			$this->db->rollback();
425 441
 			return -1*$error;
426
-		}
427
-		else
442
+		} else
428 443
 		{
429 444
 			$this->db->commit();
430 445
 			return 1;
@@ -487,8 +502,7 @@  discard block
 block discarded – undo
487 502
 			}
488 503
 			$this->db->rollback();
489 504
 			return -1*$error;
490
-		}
491
-		else
505
+		} else
492 506
 		{
493 507
 			$this->db->commit();
494 508
 			return 1;
@@ -544,8 +558,7 @@  discard block
 block discarded – undo
544 558
 			}
545 559
 			$this->db->rollback();
546 560
 			return -1*$error;
547
-		}
548
-		else
561
+		} else
549 562
 		{
550 563
 			$this->db->commit();
551 564
 			return 1;
@@ -599,8 +612,7 @@  discard block
 block discarded – undo
599 612
 		{
600 613
 			$this->db->commit();
601 614
 			return $object->id;
602
-		}
603
-		else
615
+		} else
604 616
 		{
605 617
 			$this->db->rollback();
606 618
 			return -1;
Please login to merge, or discard this patch.
Indentation   +206 added lines, -206 removed lines patch added patch discarded remove patch
@@ -47,28 +47,28 @@  discard block
 block discarded – undo
47 47
 
48 48
 
49 49
 
50
-    /**
51
-     *  Constructor
52
-     *
53
-     *  @param	DoliDb		$db      Database handler
54
-     */
55
-    function __construct($db)
56
-    {
57
-        $this->db = $db;
58
-        return 1;
59
-    }
60
-
61
-
62
-    /**
63
-     *  Create object into database
64
-     *
65
-     *  @param	User	$user        User that creates
66
-     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
67
-     *  @return int      		   	 <0 if KO, Id of created object if OK
68
-     */
69
-    function create($user, $notrigger=0)
70
-    {
71
-    	global $conf, $langs;
50
+	/**
51
+	 *  Constructor
52
+	 *
53
+	 *  @param	DoliDb		$db      Database handler
54
+	 */
55
+	function __construct($db)
56
+	{
57
+		$this->db = $db;
58
+		return 1;
59
+	}
60
+
61
+
62
+	/**
63
+	 *  Create object into database
64
+	 *
65
+	 *  @param	User	$user        User that creates
66
+	 *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
67
+	 *  @return int      		   	 <0 if KO, Id of created object if OK
68
+	 */
69
+	function create($user, $notrigger=0)
70
+	{
71
+		global $conf, $langs;
72 72
 		$error=0;
73 73
 
74 74
 		// Clean parameters
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 		// Check parameters
86 86
 		// Put here code to add control on parameters values
87 87
 
88
-        // Insert request
88
+		// Insert request
89 89
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."propal_merge_pdf_product(";
90 90
 
91 91
 		$sql.= "fk_product,";
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 		$sql.= "datec";
99 99
 
100 100
 
101
-        $sql.= ") VALUES (";
101
+		$sql.= ") VALUES (";
102 102
 
103 103
 		$sql.= " ".(! isset($this->fk_product)?'NULL':"'".$this->db->escape($this->fk_product)."'").",";
104 104
 		$sql.= " ".(! isset($this->file_name)?'NULL':"'".$this->db->escape($this->file_name)."'").",";
@@ -115,34 +115,34 @@  discard block
 block discarded – undo
115 115
 		$this->db->begin();
116 116
 
117 117
 	   	dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
118
-        $resql=$this->db->query($sql);
119
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
118
+		$resql=$this->db->query($sql);
119
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
120 120
 
121 121
 		if (! $error)
122
-        {
123
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal_merge_pdf_product");
122
+		{
123
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal_merge_pdf_product");
124 124
 
125 125
 			if (! $notrigger)
126 126
 			{
127
-	            // Uncomment this and change MYOBJECT to your own tag if you
128
-	            // want this action calls a trigger.
129
-
130
-	            //// Call triggers
131
-	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
132
-	            //$interface=new Interfaces($this->db);
133
-	            //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
134
-	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
135
-	            //// End call triggers
127
+				// Uncomment this and change MYOBJECT to your own tag if you
128
+				// want this action calls a trigger.
129
+
130
+				//// Call triggers
131
+				//include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
132
+				//$interface=new Interfaces($this->db);
133
+				//$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
134
+				//if ($result < 0) { $error++; $this->errors=$interface->errors; }
135
+				//// End call triggers
136 136
 			}
137
-        }
137
+		}
138 138
 
139
-        // Commit or rollback
140
-        if ($error)
139
+		// Commit or rollback
140
+		if ($error)
141 141
 		{
142 142
 			foreach($this->errors as $errmsg)
143 143
 			{
144
-	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
145
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
144
+				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
145
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
146 146
 			}
147 147
 			$this->db->rollback();
148 148
 			return -1*$error;
@@ -150,22 +150,22 @@  discard block
 block discarded – undo
150 150
 		else
151 151
 		{
152 152
 			$this->db->commit();
153
-            return $this->id;
153
+			return $this->id;
154 154
 		}
155
-    }
155
+	}
156 156
 
157 157
 
158
-    /**
159
-     *  Load object in memory from the database
160
-     *
161
-     *  @param	int		$id    Id object
162
-     *  @return int          	<0 if KO, >0 if OK
163
-     */
164
-    function fetch($id)
165
-    {
166
-    	global $langs,$conf;
158
+	/**
159
+	 *  Load object in memory from the database
160
+	 *
161
+	 *  @param	int		$id    Id object
162
+	 *  @return int          	<0 if KO, >0 if OK
163
+	 */
164
+	function fetch($id)
165
+	{
166
+		global $langs,$conf;
167 167
 
168
-        $sql = "SELECT";
168
+		$sql = "SELECT";
169 169
 		$sql.= " t.rowid,";
170 170
 
171 171
 		$sql.= " t.fk_product,";
@@ -178,18 +178,18 @@  discard block
 block discarded – undo
178 178
 		$sql.= " t.import_key";
179 179
 
180 180
 
181
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
182
-        $sql.= " WHERE t.rowid = ".$id;
181
+		$sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
182
+		$sql.= " WHERE t.rowid = ".$id;
183 183
 
184
-    	dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
185
-        $resql=$this->db->query($sql);
186
-        if ($resql)
187
-        {
188
-            if ($this->db->num_rows($resql))
189
-            {
190
-                $obj = $this->db->fetch_object($resql);
184
+		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
185
+		$resql=$this->db->query($sql);
186
+		if ($resql)
187
+		{
188
+			if ($this->db->num_rows($resql))
189
+			{
190
+				$obj = $this->db->fetch_object($resql);
191 191
 
192
-                $this->id    = $obj->rowid;
192
+				$this->id    = $obj->rowid;
193 193
 
194 194
 				$this->fk_product = $obj->fk_product;
195 195
 				$this->file_name = $obj->file_name;
@@ -203,107 +203,107 @@  discard block
 block discarded – undo
203 203
 				$this->import_key = $obj->import_key;
204 204
 
205 205
 
206
-            }
207
-            $this->db->free($resql);
208
-
209
-            return 1;
210
-        }
211
-        else
212
-        {
213
-      	    $this->error="Error ".$this->db->lasterror();
214
-            dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
215
-            return -1;
216
-        }
217
-    }
218
-
219
-    /**
220
-     *  Load object in memory from the database
221
-     *
222
-     *  @param	int		$product_id    	Id object
223
-     *  @param	string	$lang  			Lang string code
224
-     *  @return int          	<0 if KO, >0 if OK
225
-     */
226
-    function fetch_by_product($product_id, $lang='')
227
-    {
228
-    	global $langs,$conf;
229
-
230
-    	$sql = "SELECT";
231
-    	$sql.= " t.rowid,";
232
-
233
-    	$sql.= " t.fk_product,";
234
-    	$sql.= " t.file_name,";
235
-    	$sql.= " t.lang,";
236
-    	$sql.= " t.fk_user_author,";
237
-    	$sql.= " t.fk_user_mod,";
238
-    	$sql.= " t.datec,";
239
-    	$sql.= " t.tms,";
240
-    	$sql.= " t.import_key";
241
-
242
-
243
-    	$sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
244
-    	$sql.= " WHERE t.fk_product = ".$product_id;
245
-    	if ($conf->global->MAIN_MULTILANGS && !empty($lang)) {
246
-    		$sql.= " AND t.lang = '".$lang."'";
247
-    	}
248
-
249
-    	dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
250
-    	$resql=$this->db->query($sql);
251
-    	if ($resql)
252
-    	{
253
-    		if ($this->db->num_rows($resql))
254
-    		{
255
-    			while($obj = $this->db->fetch_object($resql)) {
256
-
257
-    				$line = new PropalmergepdfproductLine();
258
-
259
-	    			$line->id    = $obj->rowid;
260
-
261
-	    			$line->fk_product = $obj->fk_product;
262
-	    			$line->file_name = $obj->file_name;
263
-	    			if ($conf->global->MAIN_MULTILANGS) {
264
-	    				$line->lang = $obj->lang;
265
-	    			}
266
-	    			$line->fk_user_author = $obj->fk_user_author;
267
-	    			$line->fk_user_mod = $obj->fk_user_mod;
268
-	    			$line->datec = $this->db->jdate($obj->datec);
269
-	    			$line->tms = $this->db->jdate($obj->tms);
270
-	    			$line->import_key = $obj->import_key;
271
-
272
-
273
-	    			if ($conf->global->MAIN_MULTILANGS) {
274
-	    				$this->lines[$obj->file_name.'_'.$obj->lang]=$line;
275
-	    			}else {
276
-	    				$this->lines[$obj->file_name]=$line;
277
-	    			}
278
-
279
-
280
-    			}
281
-
282
-
283
-    		}
284
-    		$this->db->free($resql);
285
-
286
-    		return 1;
287
-    	}
288
-    	else
289
-    	{
290
-    		$this->error="Error ".$this->db->lasterror();
291
-    		dol_syslog(get_class($this)."::fetch_by_product ".$this->error, LOG_ERR);
292
-    		return -1;
293
-    	}
294
-    }
295
-
296
-
297
-    /**
298
-     *  Update object into database
299
-     *
300
-     *  @param	User	$user        User that modifies
301
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
302
-     *  @return int     		   	 <0 if KO, >0 if OK
303
-     */
304
-    function update($user=0, $notrigger=0)
305
-    {
306
-    	global $conf, $langs;
206
+			}
207
+			$this->db->free($resql);
208
+
209
+			return 1;
210
+		}
211
+		else
212
+		{
213
+	  		$this->error="Error ".$this->db->lasterror();
214
+			dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
215
+			return -1;
216
+		}
217
+	}
218
+
219
+	/**
220
+	 *  Load object in memory from the database
221
+	 *
222
+	 *  @param	int		$product_id    	Id object
223
+	 *  @param	string	$lang  			Lang string code
224
+	 *  @return int          	<0 if KO, >0 if OK
225
+	 */
226
+	function fetch_by_product($product_id, $lang='')
227
+	{
228
+		global $langs,$conf;
229
+
230
+		$sql = "SELECT";
231
+		$sql.= " t.rowid,";
232
+
233
+		$sql.= " t.fk_product,";
234
+		$sql.= " t.file_name,";
235
+		$sql.= " t.lang,";
236
+		$sql.= " t.fk_user_author,";
237
+		$sql.= " t.fk_user_mod,";
238
+		$sql.= " t.datec,";
239
+		$sql.= " t.tms,";
240
+		$sql.= " t.import_key";
241
+
242
+
243
+		$sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
244
+		$sql.= " WHERE t.fk_product = ".$product_id;
245
+		if ($conf->global->MAIN_MULTILANGS && !empty($lang)) {
246
+			$sql.= " AND t.lang = '".$lang."'";
247
+		}
248
+
249
+		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
250
+		$resql=$this->db->query($sql);
251
+		if ($resql)
252
+		{
253
+			if ($this->db->num_rows($resql))
254
+			{
255
+				while($obj = $this->db->fetch_object($resql)) {
256
+
257
+					$line = new PropalmergepdfproductLine();
258
+
259
+					$line->id    = $obj->rowid;
260
+
261
+					$line->fk_product = $obj->fk_product;
262
+					$line->file_name = $obj->file_name;
263
+					if ($conf->global->MAIN_MULTILANGS) {
264
+						$line->lang = $obj->lang;
265
+					}
266
+					$line->fk_user_author = $obj->fk_user_author;
267
+					$line->fk_user_mod = $obj->fk_user_mod;
268
+					$line->datec = $this->db->jdate($obj->datec);
269
+					$line->tms = $this->db->jdate($obj->tms);
270
+					$line->import_key = $obj->import_key;
271
+
272
+
273
+					if ($conf->global->MAIN_MULTILANGS) {
274
+						$this->lines[$obj->file_name.'_'.$obj->lang]=$line;
275
+					}else {
276
+						$this->lines[$obj->file_name]=$line;
277
+					}
278
+
279
+
280
+				}
281
+
282
+
283
+			}
284
+			$this->db->free($resql);
285
+
286
+			return 1;
287
+		}
288
+		else
289
+		{
290
+			$this->error="Error ".$this->db->lasterror();
291
+			dol_syslog(get_class($this)."::fetch_by_product ".$this->error, LOG_ERR);
292
+			return -1;
293
+		}
294
+	}
295
+
296
+
297
+	/**
298
+	 *  Update object into database
299
+	 *
300
+	 *  @param	User	$user        User that modifies
301
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
302
+	 *  @return int     		   	 <0 if KO, >0 if OK
303
+	 */
304
+	function update($user=0, $notrigger=0)
305
+	{
306
+		global $conf, $langs;
307 307
 		$error=0;
308 308
 
309 309
 		// Clean parameters
@@ -319,8 +319,8 @@  discard block
 block discarded – undo
319 319
 		// Check parameters
320 320
 		// Put here code to add a control on parameters values
321 321
 
322
-        // Update request
323
-        $sql = "UPDATE ".MAIN_DB_PREFIX."propal_merge_pdf_product SET";
322
+		// Update request
323
+		$sql = "UPDATE ".MAIN_DB_PREFIX."propal_merge_pdf_product SET";
324 324
 
325 325
 		$sql.= " fk_product=".(isset($this->fk_product)?$this->fk_product:"null").",";
326 326
 		$sql.= " file_name=".(isset($this->file_name)?"'".$this->db->escape($this->file_name)."'":"null").",";
@@ -330,37 +330,37 @@  discard block
 block discarded – undo
330 330
 		$sql.= " fk_user_mod=".$user->id;
331 331
 
332 332
 
333
-        $sql.= " WHERE rowid=".$this->id;
333
+		$sql.= " WHERE rowid=".$this->id;
334 334
 
335 335
 		$this->db->begin();
336 336
 
337 337
 		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
338
-        $resql = $this->db->query($sql);
339
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
338
+		$resql = $this->db->query($sql);
339
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
340 340
 
341 341
 		if (! $error)
342 342
 		{
343 343
 			if (! $notrigger)
344 344
 			{
345
-	            // Uncomment this and change MYOBJECT to your own tag if you
346
-	            // want this action calls a trigger.
347
-
348
-	            //// Call triggers
349
-	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
350
-	            //$interface=new Interfaces($this->db);
351
-	            //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
352
-	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
353
-	            //// End call triggers
354
-	    	}
345
+				// Uncomment this and change MYOBJECT to your own tag if you
346
+				// want this action calls a trigger.
347
+
348
+				//// Call triggers
349
+				//include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
350
+				//$interface=new Interfaces($this->db);
351
+				//$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
352
+				//if ($result < 0) { $error++; $this->errors=$interface->errors; }
353
+				//// End call triggers
354
+			}
355 355
 		}
356 356
 
357
-        // Commit or rollback
357
+		// Commit or rollback
358 358
 		if ($error)
359 359
 		{
360 360
 			foreach($this->errors as $errmsg)
361 361
 			{
362
-	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
363
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
362
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
363
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
364 364
 			}
365 365
 			$this->db->rollback();
366 366
 			return -1*$error;
@@ -370,16 +370,16 @@  discard block
 block discarded – undo
370 370
 			$this->db->commit();
371 371
 			return 1;
372 372
 		}
373
-    }
373
+	}
374 374
 
375 375
 
376 376
  	/**
377
-	 *  Delete object in database
378
-	 *
379
-     *	@param  User	$user        User that deletes
380
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
381
-	 *  @return	int					 <0 if KO, >0 if OK
382
-	 */
377
+ 	 *  Delete object in database
378
+ 	 *
379
+ 	 *	@param  User	$user        User that deletes
380
+ 	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
381
+ 	 *  @return	int					 <0 if KO, >0 if OK
382
+ 	 */
383 383
 	function delete($user, $notrigger=0)
384 384
 	{
385 385
 		global $conf, $langs;
@@ -392,34 +392,34 @@  discard block
 block discarded – undo
392 392
 			if (! $notrigger)
393 393
 			{
394 394
 				// Uncomment this and change MYOBJECT to your own tag if you
395
-		        // want this action calls a trigger.
396
-
397
-		        //// Call triggers
398
-		        //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
399
-		        //$interface=new Interfaces($this->db);
400
-		        //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
401
-		        //if ($result < 0) { $error++; $this->errors=$interface->errors; }
402
-		        //// End call triggers
395
+				// want this action calls a trigger.
396
+
397
+				//// Call triggers
398
+				//include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
399
+				//$interface=new Interfaces($this->db);
400
+				//$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
401
+				//if ($result < 0) { $error++; $this->errors=$interface->errors; }
402
+				//// End call triggers
403 403
 			}
404 404
 		}
405 405
 
406 406
 		if (! $error)
407 407
 		{
408
-    		$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
409
-    		$sql.= " WHERE rowid=".$this->id;
408
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
409
+			$sql.= " WHERE rowid=".$this->id;
410 410
 
411
-    		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
412
-    		$resql = $this->db->query($sql);
413
-        	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
411
+			dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
412
+			$resql = $this->db->query($sql);
413
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
414 414
 		}
415 415
 
416
-        // Commit or rollback
416
+		// Commit or rollback
417 417
 		if ($error)
418 418
 		{
419 419
 			foreach($this->errors as $errmsg)
420 420
 			{
421
-	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
422
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
421
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
422
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
423 423
 			}
424 424
 			$this->db->rollback();
425 425
 			return -1*$error;
Please login to merge, or discard this patch.
Spacing   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -31,18 +31,18 @@  discard block
 block discarded – undo
31 31
  */
32 32
 class Propalmergepdfproduct extends CommonObject
33 33
 {
34
-	var $element='propal_merge_pdf_product';			//!< Id that identify managed objects
35
-	var $table_element='propal_merge_pdf_product';		//!< Name of table without prefix where object is stored
34
+	var $element = 'propal_merge_pdf_product'; //!< Id that identify managed objects
35
+	var $table_element = 'propal_merge_pdf_product'; //!< Name of table without prefix where object is stored
36 36
 
37 37
 	var $fk_product;
38 38
 	var $file_name;
39 39
 	var $fk_user_author;
40 40
 	var $fk_user_mod;
41
-	var $datec='';
42
-	var $tms='';
41
+	var $datec = '';
42
+	var $tms = '';
43 43
 	var $lang;
44 44
 
45
-	var $lines=array();
45
+	var $lines = array();
46 46
 
47 47
 
48 48
 
@@ -66,19 +66,19 @@  discard block
 block discarded – undo
66 66
      *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
67 67
      *  @return int      		   	 <0 if KO, Id of created object if OK
68 68
      */
69
-    function create($user, $notrigger=0)
69
+    function create($user, $notrigger = 0)
70 70
     {
71 71
     	global $conf, $langs;
72
-		$error=0;
72
+		$error = 0;
73 73
 
74 74
 		// Clean parameters
75 75
 
76
-		if (isset($this->fk_product)) $this->fk_product=trim($this->fk_product);
77
-		if (isset($this->file_name)) $this->file_name=trim($this->file_name);
78
-		if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
79
-		if (isset($this->fk_user_mod)) $this->fk_user_mod=trim($this->fk_user_mod);
80
-		if (isset($this->lang)) $this->lang=trim($this->lang);
81
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
76
+		if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product);
77
+		if (isset($this->file_name)) $this->file_name = trim($this->file_name);
78
+		if (isset($this->fk_user_author)) $this->fk_user_author = trim($this->fk_user_author);
79
+		if (isset($this->fk_user_mod)) $this->fk_user_mod = trim($this->fk_user_mod);
80
+		if (isset($this->lang)) $this->lang = trim($this->lang);
81
+		if (isset($this->import_key)) $this->import_key = trim($this->import_key);
82 82
 
83 83
 
84 84
 
@@ -88,41 +88,41 @@  discard block
 block discarded – undo
88 88
         // Insert request
89 89
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."propal_merge_pdf_product(";
90 90
 
91
-		$sql.= "fk_product,";
92
-		$sql.= "file_name,";
91
+		$sql .= "fk_product,";
92
+		$sql .= "file_name,";
93 93
 		if ($conf->global->MAIN_MULTILANGS) {
94
-			$sql.= "lang,";
94
+			$sql .= "lang,";
95 95
 		}
96
-		$sql.= "fk_user_author,";
97
-		$sql.= "fk_user_mod,";
98
-		$sql.= "datec";
96
+		$sql .= "fk_user_author,";
97
+		$sql .= "fk_user_mod,";
98
+		$sql .= "datec";
99 99
 
100 100
 
101
-        $sql.= ") VALUES (";
101
+        $sql .= ") VALUES (";
102 102
 
103
-		$sql.= " ".(! isset($this->fk_product)?'NULL':"'".$this->db->escape($this->fk_product)."'").",";
104
-		$sql.= " ".(! isset($this->file_name)?'NULL':"'".$this->db->escape($this->file_name)."'").",";
103
+		$sql .= " ".(!isset($this->fk_product) ? 'NULL' : "'".$this->db->escape($this->fk_product)."'").",";
104
+		$sql .= " ".(!isset($this->file_name) ? 'NULL' : "'".$this->db->escape($this->file_name)."'").",";
105 105
 		if ($conf->global->MAIN_MULTILANGS) {
106
-			$sql.= " ".(! isset($this->lang)?'NULL':"'".$this->db->escape($this->lang)."'").",";
106
+			$sql .= " ".(!isset($this->lang) ? 'NULL' : "'".$this->db->escape($this->lang)."'").",";
107 107
 		}
108
-		$sql.= " ".$user->id.",";
109
-		$sql.= " ".$user->id.",";
110
-		$sql.= " '".$this->db->idate(dol_now())."'";
108
+		$sql .= " ".$user->id.",";
109
+		$sql .= " ".$user->id.",";
110
+		$sql .= " '".$this->db->idate(dol_now())."'";
111 111
 
112 112
 
113
-		$sql.= ")";
113
+		$sql .= ")";
114 114
 
115 115
 		$this->db->begin();
116 116
 
117 117
 	   	dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
118
-        $resql=$this->db->query($sql);
119
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
118
+        $resql = $this->db->query($sql);
119
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
120 120
 
121
-		if (! $error)
121
+		if (!$error)
122 122
         {
123 123
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal_merge_pdf_product");
124 124
 
125
-			if (! $notrigger)
125
+			if (!$notrigger)
126 126
 			{
127 127
 	            // Uncomment this and change MYOBJECT to your own tag if you
128 128
 	            // want this action calls a trigger.
@@ -139,13 +139,13 @@  discard block
 block discarded – undo
139 139
         // Commit or rollback
140 140
         if ($error)
141 141
 		{
142
-			foreach($this->errors as $errmsg)
142
+			foreach ($this->errors as $errmsg)
143 143
 			{
144 144
 	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
145
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
145
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
146 146
 			}
147 147
 			$this->db->rollback();
148
-			return -1*$error;
148
+			return -1 * $error;
149 149
 		}
150 150
 		else
151 151
 		{
@@ -163,33 +163,33 @@  discard block
 block discarded – undo
163 163
      */
164 164
     function fetch($id)
165 165
     {
166
-    	global $langs,$conf;
166
+    	global $langs, $conf;
167 167
 
168 168
         $sql = "SELECT";
169
-		$sql.= " t.rowid,";
169
+		$sql .= " t.rowid,";
170 170
 
171
-		$sql.= " t.fk_product,";
172
-		$sql.= " t.file_name,";
173
-		$sql.= " t.lang,";
174
-		$sql.= " t.fk_user_author,";
175
-		$sql.= " t.fk_user_mod,";
176
-		$sql.= " t.datec,";
177
-		$sql.= " t.tms,";
178
-		$sql.= " t.import_key";
171
+		$sql .= " t.fk_product,";
172
+		$sql .= " t.file_name,";
173
+		$sql .= " t.lang,";
174
+		$sql .= " t.fk_user_author,";
175
+		$sql .= " t.fk_user_mod,";
176
+		$sql .= " t.datec,";
177
+		$sql .= " t.tms,";
178
+		$sql .= " t.import_key";
179 179
 
180 180
 
181
-        $sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
182
-        $sql.= " WHERE t.rowid = ".$id;
181
+        $sql .= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
182
+        $sql .= " WHERE t.rowid = ".$id;
183 183
 
184 184
     	dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
185
-        $resql=$this->db->query($sql);
185
+        $resql = $this->db->query($sql);
186 186
         if ($resql)
187 187
         {
188 188
             if ($this->db->num_rows($resql))
189 189
             {
190 190
                 $obj = $this->db->fetch_object($resql);
191 191
 
192
-                $this->id    = $obj->rowid;
192
+                $this->id = $obj->rowid;
193 193
 
194 194
 				$this->fk_product = $obj->fk_product;
195 195
 				$this->file_name = $obj->file_name;
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
         }
211 211
         else
212 212
         {
213
-      	    $this->error="Error ".$this->db->lasterror();
213
+      	    $this->error = "Error ".$this->db->lasterror();
214 214
             dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
215 215
             return -1;
216 216
         }
@@ -223,40 +223,40 @@  discard block
 block discarded – undo
223 223
      *  @param	string	$lang  			Lang string code
224 224
      *  @return int          	<0 if KO, >0 if OK
225 225
      */
226
-    function fetch_by_product($product_id, $lang='')
226
+    function fetch_by_product($product_id, $lang = '')
227 227
     {
228
-    	global $langs,$conf;
228
+    	global $langs, $conf;
229 229
 
230 230
     	$sql = "SELECT";
231
-    	$sql.= " t.rowid,";
231
+    	$sql .= " t.rowid,";
232 232
 
233
-    	$sql.= " t.fk_product,";
234
-    	$sql.= " t.file_name,";
235
-    	$sql.= " t.lang,";
236
-    	$sql.= " t.fk_user_author,";
237
-    	$sql.= " t.fk_user_mod,";
238
-    	$sql.= " t.datec,";
239
-    	$sql.= " t.tms,";
240
-    	$sql.= " t.import_key";
233
+    	$sql .= " t.fk_product,";
234
+    	$sql .= " t.file_name,";
235
+    	$sql .= " t.lang,";
236
+    	$sql .= " t.fk_user_author,";
237
+    	$sql .= " t.fk_user_mod,";
238
+    	$sql .= " t.datec,";
239
+    	$sql .= " t.tms,";
240
+    	$sql .= " t.import_key";
241 241
 
242 242
 
243
-    	$sql.= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
244
-    	$sql.= " WHERE t.fk_product = ".$product_id;
243
+    	$sql .= " FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product as t";
244
+    	$sql .= " WHERE t.fk_product = ".$product_id;
245 245
     	if ($conf->global->MAIN_MULTILANGS && !empty($lang)) {
246
-    		$sql.= " AND t.lang = '".$lang."'";
246
+    		$sql .= " AND t.lang = '".$lang."'";
247 247
     	}
248 248
 
249 249
     	dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
250
-    	$resql=$this->db->query($sql);
250
+    	$resql = $this->db->query($sql);
251 251
     	if ($resql)
252 252
     	{
253 253
     		if ($this->db->num_rows($resql))
254 254
     		{
255
-    			while($obj = $this->db->fetch_object($resql)) {
255
+    			while ($obj = $this->db->fetch_object($resql)) {
256 256
 
257 257
     				$line = new PropalmergepdfproductLine();
258 258
 
259
-	    			$line->id    = $obj->rowid;
259
+	    			$line->id = $obj->rowid;
260 260
 
261 261
 	    			$line->fk_product = $obj->fk_product;
262 262
 	    			$line->file_name = $obj->file_name;
@@ -271,9 +271,9 @@  discard block
 block discarded – undo
271 271
 
272 272
 
273 273
 	    			if ($conf->global->MAIN_MULTILANGS) {
274
-	    				$this->lines[$obj->file_name.'_'.$obj->lang]=$line;
275
-	    			}else {
276
-	    				$this->lines[$obj->file_name]=$line;
274
+	    				$this->lines[$obj->file_name.'_'.$obj->lang] = $line;
275
+	    			} else {
276
+	    				$this->lines[$obj->file_name] = $line;
277 277
 	    			}
278 278
 
279 279
 
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
     	}
288 288
     	else
289 289
     	{
290
-    		$this->error="Error ".$this->db->lasterror();
290
+    		$this->error = "Error ".$this->db->lasterror();
291 291
     		dol_syslog(get_class($this)."::fetch_by_product ".$this->error, LOG_ERR);
292 292
     		return -1;
293 293
     	}
@@ -301,17 +301,17 @@  discard block
 block discarded – undo
301 301
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
302 302
      *  @return int     		   	 <0 if KO, >0 if OK
303 303
      */
304
-    function update($user=0, $notrigger=0)
304
+    function update($user = 0, $notrigger = 0)
305 305
     {
306 306
     	global $conf, $langs;
307
-		$error=0;
307
+		$error = 0;
308 308
 
309 309
 		// Clean parameters
310 310
 
311
-		if (isset($this->fk_product)) $this->fk_product=trim($this->fk_product);
312
-		if (isset($this->file_name)) $this->file_name=trim($this->file_name);
313
-		if (isset($this->fk_user_mod)) $this->fk_user_mod=trim($this->fk_user_mod);
314
-		if (isset($this->lang)) $this->lang=trim($this->lang);
311
+		if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product);
312
+		if (isset($this->file_name)) $this->file_name = trim($this->file_name);
313
+		if (isset($this->fk_user_mod)) $this->fk_user_mod = trim($this->fk_user_mod);
314
+		if (isset($this->lang)) $this->lang = trim($this->lang);
315 315
 
316 316
 
317 317
 
@@ -322,25 +322,25 @@  discard block
 block discarded – undo
322 322
         // Update request
323 323
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal_merge_pdf_product SET";
324 324
 
325
-		$sql.= " fk_product=".(isset($this->fk_product)?$this->fk_product:"null").",";
326
-		$sql.= " file_name=".(isset($this->file_name)?"'".$this->db->escape($this->file_name)."'":"null").",";
325
+		$sql .= " fk_product=".(isset($this->fk_product) ? $this->fk_product : "null").",";
326
+		$sql .= " file_name=".(isset($this->file_name) ? "'".$this->db->escape($this->file_name)."'" : "null").",";
327 327
 		if ($conf->global->MAIN_MULTILANGS) {
328
-			$sql.= " lang=".(isset($this->lang)?"'".$this->db->escape($this->lang)."'":"null").",";
328
+			$sql .= " lang=".(isset($this->lang) ? "'".$this->db->escape($this->lang)."'" : "null").",";
329 329
 		}
330
-		$sql.= " fk_user_mod=".$user->id;
330
+		$sql .= " fk_user_mod=".$user->id;
331 331
 
332 332
 
333
-        $sql.= " WHERE rowid=".$this->id;
333
+        $sql .= " WHERE rowid=".$this->id;
334 334
 
335 335
 		$this->db->begin();
336 336
 
337 337
 		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
338 338
         $resql = $this->db->query($sql);
339
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
339
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
340 340
 
341
-		if (! $error)
341
+		if (!$error)
342 342
 		{
343
-			if (! $notrigger)
343
+			if (!$notrigger)
344 344
 			{
345 345
 	            // Uncomment this and change MYOBJECT to your own tag if you
346 346
 	            // want this action calls a trigger.
@@ -357,13 +357,13 @@  discard block
 block discarded – undo
357 357
         // Commit or rollback
358 358
 		if ($error)
359 359
 		{
360
-			foreach($this->errors as $errmsg)
360
+			foreach ($this->errors as $errmsg)
361 361
 			{
362 362
 	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
363
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
363
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
364 364
 			}
365 365
 			$this->db->rollback();
366
-			return -1*$error;
366
+			return -1 * $error;
367 367
 		}
368 368
 		else
369 369
 		{
@@ -380,16 +380,16 @@  discard block
 block discarded – undo
380 380
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
381 381
 	 *  @return	int					 <0 if KO, >0 if OK
382 382
 	 */
383
-	function delete($user, $notrigger=0)
383
+	function delete($user, $notrigger = 0)
384 384
 	{
385 385
 		global $conf, $langs;
386
-		$error=0;
386
+		$error = 0;
387 387
 
388 388
 		$this->db->begin();
389 389
 
390
-		if (! $error)
390
+		if (!$error)
391 391
 		{
392
-			if (! $notrigger)
392
+			if (!$notrigger)
393 393
 			{
394 394
 				// Uncomment this and change MYOBJECT to your own tag if you
395 395
 		        // want this action calls a trigger.
@@ -403,26 +403,26 @@  discard block
 block discarded – undo
403 403
 			}
404 404
 		}
405 405
 
406
-		if (! $error)
406
+		if (!$error)
407 407
 		{
408 408
     		$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
409
-    		$sql.= " WHERE rowid=".$this->id;
409
+    		$sql .= " WHERE rowid=".$this->id;
410 410
 
411 411
     		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
412 412
     		$resql = $this->db->query($sql);
413
-        	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
413
+        	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
414 414
 		}
415 415
 
416 416
         // Commit or rollback
417 417
 		if ($error)
418 418
 		{
419
-			foreach($this->errors as $errmsg)
419
+			foreach ($this->errors as $errmsg)
420 420
 			{
421 421
 	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
422
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
422
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
423 423
 			}
424 424
 			$this->db->rollback();
425
-			return -1*$error;
425
+			return -1 * $error;
426 426
 		}
427 427
 		else
428 428
 		{
@@ -440,16 +440,16 @@  discard block
 block discarded – undo
440 440
 	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
441 441
 	 *  @return	int					 <0 if KO, >0 if OK
442 442
 	 */
443
-	function delete_by_product($user, $product_id, $lang_id='',  $notrigger=0)
443
+	function delete_by_product($user, $product_id, $lang_id = '', $notrigger = 0)
444 444
 	{
445 445
 		global $conf, $langs;
446
-		$error=0;
446
+		$error = 0;
447 447
 
448 448
 		$this->db->begin();
449 449
 
450
-		if (! $error)
450
+		if (!$error)
451 451
 		{
452
-			if (! $notrigger)
452
+			if (!$notrigger)
453 453
 			{
454 454
 				// Uncomment this and change MYOBJECT to your own tag if you
455 455
 				// want this action calls a trigger.
@@ -463,30 +463,30 @@  discard block
 block discarded – undo
463 463
 			}
464 464
 		}
465 465
 
466
-		if (! $error)
466
+		if (!$error)
467 467
 		{
468 468
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
469
-			$sql.= " WHERE fk_product=".$product_id;
469
+			$sql .= " WHERE fk_product=".$product_id;
470 470
 
471 471
 			if ($conf->global->MAIN_MULTILANGS && !empty($lang_id)) {
472
-				$sql.= " AND lang='".$lang_id."'";
472
+				$sql .= " AND lang='".$lang_id."'";
473 473
 			}
474 474
 
475 475
 			dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
476 476
 			$resql = $this->db->query($sql);
477
-			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
477
+			if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
478 478
 		}
479 479
 
480 480
 		// Commit or rollback
481 481
 		if ($error)
482 482
 		{
483
-			foreach($this->errors as $errmsg)
483
+			foreach ($this->errors as $errmsg)
484 484
 			{
485 485
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
486
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
486
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
487 487
 			}
488 488
 			$this->db->rollback();
489
-			return -1*$error;
489
+			return -1 * $error;
490 490
 		}
491 491
 		else
492 492
 		{
@@ -504,13 +504,13 @@  discard block
 block discarded – undo
504 504
 	function delete_by_file($user)
505 505
 	{
506 506
 		global $conf, $langs;
507
-		$error=0;
507
+		$error = 0;
508 508
 
509 509
 		$this->db->begin();
510 510
 
511
-		if (! $error)
511
+		if (!$error)
512 512
 		{
513
-			if (! $notrigger)
513
+			if (!$notrigger)
514 514
 			{
515 515
 				// Uncomment this and change MYOBJECT to your own tag if you
516 516
 				// want this action calls a trigger.
@@ -524,26 +524,26 @@  discard block
 block discarded – undo
524 524
 			}
525 525
 		}
526 526
 
527
-		if (! $error)
527
+		if (!$error)
528 528
 		{
529 529
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
530
-			$sql.= " WHERE fk_product=".$this->fk_product." AND file_name='".$this->db->escape($this->file_name)."'";
530
+			$sql .= " WHERE fk_product=".$this->fk_product." AND file_name='".$this->db->escape($this->file_name)."'";
531 531
 
532 532
 			dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
533 533
 			$resql = $this->db->query($sql);
534
-			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
534
+			if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
535 535
 		}
536 536
 
537 537
 		// Commit or rollback
538 538
 		if ($error)
539 539
 		{
540
-			foreach($this->errors as $errmsg)
540
+			foreach ($this->errors as $errmsg)
541 541
 			{
542 542
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
543
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
543
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
544 544
 			}
545 545
 			$this->db->rollback();
546
-			return -1*$error;
546
+			return -1 * $error;
547 547
 		}
548 548
 		else
549 549
 		{
@@ -562,40 +562,40 @@  discard block
 block discarded – undo
562 562
 	 */
563 563
 	function createFromClone($fromid)
564 564
 	{
565
-		global $user,$langs;
565
+		global $user, $langs;
566 566
 
567
-		$error=0;
567
+		$error = 0;
568 568
 
569
-		$object=new Propalmergepdfproduct($this->db);
569
+		$object = new Propalmergepdfproduct($this->db);
570 570
 
571 571
 		$this->db->begin();
572 572
 
573 573
 		// Load source object
574 574
 		$object->fetch($fromid);
575
-		$object->id=0;
576
-		$object->statut=0;
575
+		$object->id = 0;
576
+		$object->statut = 0;
577 577
 
578 578
 		// Clear fields
579 579
 		// ...
580 580
 
581 581
 		// Create clone
582
-		$result=$object->create($user);
582
+		$result = $object->create($user);
583 583
 
584 584
 		// Other options
585 585
 		if ($result < 0)
586 586
 		{
587
-			$this->error=$object->error;
587
+			$this->error = $object->error;
588 588
 			$error++;
589 589
 		}
590 590
 
591
-		if (! $error)
591
+		if (!$error)
592 592
 		{
593 593
 
594 594
 
595 595
 		}
596 596
 
597 597
 		// End
598
-		if (! $error)
598
+		if (!$error)
599 599
 		{
600 600
 			$this->db->commit();
601 601
 			return $object->id;
@@ -616,15 +616,15 @@  discard block
 block discarded – undo
616 616
 	 */
617 617
 	function initAsSpecimen()
618 618
 	{
619
-		$this->id=0;
619
+		$this->id = 0;
620 620
 
621
-		$this->fk_product='';
622
-		$this->file_name='';
623
-		$this->fk_user_author='';
624
-		$this->fk_user_mod='';
625
-		$this->datec='';
626
-		$this->tms='';
627
-		$this->import_key='';
621
+		$this->fk_product = '';
622
+		$this->file_name = '';
623
+		$this->fk_user_author = '';
624
+		$this->fk_user_mod = '';
625
+		$this->datec = '';
626
+		$this->tms = '';
627
+		$this->import_key = '';
628 628
 
629 629
 
630 630
 	}
@@ -643,8 +643,8 @@  discard block
 block discarded – undo
643 643
 	var $lang;
644 644
 	var $fk_user_author;
645 645
 	var $fk_user_mod;
646
-	var $datec='';
647
-	var $tms='';
646
+	var $datec = '';
647
+	var $tms = '';
648 648
 	var $import_key;
649 649
 
650 650
 	function __construct() {
Please login to merge, or discard this patch.
htdocs/product/dynamic_price/class/price_global_variable_updater.class.php 4 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
     /**
169 169
      *  Update object into database
170 170
      *
171
-     *  @param	User	$user        User that modifies
171
+     *  @param	integer	$user        User that modifies
172 172
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
173 173
      *  @return int     		   	 <0 if KO, >0 if OK
174 174
      */
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
      *  Update next_update into database
540 540
      *
541 541
      *  @param	string	$next_update Next update to write
542
-     *  @param	User	$user        User that modifies
542
+     *  @param	integer	$user        User that modifies
543 543
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
544 544
      *  @return int     		   	 <0 if KO, >0 if OK
545 545
      */
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
      *  Update last_status into database
584 584
      *
585 585
      *  @param	string	$last_status Status to write
586
-     *  @param	User	$user        User that modifies
586
+     *  @param	integer	$user        User that modifies
587 587
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
588 588
      *  @return int     		   	 <0 if KO, >0 if OK
589 589
      */
Please login to merge, or discard this patch.
Indentation   +587 added lines, -587 removed lines patch added patch discarded remove patch
@@ -29,591 +29,591 @@
 block discarded – undo
29 29
  */
30 30
 class PriceGlobalVariableUpdater
31 31
 {
32
-    var $db;							//!< To store db handler
33
-    var $error;							//!< To return error code (or message)
34
-    var $errors=array();				//!< To return several error codes (or messages)
35
-    var $types=array(0, 1);				//!< Updater types
36
-    var $update_min = 5;				//!< Minimal update rate
37
-    var $id;
38
-    var $type;
39
-    var $description;
40
-    var $parameters;
41
-    var $fk_variable;
42
-    var $update_interval;				//!< Interval in mins
43
-    var $next_update;					//!< Next update timestamp
44
-    var $last_status;
45
-    public $table_element = "c_price_global_variable_updater";
46
-
47
-    /**
48
-     *  Constructor
49
-     *
50
-     *  @param	DoliDb		$db      Database handler
51
-     */
52
-    function __construct($db)
53
-    {
54
-        $this->db = $db;
55
-        return 1;
56
-    }
57
-
58
-
59
-    /**
60
-     *  Create object into database
61
-     *
62
-     *  @param	User	$user        User that creates
63
-     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
64
-     *  @return int      		   	 <0 if KO, Id of created object if OK
65
-     */
66
-    function create($user, $notrigger=0)
67
-    {
68
-        $error=0;
69
-
70
-        $this->checkParameters();
71
-
72
-        // Insert request
73
-        $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
74
-        $sql.= "type, description, parameters, fk_variable, update_interval, next_update, last_status";
75
-        $sql.= ") VALUES (";
76
-        $sql.= " ".$this->type.",";
77
-        $sql.= " ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
78
-        $sql.= " ".(isset($this->parameters)?"'".$this->db->escape($this->parameters)."'":"''").",";
79
-        $sql.= " ".$this->fk_variable.",";
80
-        $sql.= " ".$this->update_interval.",";
81
-        $sql.= " ".$this->next_update.",";
82
-        $sql.= " ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
83
-        $sql.= ")";
84
-
85
-        $this->db->begin();
86
-
87
-        dol_syslog(get_class($this)."::create", LOG_DEBUG);
88
-        $resql=$this->db->query($sql);
89
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
90
-
91
-        if (! $error)
92
-        {
93
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
94
-
95
-            if (! $notrigger)
96
-            {
97
-                // Uncomment this and change MYOBJECT to your own tag if you
98
-                // want this action calls a trigger.
99
-
100
-                //// Call triggers
101
-                //$result=$this->call_trigger('MYOBJECT_CREATE',$user);
102
-                //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
103
-                //// End call triggers
104
-            }
105
-        }
106
-
107
-        // Commit or rollback
108
-        if ($error)
109
-        {
110
-            foreach($this->errors as $errmsg)
111
-            {
112
-                dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
113
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
114
-            }
115
-            $this->db->rollback();
116
-            return -1*$error;
117
-        }
118
-        else
119
-        {
120
-            $this->db->commit();
121
-            return $this->id;
122
-        }
123
-    }
124
-
125
-
126
-    /**
127
-     *  Load object in memory from the database
128
-     *
129
-     *  @param		int		$id    	Id object
130
-     *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 if OK
131
-     */
132
-    function fetch($id)
133
-    {
134
-        $sql = "SELECT type, description, parameters, fk_variable, update_interval, next_update, last_status";
135
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
136
-        $sql.= " WHERE rowid = ".$id;
137
-
138
-        dol_syslog(get_class($this)."::fetch");
139
-        $resql=$this->db->query($sql);
140
-        if ($resql)
141
-        {
142
-            $obj = $this->db->fetch_object($resql);
143
-            if ($obj)
144
-            {
145
-                $this->id				= $id;
146
-                $this->type				= $obj->type;
147
-                $this->description		= $obj->description;
148
-                $this->parameters		= $obj->parameters;
149
-                $this->fk_variable		= $obj->fk_variable;
150
-                $this->update_interval	= $obj->update_interval;
151
-                $this->next_update		= $obj->next_update;
152
-                $this->last_status		= $obj->last_status;
153
-                $this->checkParameters();
154
-                return 1;
155
-            }
156
-            else
157
-            {
158
-                return 0;
159
-            }
160
-        }
161
-        else
162
-        {
163
-            $this->error="Error ".$this->db->lasterror();
164
-            return -1;
165
-        }
166
-    }
167
-
168
-    /**
169
-     *  Update object into database
170
-     *
171
-     *  @param	User	$user        User that modifies
172
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
173
-     *  @return int     		   	 <0 if KO, >0 if OK
174
-     */
175
-    function update($user=0, $notrigger=0)
176
-    {
177
-        $error=0;
178
-
179
-        $this->checkParameters();
180
-
181
-        // Update request
182
-        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
183
-        $sql.= " type = ".$this->type.",";
184
-        $sql.= " description = ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
185
-        $sql.= " parameters = ".(isset($this->parameters)?"'".$this->db->escape($this->parameters)."'":"''").",";
186
-        $sql.= " fk_variable = ".$this->fk_variable.",";
187
-        $sql.= " update_interval = ".$this->update_interval.",";
188
-        $sql.= " next_update = ".$this->next_update.",";
189
-        $sql.= " last_status = ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
190
-        $sql.= " WHERE rowid = ".$this->id;
191
-
192
-        $this->db->begin();
193
-
194
-        dol_syslog(get_class($this)."::update");
195
-        $resql = $this->db->query($sql);
196
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
197
-
198
-        if (! $error)
199
-        {
200
-            if (! $notrigger)
201
-            {
202
-                // Uncomment this and change MYOBJECT to your own tag if you
203
-                // want this action calls a trigger.
204
-
205
-                //// Call triggers
206
-                //$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
207
-                //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
208
-                //// End call triggers
209
-             }
210
-        }
211
-
212
-        // Commit or rollback
213
-        if ($error)
214
-        {
215
-            foreach($this->errors as $errmsg)
216
-            {
217
-                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
218
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
219
-            }
220
-            $this->db->rollback();
221
-            return -1*$error;
222
-        }
223
-        else
224
-        {
225
-            $this->db->commit();
226
-            return 1;
227
-        }
228
-    }
229
-
230
-    /**
231
-     *  Delete object in database
232
-     *
233
-     * 	@param	int		$rowid		 Row id of global variable
234
-     *	@param  User	$user        User that deletes
235
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
236
-     *  @return	int					 <0 if KO, >0 if OK
237
-     */
238
-    function delete($rowid, $user, $notrigger=0)
239
-    {
240
-        $error=0;
241
-
242
-        $this->db->begin();
243
-
244
-        if (! $error)
245
-        {
246
-            if (! $notrigger)
247
-            {
248
-                // Uncomment this and change MYOBJECT to your own tag if you
249
-                // want this action calls a trigger.
250
-
251
-                //// Call triggers
252
-                //$result=$this->call_trigger('MYOBJECT_DELETE',$user);
253
-                //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
254
-                //// End call triggers
255
-            }
256
-        }
257
-
258
-        if (! $error)
259
-        {
260
-            $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
261
-            $sql.= " WHERE rowid = ".$rowid;
262
-
263
-            dol_syslog(get_class($this)."::delete");
264
-            $resql = $this->db->query($sql);
265
-            if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
266
-        }
267
-
268
-        // Commit or rollback
269
-        if ($error)
270
-        {
271
-            foreach($this->errors as $errmsg)
272
-            {
273
-                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
274
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
275
-            }
276
-            $this->db->rollback();
277
-            return -1*$error;
278
-        }
279
-        else
280
-        {
281
-            $this->db->commit();
282
-            return 1;
283
-        }
284
-    }
285
-
286
-    /**
287
-     *	Initialise object with example values
288
-     *	Id must be 0 if object instance is a specimen
289
-     *
290
-     *	@return	void
291
-     */
292
-    function initAsSpecimen()
293
-    {
294
-        $this->id=0;
295
-        $this->type=0;
296
-        $this->description='';
297
-        $this->parameters='';
298
-        $this->fk_variable=0;
299
-        $this->update_interval=0;
300
-        $this->next_update=0;
301
-        $this->last_status='';
302
-    }
303
-
304
-    /**
305
-     *	Returns the last updated time in string html format, returns "never" if its less than 1
306
-     *
307
-     *	@return	string
308
-     */
309
-    function getLastUpdated()
310
-    {
311
-        global $langs;
312
-        $last = $this->next_update - ($this->update_interval * 60);
313
-        if ($last < 1) {
314
-            return $langs->trans("Never");
315
-        }
316
-        $status = empty($this->last_status) ? $langs->trans("CorrectlyUpdated") : $this->last_status;
317
-        return $status.'<br>'.dol_print_date($last, '%d/%m/%Y %H:%M:%S');
318
-    }
319
-
320
-    /**
321
-     *	Checks if all parameters are in order
322
-     *
323
-     *	@return	void
324
-     */
325
-    function checkParameters()
326
-    {
327
-        // Clean parameters
328
-        if (isset($this->description)) $this->description=trim($this->description);
329
-        if (isset($this->parameters)) $this->parameters=trim($this->parameters);
330
-        else $this->parameters="";
331
-        if (isset($this->last_status)) $this->last_status=trim($this->last_status);
332
-
333
-        // Check parameters
334
-        if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type=0;
335
-        if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval=$this->update_min;
336
-        if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update=0;
337
-    }
338
-
339
-    /**
340
-     *  List all price global variables
341
-     *
342
-     *  @return	array				Array of price global variable updaters
343
-     */
344
-    function listUpdaters()
345
-    {
346
-        $sql = "SELECT rowid, type, description, parameters, fk_variable, update_interval, next_update, last_status";
347
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
348
-
349
-        dol_syslog(get_class($this)."::listUpdaters");
350
-        $resql=$this->db->query($sql);
351
-        if ($resql)
352
-        {
353
-            $retarray = array();
354
-
355
-            while ($record = $this->db->fetch_array($resql))
356
-            {
357
-                $updater_obj = new PriceGlobalVariableUpdater($this->db);
358
-                $updater_obj->id				= $record["rowid"];
359
-                $updater_obj->type				= $record["type"];
360
-                $updater_obj->description		= $record["description"];
361
-                $updater_obj->parameters		= $record["parameters"];
362
-                $updater_obj->fk_variable		= $record["fk_variable"];
363
-                $updater_obj->update_interval	= $record["update_interval"];
364
-                $updater_obj->next_update		= $record["next_update"];
365
-                $updater_obj->last_status		= $record["last_status"];
366
-                $updater_obj->checkParameters();
367
-                $retarray[]=$updater_obj;
368
-            }
369
-
370
-            $this->db->free($resql);
371
-            return $retarray;
372
-        }
373
-        else
374
-        {
375
-            $this->error=$this->db->error();
376
-            return -1;
377
-        }
378
-    }
379
-
380
-    /**
381
-     *  List all updaters which need to be processed
382
-     *
383
-     *  @return	array				Array of price global variable updaters
384
-     */
385
-    function listPendingUpdaters()
386
-    {
387
-        $sql = "SELECT rowid, type, description, parameters, fk_variable, update_interval, next_update, last_status";
388
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
389
-        $sql.= " WHERE next_update < ".dol_now();
390
-
391
-        dol_syslog(get_class($this)."::processUpdaters");
392
-        $resql=$this->db->query($sql);
393
-        if ($resql)
394
-        {
395
-            $retarray = array();
396
-
397
-            while ($record = $this->db->fetch_array($resql))
398
-            {
399
-                $updater_obj = new PriceGlobalVariableUpdater($this->db);
400
-                $updater_obj->id				= $record["rowid"];
401
-                $updater_obj->type				= $record["type"];
402
-                $updater_obj->description		= $record["description"];
403
-                $updater_obj->parameters		= $record["parameters"];
404
-                $updater_obj->fk_variable		= $record["fk_variable"];
405
-                $updater_obj->update_interval	= $record["update_interval"];
406
-                $updater_obj->next_update		= $record["next_update"];
407
-                $updater_obj->last_status		= $record["last_status"];
408
-                $updater_obj->checkParameters();
409
-                $retarray[]=$updater_obj;
410
-            }
411
-
412
-            $this->db->free($resql);
413
-            return $retarray;
414
-        }
415
-        else
416
-        {
417
-            $this->error=$this->db->error();
418
-            return -1;
419
-        }
420
-    }
421
-
422
-    /**
423
-     *	Handles the processing of this updater
424
-     *
425
-     *  @return	int					 <0 if KO, 0 if OK but no global variable found, >0 if OK
426
-     */
427
-    function process()
428
-    {
429
-        global $langs, $user;
430
-        $langs->load("errors");
431
-
432
-        $this->error = null;
433
-        $this->checkParameters();
434
-
435
-        //Try to load the target global variable and abort if fails
436
-        if ($this->fk_variable < 1) {
437
-            $this->error = $langs->trans("ErrorGlobalVariableUpdater5");
438
-            return 0;
439
-        }
440
-        $price_globals = new PriceGlobalVariable($this->db);
441
-        $res = $price_globals->fetch($this->fk_variable);
442
-        if ($res < 1) {
443
-            $this->error = $langs->trans("ErrorGlobalVariableUpdater5");
444
-            return 0;
445
-        }
446
-
447
-        //Process depending of type
448
-        if ($this->type == 0 || $this->type == 1) {
449
-            //Get and check if required parameters are present
450
-            $parameters = json_decode($this->parameters, true);
451
-            if (!isset($parameters)) {
452
-                $this->error = $langs->trans("ErrorGlobalVariableUpdater1", $this->parameters);
453
-                return -1;
454
-            }
455
-            $url = $parameters['URL'];
456
-            if (!isset($url)) {
457
-                $this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'URL');
458
-                return -1;
459
-            }
460
-            $value = $parameters['VALUE'];
461
-            if (!isset($value)) {
462
-                $this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'VALUE');
463
-                return -1;
464
-            }
465
-            $result = "";
466
-            if ($this->type == 0) {
467
-                // Call JSON request
468
-                include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
469
-                $tmpresult=getURLContent($url);
470
-                $code=$tmpresult['http_code'];
471
-                $result=$tmpresult['content'];
472
-
473
-                if (!isset($result)) {
474
-                    $this->error = $langs->trans("ErrorGlobalVariableUpdater0", "empty response");
475
-                    return -1;
476
-                }
477
-                if ($code !== 200) {
478
-                    $this->error = $langs->trans("ErrorGlobalVariableUpdater0", $code.' '.$tmpresult['curl_error_msg']);
479
-                    return -1;
480
-                }
481
-
482
-                //Decode returned response
483
-                $result = json_decode($result, true);
484
-            } elseif ($this->type == 1) {
485
-                $ns = $parameters['NS'];
486
-                if (!isset($ns)) {
487
-                    $this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'NS');
488
-                    return -1;
489
-                }
490
-                $method = $parameters['METHOD'];
491
-                if (!isset($method)) {
492
-                    $this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'METHOD');
493
-                    return -1;
494
-                }
495
-                $data = $parameters['DATA'];
496
-                if (!isset($data)) {
497
-                    $this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'DATA');
498
-                    return -1;
499
-                }
500
-
501
-                //SOAP client
502
-                require_once NUSOAP_PATH.'/nusoap.php';
503
-                $soap_client = new nusoap_client($url);
504
-                $soap_client->soap_defencoding='UTF-8';
505
-                $soap_client->decodeUTF8(false);
506
-                $result = $soap_client->call($method, $data, $ns,'');
507
-
508
-                //Check if result is a error
509
-                if ($result === false) {
510
-                    $this->error = $langs->trans("ErrorGlobalVariableUpdater4", $soap_client->error_str);
511
-                    return -1;
512
-                }
513
-            }
514
-
515
-            //Explode value and walk for each key in value array to get the relevant key
516
-            $value = explode(',', $value);
517
-            foreach ($value as $key) {
518
-                $result = $result[$key];
519
-            }
520
-            if (!isset($result)) {
521
-                $this->error = $langs->trans("ErrorGlobalVariableUpdater3");
522
-                return -1;
523
-            }
524
-
525
-            //Save data to global and update it
526
-            $price_globals->value = $result;
527
-            $price_globals->update($user);
528
-        }
529
-        return 1;
530
-    }
531
-
532
-    /**
533
-     *  Update next_update into database
534
-     *
535
-     *  @param	string	$next_update Next update to write
536
-     *  @param	User	$user        User that modifies
537
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
538
-     *  @return int     		   	 <0 if KO, >0 if OK
539
-     */
540
-    function update_next_update($next_update, $user=0, $notrigger=0)
541
-    {
542
-        $error=0;
543
-
544
-        $this->next_update = $next_update;
545
-        $this->checkParameters();
546
-
547
-        // Update request
548
-        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
549
-        $sql.= " next_update = ".$this->next_update;
550
-        $sql.= " WHERE rowid = ".$this->id;
551
-
552
-        $this->db->begin();
553
-
554
-        dol_syslog(get_class($this)."::update_next_update");
555
-        $resql = $this->db->query($sql);
556
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
557
-
558
-        // Commit or rollback
559
-        if ($error)
560
-        {
561
-            foreach($this->errors as $errmsg)
562
-            {
563
-                dol_syslog(get_class($this)."::update_next_update ".$errmsg, LOG_ERR);
564
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
565
-            }
566
-            $this->db->rollback();
567
-            return -1*$error;
568
-        }
569
-        else
570
-        {
571
-            $this->db->commit();
572
-            return 1;
573
-        }
574
-    }
575
-
576
-    /**
577
-     *  Update last_status into database
578
-     *
579
-     *  @param	string	$last_status Status to write
580
-     *  @param	User	$user        User that modifies
581
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
582
-     *  @return int     		   	 <0 if KO, >0 if OK
583
-     */
584
-    function update_status($last_status, $user=0, $notrigger=0)
585
-    {
586
-        $error=0;
587
-
588
-        $this->last_status = $last_status;
589
-        $this->checkParameters();
590
-
591
-        // Update request
592
-        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
593
-        $sql.= " last_status = ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
594
-        $sql.= " WHERE rowid = ".$this->id;
595
-
596
-        $this->db->begin();
597
-
598
-        dol_syslog(get_class($this)."::update_status");
599
-        $resql = $this->db->query($sql);
600
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
601
-
602
-        // Commit or rollback
603
-        if ($error)
604
-        {
605
-            foreach($this->errors as $errmsg)
606
-            {
607
-                dol_syslog(get_class($this)."::update_status ".$errmsg, LOG_ERR);
608
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
609
-            }
610
-            $this->db->rollback();
611
-            return -1*$error;
612
-        }
613
-        else
614
-        {
615
-            $this->db->commit();
616
-            return 1;
617
-        }
618
-    }
32
+	var $db;							//!< To store db handler
33
+	var $error;							//!< To return error code (or message)
34
+	var $errors=array();				//!< To return several error codes (or messages)
35
+	var $types=array(0, 1);				//!< Updater types
36
+	var $update_min = 5;				//!< Minimal update rate
37
+	var $id;
38
+	var $type;
39
+	var $description;
40
+	var $parameters;
41
+	var $fk_variable;
42
+	var $update_interval;				//!< Interval in mins
43
+	var $next_update;					//!< Next update timestamp
44
+	var $last_status;
45
+	public $table_element = "c_price_global_variable_updater";
46
+
47
+	/**
48
+	 *  Constructor
49
+	 *
50
+	 *  @param	DoliDb		$db      Database handler
51
+	 */
52
+	function __construct($db)
53
+	{
54
+		$this->db = $db;
55
+		return 1;
56
+	}
57
+
58
+
59
+	/**
60
+	 *  Create object into database
61
+	 *
62
+	 *  @param	User	$user        User that creates
63
+	 *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
64
+	 *  @return int      		   	 <0 if KO, Id of created object if OK
65
+	 */
66
+	function create($user, $notrigger=0)
67
+	{
68
+		$error=0;
69
+
70
+		$this->checkParameters();
71
+
72
+		// Insert request
73
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
74
+		$sql.= "type, description, parameters, fk_variable, update_interval, next_update, last_status";
75
+		$sql.= ") VALUES (";
76
+		$sql.= " ".$this->type.",";
77
+		$sql.= " ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
78
+		$sql.= " ".(isset($this->parameters)?"'".$this->db->escape($this->parameters)."'":"''").",";
79
+		$sql.= " ".$this->fk_variable.",";
80
+		$sql.= " ".$this->update_interval.",";
81
+		$sql.= " ".$this->next_update.",";
82
+		$sql.= " ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
83
+		$sql.= ")";
84
+
85
+		$this->db->begin();
86
+
87
+		dol_syslog(get_class($this)."::create", LOG_DEBUG);
88
+		$resql=$this->db->query($sql);
89
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
90
+
91
+		if (! $error)
92
+		{
93
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
94
+
95
+			if (! $notrigger)
96
+			{
97
+				// Uncomment this and change MYOBJECT to your own tag if you
98
+				// want this action calls a trigger.
99
+
100
+				//// Call triggers
101
+				//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
102
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
103
+				//// End call triggers
104
+			}
105
+		}
106
+
107
+		// Commit or rollback
108
+		if ($error)
109
+		{
110
+			foreach($this->errors as $errmsg)
111
+			{
112
+				dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
113
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
114
+			}
115
+			$this->db->rollback();
116
+			return -1*$error;
117
+		}
118
+		else
119
+		{
120
+			$this->db->commit();
121
+			return $this->id;
122
+		}
123
+	}
124
+
125
+
126
+	/**
127
+	 *  Load object in memory from the database
128
+	 *
129
+	 *  @param		int		$id    	Id object
130
+	 *  @return		int			    < 0 if KO, 0 if OK but not found, > 0 if OK
131
+	 */
132
+	function fetch($id)
133
+	{
134
+		$sql = "SELECT type, description, parameters, fk_variable, update_interval, next_update, last_status";
135
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
136
+		$sql.= " WHERE rowid = ".$id;
137
+
138
+		dol_syslog(get_class($this)."::fetch");
139
+		$resql=$this->db->query($sql);
140
+		if ($resql)
141
+		{
142
+			$obj = $this->db->fetch_object($resql);
143
+			if ($obj)
144
+			{
145
+				$this->id				= $id;
146
+				$this->type				= $obj->type;
147
+				$this->description		= $obj->description;
148
+				$this->parameters		= $obj->parameters;
149
+				$this->fk_variable		= $obj->fk_variable;
150
+				$this->update_interval	= $obj->update_interval;
151
+				$this->next_update		= $obj->next_update;
152
+				$this->last_status		= $obj->last_status;
153
+				$this->checkParameters();
154
+				return 1;
155
+			}
156
+			else
157
+			{
158
+				return 0;
159
+			}
160
+		}
161
+		else
162
+		{
163
+			$this->error="Error ".$this->db->lasterror();
164
+			return -1;
165
+		}
166
+	}
167
+
168
+	/**
169
+	 *  Update object into database
170
+	 *
171
+	 *  @param	User	$user        User that modifies
172
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
173
+	 *  @return int     		   	 <0 if KO, >0 if OK
174
+	 */
175
+	function update($user=0, $notrigger=0)
176
+	{
177
+		$error=0;
178
+
179
+		$this->checkParameters();
180
+
181
+		// Update request
182
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
183
+		$sql.= " type = ".$this->type.",";
184
+		$sql.= " description = ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
185
+		$sql.= " parameters = ".(isset($this->parameters)?"'".$this->db->escape($this->parameters)."'":"''").",";
186
+		$sql.= " fk_variable = ".$this->fk_variable.",";
187
+		$sql.= " update_interval = ".$this->update_interval.",";
188
+		$sql.= " next_update = ".$this->next_update.",";
189
+		$sql.= " last_status = ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
190
+		$sql.= " WHERE rowid = ".$this->id;
191
+
192
+		$this->db->begin();
193
+
194
+		dol_syslog(get_class($this)."::update");
195
+		$resql = $this->db->query($sql);
196
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
197
+
198
+		if (! $error)
199
+		{
200
+			if (! $notrigger)
201
+			{
202
+				// Uncomment this and change MYOBJECT to your own tag if you
203
+				// want this action calls a trigger.
204
+
205
+				//// Call triggers
206
+				//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
207
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
208
+				//// End call triggers
209
+			 }
210
+		}
211
+
212
+		// Commit or rollback
213
+		if ($error)
214
+		{
215
+			foreach($this->errors as $errmsg)
216
+			{
217
+				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
218
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
219
+			}
220
+			$this->db->rollback();
221
+			return -1*$error;
222
+		}
223
+		else
224
+		{
225
+			$this->db->commit();
226
+			return 1;
227
+		}
228
+	}
229
+
230
+	/**
231
+	 *  Delete object in database
232
+	 *
233
+	 * 	@param	int		$rowid		 Row id of global variable
234
+	 *	@param  User	$user        User that deletes
235
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
236
+	 *  @return	int					 <0 if KO, >0 if OK
237
+	 */
238
+	function delete($rowid, $user, $notrigger=0)
239
+	{
240
+		$error=0;
241
+
242
+		$this->db->begin();
243
+
244
+		if (! $error)
245
+		{
246
+			if (! $notrigger)
247
+			{
248
+				// Uncomment this and change MYOBJECT to your own tag if you
249
+				// want this action calls a trigger.
250
+
251
+				//// Call triggers
252
+				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
253
+				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
254
+				//// End call triggers
255
+			}
256
+		}
257
+
258
+		if (! $error)
259
+		{
260
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
261
+			$sql.= " WHERE rowid = ".$rowid;
262
+
263
+			dol_syslog(get_class($this)."::delete");
264
+			$resql = $this->db->query($sql);
265
+			if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
266
+		}
267
+
268
+		// Commit or rollback
269
+		if ($error)
270
+		{
271
+			foreach($this->errors as $errmsg)
272
+			{
273
+				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
274
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
275
+			}
276
+			$this->db->rollback();
277
+			return -1*$error;
278
+		}
279
+		else
280
+		{
281
+			$this->db->commit();
282
+			return 1;
283
+		}
284
+	}
285
+
286
+	/**
287
+	 *	Initialise object with example values
288
+	 *	Id must be 0 if object instance is a specimen
289
+	 *
290
+	 *	@return	void
291
+	 */
292
+	function initAsSpecimen()
293
+	{
294
+		$this->id=0;
295
+		$this->type=0;
296
+		$this->description='';
297
+		$this->parameters='';
298
+		$this->fk_variable=0;
299
+		$this->update_interval=0;
300
+		$this->next_update=0;
301
+		$this->last_status='';
302
+	}
303
+
304
+	/**
305
+	 *	Returns the last updated time in string html format, returns "never" if its less than 1
306
+	 *
307
+	 *	@return	string
308
+	 */
309
+	function getLastUpdated()
310
+	{
311
+		global $langs;
312
+		$last = $this->next_update - ($this->update_interval * 60);
313
+		if ($last < 1) {
314
+			return $langs->trans("Never");
315
+		}
316
+		$status = empty($this->last_status) ? $langs->trans("CorrectlyUpdated") : $this->last_status;
317
+		return $status.'<br>'.dol_print_date($last, '%d/%m/%Y %H:%M:%S');
318
+	}
319
+
320
+	/**
321
+	 *	Checks if all parameters are in order
322
+	 *
323
+	 *	@return	void
324
+	 */
325
+	function checkParameters()
326
+	{
327
+		// Clean parameters
328
+		if (isset($this->description)) $this->description=trim($this->description);
329
+		if (isset($this->parameters)) $this->parameters=trim($this->parameters);
330
+		else $this->parameters="";
331
+		if (isset($this->last_status)) $this->last_status=trim($this->last_status);
332
+
333
+		// Check parameters
334
+		if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type=0;
335
+		if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval=$this->update_min;
336
+		if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update=0;
337
+	}
338
+
339
+	/**
340
+	 *  List all price global variables
341
+	 *
342
+	 *  @return	array				Array of price global variable updaters
343
+	 */
344
+	function listUpdaters()
345
+	{
346
+		$sql = "SELECT rowid, type, description, parameters, fk_variable, update_interval, next_update, last_status";
347
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
348
+
349
+		dol_syslog(get_class($this)."::listUpdaters");
350
+		$resql=$this->db->query($sql);
351
+		if ($resql)
352
+		{
353
+			$retarray = array();
354
+
355
+			while ($record = $this->db->fetch_array($resql))
356
+			{
357
+				$updater_obj = new PriceGlobalVariableUpdater($this->db);
358
+				$updater_obj->id				= $record["rowid"];
359
+				$updater_obj->type				= $record["type"];
360
+				$updater_obj->description		= $record["description"];
361
+				$updater_obj->parameters		= $record["parameters"];
362
+				$updater_obj->fk_variable		= $record["fk_variable"];
363
+				$updater_obj->update_interval	= $record["update_interval"];
364
+				$updater_obj->next_update		= $record["next_update"];
365
+				$updater_obj->last_status		= $record["last_status"];
366
+				$updater_obj->checkParameters();
367
+				$retarray[]=$updater_obj;
368
+			}
369
+
370
+			$this->db->free($resql);
371
+			return $retarray;
372
+		}
373
+		else
374
+		{
375
+			$this->error=$this->db->error();
376
+			return -1;
377
+		}
378
+	}
379
+
380
+	/**
381
+	 *  List all updaters which need to be processed
382
+	 *
383
+	 *  @return	array				Array of price global variable updaters
384
+	 */
385
+	function listPendingUpdaters()
386
+	{
387
+		$sql = "SELECT rowid, type, description, parameters, fk_variable, update_interval, next_update, last_status";
388
+		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
389
+		$sql.= " WHERE next_update < ".dol_now();
390
+
391
+		dol_syslog(get_class($this)."::processUpdaters");
392
+		$resql=$this->db->query($sql);
393
+		if ($resql)
394
+		{
395
+			$retarray = array();
396
+
397
+			while ($record = $this->db->fetch_array($resql))
398
+			{
399
+				$updater_obj = new PriceGlobalVariableUpdater($this->db);
400
+				$updater_obj->id				= $record["rowid"];
401
+				$updater_obj->type				= $record["type"];
402
+				$updater_obj->description		= $record["description"];
403
+				$updater_obj->parameters		= $record["parameters"];
404
+				$updater_obj->fk_variable		= $record["fk_variable"];
405
+				$updater_obj->update_interval	= $record["update_interval"];
406
+				$updater_obj->next_update		= $record["next_update"];
407
+				$updater_obj->last_status		= $record["last_status"];
408
+				$updater_obj->checkParameters();
409
+				$retarray[]=$updater_obj;
410
+			}
411
+
412
+			$this->db->free($resql);
413
+			return $retarray;
414
+		}
415
+		else
416
+		{
417
+			$this->error=$this->db->error();
418
+			return -1;
419
+		}
420
+	}
421
+
422
+	/**
423
+	 *	Handles the processing of this updater
424
+	 *
425
+	 *  @return	int					 <0 if KO, 0 if OK but no global variable found, >0 if OK
426
+	 */
427
+	function process()
428
+	{
429
+		global $langs, $user;
430
+		$langs->load("errors");
431
+
432
+		$this->error = null;
433
+		$this->checkParameters();
434
+
435
+		//Try to load the target global variable and abort if fails
436
+		if ($this->fk_variable < 1) {
437
+			$this->error = $langs->trans("ErrorGlobalVariableUpdater5");
438
+			return 0;
439
+		}
440
+		$price_globals = new PriceGlobalVariable($this->db);
441
+		$res = $price_globals->fetch($this->fk_variable);
442
+		if ($res < 1) {
443
+			$this->error = $langs->trans("ErrorGlobalVariableUpdater5");
444
+			return 0;
445
+		}
446
+
447
+		//Process depending of type
448
+		if ($this->type == 0 || $this->type == 1) {
449
+			//Get and check if required parameters are present
450
+			$parameters = json_decode($this->parameters, true);
451
+			if (!isset($parameters)) {
452
+				$this->error = $langs->trans("ErrorGlobalVariableUpdater1", $this->parameters);
453
+				return -1;
454
+			}
455
+			$url = $parameters['URL'];
456
+			if (!isset($url)) {
457
+				$this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'URL');
458
+				return -1;
459
+			}
460
+			$value = $parameters['VALUE'];
461
+			if (!isset($value)) {
462
+				$this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'VALUE');
463
+				return -1;
464
+			}
465
+			$result = "";
466
+			if ($this->type == 0) {
467
+				// Call JSON request
468
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
469
+				$tmpresult=getURLContent($url);
470
+				$code=$tmpresult['http_code'];
471
+				$result=$tmpresult['content'];
472
+
473
+				if (!isset($result)) {
474
+					$this->error = $langs->trans("ErrorGlobalVariableUpdater0", "empty response");
475
+					return -1;
476
+				}
477
+				if ($code !== 200) {
478
+					$this->error = $langs->trans("ErrorGlobalVariableUpdater0", $code.' '.$tmpresult['curl_error_msg']);
479
+					return -1;
480
+				}
481
+
482
+				//Decode returned response
483
+				$result = json_decode($result, true);
484
+			} elseif ($this->type == 1) {
485
+				$ns = $parameters['NS'];
486
+				if (!isset($ns)) {
487
+					$this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'NS');
488
+					return -1;
489
+				}
490
+				$method = $parameters['METHOD'];
491
+				if (!isset($method)) {
492
+					$this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'METHOD');
493
+					return -1;
494
+				}
495
+				$data = $parameters['DATA'];
496
+				if (!isset($data)) {
497
+					$this->error = $langs->trans("ErrorGlobalVariableUpdater2", 'DATA');
498
+					return -1;
499
+				}
500
+
501
+				//SOAP client
502
+				require_once NUSOAP_PATH.'/nusoap.php';
503
+				$soap_client = new nusoap_client($url);
504
+				$soap_client->soap_defencoding='UTF-8';
505
+				$soap_client->decodeUTF8(false);
506
+				$result = $soap_client->call($method, $data, $ns,'');
507
+
508
+				//Check if result is a error
509
+				if ($result === false) {
510
+					$this->error = $langs->trans("ErrorGlobalVariableUpdater4", $soap_client->error_str);
511
+					return -1;
512
+				}
513
+			}
514
+
515
+			//Explode value and walk for each key in value array to get the relevant key
516
+			$value = explode(',', $value);
517
+			foreach ($value as $key) {
518
+				$result = $result[$key];
519
+			}
520
+			if (!isset($result)) {
521
+				$this->error = $langs->trans("ErrorGlobalVariableUpdater3");
522
+				return -1;
523
+			}
524
+
525
+			//Save data to global and update it
526
+			$price_globals->value = $result;
527
+			$price_globals->update($user);
528
+		}
529
+		return 1;
530
+	}
531
+
532
+	/**
533
+	 *  Update next_update into database
534
+	 *
535
+	 *  @param	string	$next_update Next update to write
536
+	 *  @param	User	$user        User that modifies
537
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
538
+	 *  @return int     		   	 <0 if KO, >0 if OK
539
+	 */
540
+	function update_next_update($next_update, $user=0, $notrigger=0)
541
+	{
542
+		$error=0;
543
+
544
+		$this->next_update = $next_update;
545
+		$this->checkParameters();
546
+
547
+		// Update request
548
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
549
+		$sql.= " next_update = ".$this->next_update;
550
+		$sql.= " WHERE rowid = ".$this->id;
551
+
552
+		$this->db->begin();
553
+
554
+		dol_syslog(get_class($this)."::update_next_update");
555
+		$resql = $this->db->query($sql);
556
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
557
+
558
+		// Commit or rollback
559
+		if ($error)
560
+		{
561
+			foreach($this->errors as $errmsg)
562
+			{
563
+				dol_syslog(get_class($this)."::update_next_update ".$errmsg, LOG_ERR);
564
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
565
+			}
566
+			$this->db->rollback();
567
+			return -1*$error;
568
+		}
569
+		else
570
+		{
571
+			$this->db->commit();
572
+			return 1;
573
+		}
574
+	}
575
+
576
+	/**
577
+	 *  Update last_status into database
578
+	 *
579
+	 *  @param	string	$last_status Status to write
580
+	 *  @param	User	$user        User that modifies
581
+	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
582
+	 *  @return int     		   	 <0 if KO, >0 if OK
583
+	 */
584
+	function update_status($last_status, $user=0, $notrigger=0)
585
+	{
586
+		$error=0;
587
+
588
+		$this->last_status = $last_status;
589
+		$this->checkParameters();
590
+
591
+		// Update request
592
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
593
+		$sql.= " last_status = ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
594
+		$sql.= " WHERE rowid = ".$this->id;
595
+
596
+		$this->db->begin();
597
+
598
+		dol_syslog(get_class($this)."::update_status");
599
+		$resql = $this->db->query($sql);
600
+		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
601
+
602
+		// Commit or rollback
603
+		if ($error)
604
+		{
605
+			foreach($this->errors as $errmsg)
606
+			{
607
+				dol_syslog(get_class($this)."::update_status ".$errmsg, LOG_ERR);
608
+				$this->error.=($this->error?', '.$errmsg:$errmsg);
609
+			}
610
+			$this->db->rollback();
611
+			return -1*$error;
612
+		}
613
+		else
614
+		{
615
+			$this->db->commit();
616
+			return 1;
617
+		}
618
+	}
619 619
 }
Please login to merge, or discard this patch.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -29,18 +29,18 @@  discard block
 block discarded – undo
29 29
  */
30 30
 class PriceGlobalVariableUpdater
31 31
 {
32
-    var $db;							//!< To store db handler
33
-    var $error;							//!< To return error code (or message)
34
-    var $errors=array();				//!< To return several error codes (or messages)
35
-    var $types=array(0, 1);				//!< Updater types
36
-    var $update_min = 5;				//!< Minimal update rate
32
+    var $db; //!< To store db handler
33
+    var $error; //!< To return error code (or message)
34
+    var $errors = array(); //!< To return several error codes (or messages)
35
+    var $types = array(0, 1); //!< Updater types
36
+    var $update_min = 5; //!< Minimal update rate
37 37
     var $id;
38 38
     var $type;
39 39
     var $description;
40 40
     var $parameters;
41 41
     var $fk_variable;
42
-    var $update_interval;				//!< Interval in mins
43
-    var $next_update;					//!< Next update timestamp
42
+    var $update_interval; //!< Interval in mins
43
+    var $next_update; //!< Next update timestamp
44 44
     var $last_status;
45 45
     public $table_element = "c_price_global_variable_updater";
46 46
 
@@ -63,36 +63,36 @@  discard block
 block discarded – undo
63 63
      *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
64 64
      *  @return int      		   	 <0 if KO, Id of created object if OK
65 65
      */
66
-    function create($user, $notrigger=0)
66
+    function create($user, $notrigger = 0)
67 67
     {
68
-        $error=0;
68
+        $error = 0;
69 69
 
70 70
         $this->checkParameters();
71 71
 
72 72
         // Insert request
73 73
         $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
74
-        $sql.= "type, description, parameters, fk_variable, update_interval, next_update, last_status";
75
-        $sql.= ") VALUES (";
76
-        $sql.= " ".$this->type.",";
77
-        $sql.= " ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
78
-        $sql.= " ".(isset($this->parameters)?"'".$this->db->escape($this->parameters)."'":"''").",";
79
-        $sql.= " ".$this->fk_variable.",";
80
-        $sql.= " ".$this->update_interval.",";
81
-        $sql.= " ".$this->next_update.",";
82
-        $sql.= " ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
83
-        $sql.= ")";
74
+        $sql .= "type, description, parameters, fk_variable, update_interval, next_update, last_status";
75
+        $sql .= ") VALUES (";
76
+        $sql .= " ".$this->type.",";
77
+        $sql .= " ".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "''").",";
78
+        $sql .= " ".(isset($this->parameters) ? "'".$this->db->escape($this->parameters)."'" : "''").",";
79
+        $sql .= " ".$this->fk_variable.",";
80
+        $sql .= " ".$this->update_interval.",";
81
+        $sql .= " ".$this->next_update.",";
82
+        $sql .= " ".(isset($this->last_status) ? "'".$this->db->escape($this->last_status)."'" : "''");
83
+        $sql .= ")";
84 84
 
85 85
         $this->db->begin();
86 86
 
87 87
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
88
-        $resql=$this->db->query($sql);
89
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
88
+        $resql = $this->db->query($sql);
89
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
90 90
 
91
-        if (! $error)
91
+        if (!$error)
92 92
         {
93 93
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
94 94
 
95
-            if (! $notrigger)
95
+            if (!$notrigger)
96 96
             {
97 97
                 // Uncomment this and change MYOBJECT to your own tag if you
98 98
                 // want this action calls a trigger.
@@ -107,13 +107,13 @@  discard block
 block discarded – undo
107 107
         // Commit or rollback
108 108
         if ($error)
109 109
         {
110
-            foreach($this->errors as $errmsg)
110
+            foreach ($this->errors as $errmsg)
111 111
             {
112 112
                 dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
113
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
113
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
114 114
             }
115 115
             $this->db->rollback();
116
-            return -1*$error;
116
+            return -1 * $error;
117 117
         }
118 118
         else
119 119
         {
@@ -132,22 +132,22 @@  discard block
 block discarded – undo
132 132
     function fetch($id)
133 133
     {
134 134
         $sql = "SELECT type, description, parameters, fk_variable, update_interval, next_update, last_status";
135
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
136
-        $sql.= " WHERE rowid = ".$id;
135
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
136
+        $sql .= " WHERE rowid = ".$id;
137 137
 
138 138
         dol_syslog(get_class($this)."::fetch");
139
-        $resql=$this->db->query($sql);
139
+        $resql = $this->db->query($sql);
140 140
         if ($resql)
141 141
         {
142 142
             $obj = $this->db->fetch_object($resql);
143 143
             if ($obj)
144 144
             {
145
-                $this->id				= $id;
146
-                $this->type				= $obj->type;
145
+                $this->id = $id;
146
+                $this->type = $obj->type;
147 147
                 $this->description		= $obj->description;
148
-                $this->parameters		= $obj->parameters;
148
+                $this->parameters = $obj->parameters;
149 149
                 $this->fk_variable		= $obj->fk_variable;
150
-                $this->update_interval	= $obj->update_interval;
150
+                $this->update_interval = $obj->update_interval;
151 151
                 $this->next_update		= $obj->next_update;
152 152
                 $this->last_status		= $obj->last_status;
153 153
                 $this->checkParameters();
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
         }
161 161
         else
162 162
         {
163
-            $this->error="Error ".$this->db->lasterror();
163
+            $this->error = "Error ".$this->db->lasterror();
164 164
             return -1;
165 165
         }
166 166
     }
@@ -172,32 +172,32 @@  discard block
 block discarded – undo
172 172
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
173 173
      *  @return int     		   	 <0 if KO, >0 if OK
174 174
      */
175
-    function update($user=0, $notrigger=0)
175
+    function update($user = 0, $notrigger = 0)
176 176
     {
177
-        $error=0;
177
+        $error = 0;
178 178
 
179 179
         $this->checkParameters();
180 180
 
181 181
         // Update request
182 182
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
183
-        $sql.= " type = ".$this->type.",";
184
-        $sql.= " description = ".(isset($this->description)?"'".$this->db->escape($this->description)."'":"''").",";
185
-        $sql.= " parameters = ".(isset($this->parameters)?"'".$this->db->escape($this->parameters)."'":"''").",";
186
-        $sql.= " fk_variable = ".$this->fk_variable.",";
187
-        $sql.= " update_interval = ".$this->update_interval.",";
188
-        $sql.= " next_update = ".$this->next_update.",";
189
-        $sql.= " last_status = ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
190
-        $sql.= " WHERE rowid = ".$this->id;
183
+        $sql .= " type = ".$this->type.",";
184
+        $sql .= " description = ".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "''").",";
185
+        $sql .= " parameters = ".(isset($this->parameters) ? "'".$this->db->escape($this->parameters)."'" : "''").",";
186
+        $sql .= " fk_variable = ".$this->fk_variable.",";
187
+        $sql .= " update_interval = ".$this->update_interval.",";
188
+        $sql .= " next_update = ".$this->next_update.",";
189
+        $sql .= " last_status = ".(isset($this->last_status) ? "'".$this->db->escape($this->last_status)."'" : "''");
190
+        $sql .= " WHERE rowid = ".$this->id;
191 191
 
192 192
         $this->db->begin();
193 193
 
194 194
         dol_syslog(get_class($this)."::update");
195 195
         $resql = $this->db->query($sql);
196
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
196
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
197 197
 
198
-        if (! $error)
198
+        if (!$error)
199 199
         {
200
-            if (! $notrigger)
200
+            if (!$notrigger)
201 201
             {
202 202
                 // Uncomment this and change MYOBJECT to your own tag if you
203 203
                 // want this action calls a trigger.
@@ -212,13 +212,13 @@  discard block
 block discarded – undo
212 212
         // Commit or rollback
213 213
         if ($error)
214 214
         {
215
-            foreach($this->errors as $errmsg)
215
+            foreach ($this->errors as $errmsg)
216 216
             {
217 217
                 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
218
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
218
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
219 219
             }
220 220
             $this->db->rollback();
221
-            return -1*$error;
221
+            return -1 * $error;
222 222
         }
223 223
         else
224 224
         {
@@ -235,15 +235,15 @@  discard block
 block discarded – undo
235 235
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
236 236
      *  @return	int					 <0 if KO, >0 if OK
237 237
      */
238
-    function delete($rowid, $user, $notrigger=0)
238
+    function delete($rowid, $user, $notrigger = 0)
239 239
     {
240
-        $error=0;
240
+        $error = 0;
241 241
 
242 242
         $this->db->begin();
243 243
 
244
-        if (! $error)
244
+        if (!$error)
245 245
         {
246
-            if (! $notrigger)
246
+            if (!$notrigger)
247 247
             {
248 248
                 // Uncomment this and change MYOBJECT to your own tag if you
249 249
                 // want this action calls a trigger.
@@ -255,26 +255,26 @@  discard block
 block discarded – undo
255 255
             }
256 256
         }
257 257
 
258
-        if (! $error)
258
+        if (!$error)
259 259
         {
260 260
             $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
261
-            $sql.= " WHERE rowid = ".$rowid;
261
+            $sql .= " WHERE rowid = ".$rowid;
262 262
 
263 263
             dol_syslog(get_class($this)."::delete");
264 264
             $resql = $this->db->query($sql);
265
-            if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
265
+            if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
266 266
         }
267 267
 
268 268
         // Commit or rollback
269 269
         if ($error)
270 270
         {
271
-            foreach($this->errors as $errmsg)
271
+            foreach ($this->errors as $errmsg)
272 272
             {
273 273
                 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
274
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
274
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
275 275
             }
276 276
             $this->db->rollback();
277
-            return -1*$error;
277
+            return -1 * $error;
278 278
         }
279 279
         else
280 280
         {
@@ -291,14 +291,14 @@  discard block
 block discarded – undo
291 291
      */
292 292
     function initAsSpecimen()
293 293
     {
294
-        $this->id=0;
295
-        $this->type=0;
296
-        $this->description='';
297
-        $this->parameters='';
298
-        $this->fk_variable=0;
299
-        $this->update_interval=0;
300
-        $this->next_update=0;
301
-        $this->last_status='';
294
+        $this->id = 0;
295
+        $this->type = 0;
296
+        $this->description = '';
297
+        $this->parameters = '';
298
+        $this->fk_variable = 0;
299
+        $this->update_interval = 0;
300
+        $this->next_update = 0;
301
+        $this->last_status = '';
302 302
     }
303 303
 
304 304
     /**
@@ -325,15 +325,15 @@  discard block
 block discarded – undo
325 325
     function checkParameters()
326 326
     {
327 327
         // Clean parameters
328
-        if (isset($this->description)) $this->description=trim($this->description);
329
-        if (isset($this->parameters)) $this->parameters=trim($this->parameters);
330
-        else $this->parameters="";
331
-        if (isset($this->last_status)) $this->last_status=trim($this->last_status);
328
+        if (isset($this->description)) $this->description = trim($this->description);
329
+        if (isset($this->parameters)) $this->parameters = trim($this->parameters);
330
+        else $this->parameters = "";
331
+        if (isset($this->last_status)) $this->last_status = trim($this->last_status);
332 332
 
333 333
         // Check parameters
334
-        if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type=0;
335
-        if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval=$this->update_min;
336
-        if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update=0;
334
+        if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type = 0;
335
+        if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval = $this->update_min;
336
+        if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update = 0;
337 337
     }
338 338
 
339 339
     /**
@@ -344,10 +344,10 @@  discard block
 block discarded – undo
344 344
     function listUpdaters()
345 345
     {
346 346
         $sql = "SELECT rowid, type, description, parameters, fk_variable, update_interval, next_update, last_status";
347
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
347
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
348 348
 
349 349
         dol_syslog(get_class($this)."::listUpdaters");
350
-        $resql=$this->db->query($sql);
350
+        $resql = $this->db->query($sql);
351 351
         if ($resql)
352 352
         {
353 353
             $retarray = array();
@@ -355,16 +355,16 @@  discard block
 block discarded – undo
355 355
             while ($record = $this->db->fetch_array($resql))
356 356
             {
357 357
                 $updater_obj = new PriceGlobalVariableUpdater($this->db);
358
-                $updater_obj->id				= $record["rowid"];
359
-                $updater_obj->type				= $record["type"];
358
+                $updater_obj->id = $record["rowid"];
359
+                $updater_obj->type = $record["type"];
360 360
                 $updater_obj->description		= $record["description"];
361
-                $updater_obj->parameters		= $record["parameters"];
361
+                $updater_obj->parameters = $record["parameters"];
362 362
                 $updater_obj->fk_variable		= $record["fk_variable"];
363
-                $updater_obj->update_interval	= $record["update_interval"];
363
+                $updater_obj->update_interval = $record["update_interval"];
364 364
                 $updater_obj->next_update		= $record["next_update"];
365 365
                 $updater_obj->last_status		= $record["last_status"];
366 366
                 $updater_obj->checkParameters();
367
-                $retarray[]=$updater_obj;
367
+                $retarray[] = $updater_obj;
368 368
             }
369 369
 
370 370
             $this->db->free($resql);
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
         }
373 373
         else
374 374
         {
375
-            $this->error=$this->db->error();
375
+            $this->error = $this->db->error();
376 376
             return -1;
377 377
         }
378 378
     }
@@ -385,11 +385,11 @@  discard block
 block discarded – undo
385 385
     function listPendingUpdaters()
386 386
     {
387 387
         $sql = "SELECT rowid, type, description, parameters, fk_variable, update_interval, next_update, last_status";
388
-        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
389
-        $sql.= " WHERE next_update < ".dol_now();
388
+        $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
389
+        $sql .= " WHERE next_update < ".dol_now();
390 390
 
391 391
         dol_syslog(get_class($this)."::processUpdaters");
392
-        $resql=$this->db->query($sql);
392
+        $resql = $this->db->query($sql);
393 393
         if ($resql)
394 394
         {
395 395
             $retarray = array();
@@ -397,16 +397,16 @@  discard block
 block discarded – undo
397 397
             while ($record = $this->db->fetch_array($resql))
398 398
             {
399 399
                 $updater_obj = new PriceGlobalVariableUpdater($this->db);
400
-                $updater_obj->id				= $record["rowid"];
401
-                $updater_obj->type				= $record["type"];
400
+                $updater_obj->id = $record["rowid"];
401
+                $updater_obj->type = $record["type"];
402 402
                 $updater_obj->description		= $record["description"];
403
-                $updater_obj->parameters		= $record["parameters"];
403
+                $updater_obj->parameters = $record["parameters"];
404 404
                 $updater_obj->fk_variable		= $record["fk_variable"];
405
-                $updater_obj->update_interval	= $record["update_interval"];
405
+                $updater_obj->update_interval = $record["update_interval"];
406 406
                 $updater_obj->next_update		= $record["next_update"];
407 407
                 $updater_obj->last_status		= $record["last_status"];
408 408
                 $updater_obj->checkParameters();
409
-                $retarray[]=$updater_obj;
409
+                $retarray[] = $updater_obj;
410 410
             }
411 411
 
412 412
             $this->db->free($resql);
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
         }
415 415
         else
416 416
         {
417
-            $this->error=$this->db->error();
417
+            $this->error = $this->db->error();
418 418
             return -1;
419 419
         }
420 420
     }
@@ -466,9 +466,9 @@  discard block
 block discarded – undo
466 466
             if ($this->type == 0) {
467 467
                 // Call JSON request
468 468
                 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
469
-                $tmpresult=getURLContent($url);
470
-                $code=$tmpresult['http_code'];
471
-                $result=$tmpresult['content'];
469
+                $tmpresult = getURLContent($url);
470
+                $code = $tmpresult['http_code'];
471
+                $result = $tmpresult['content'];
472 472
 
473 473
                 if (!isset($result)) {
474 474
                     $this->error = $langs->trans("ErrorGlobalVariableUpdater0", "empty response");
@@ -501,9 +501,9 @@  discard block
 block discarded – undo
501 501
                 //SOAP client
502 502
                 require_once NUSOAP_PATH.'/nusoap.php';
503 503
                 $soap_client = new nusoap_client($url);
504
-                $soap_client->soap_defencoding='UTF-8';
504
+                $soap_client->soap_defencoding = 'UTF-8';
505 505
                 $soap_client->decodeUTF8(false);
506
-                $result = $soap_client->call($method, $data, $ns,'');
506
+                $result = $soap_client->call($method, $data, $ns, '');
507 507
 
508 508
                 //Check if result is a error
509 509
                 if ($result === false) {
@@ -537,34 +537,34 @@  discard block
 block discarded – undo
537 537
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
538 538
      *  @return int     		   	 <0 if KO, >0 if OK
539 539
      */
540
-    function update_next_update($next_update, $user=0, $notrigger=0)
540
+    function update_next_update($next_update, $user = 0, $notrigger = 0)
541 541
     {
542
-        $error=0;
542
+        $error = 0;
543 543
 
544 544
         $this->next_update = $next_update;
545 545
         $this->checkParameters();
546 546
 
547 547
         // Update request
548 548
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
549
-        $sql.= " next_update = ".$this->next_update;
550
-        $sql.= " WHERE rowid = ".$this->id;
549
+        $sql .= " next_update = ".$this->next_update;
550
+        $sql .= " WHERE rowid = ".$this->id;
551 551
 
552 552
         $this->db->begin();
553 553
 
554 554
         dol_syslog(get_class($this)."::update_next_update");
555 555
         $resql = $this->db->query($sql);
556
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
556
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
557 557
 
558 558
         // Commit or rollback
559 559
         if ($error)
560 560
         {
561
-            foreach($this->errors as $errmsg)
561
+            foreach ($this->errors as $errmsg)
562 562
             {
563 563
                 dol_syslog(get_class($this)."::update_next_update ".$errmsg, LOG_ERR);
564
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
564
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
565 565
             }
566 566
             $this->db->rollback();
567
-            return -1*$error;
567
+            return -1 * $error;
568 568
         }
569 569
         else
570 570
         {
@@ -581,34 +581,34 @@  discard block
 block discarded – undo
581 581
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
582 582
      *  @return int     		   	 <0 if KO, >0 if OK
583 583
      */
584
-    function update_status($last_status, $user=0, $notrigger=0)
584
+    function update_status($last_status, $user = 0, $notrigger = 0)
585 585
     {
586
-        $error=0;
586
+        $error = 0;
587 587
 
588 588
         $this->last_status = $last_status;
589 589
         $this->checkParameters();
590 590
 
591 591
         // Update request
592 592
         $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
593
-        $sql.= " last_status = ".(isset($this->last_status)?"'".$this->db->escape($this->last_status)."'":"''");
594
-        $sql.= " WHERE rowid = ".$this->id;
593
+        $sql .= " last_status = ".(isset($this->last_status) ? "'".$this->db->escape($this->last_status)."'" : "''");
594
+        $sql .= " WHERE rowid = ".$this->id;
595 595
 
596 596
         $this->db->begin();
597 597
 
598 598
         dol_syslog(get_class($this)."::update_status");
599 599
         $resql = $this->db->query($sql);
600
-        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
600
+        if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
601 601
 
602 602
         // Commit or rollback
603 603
         if ($error)
604 604
         {
605
-            foreach($this->errors as $errmsg)
605
+            foreach ($this->errors as $errmsg)
606 606
             {
607 607
                 dol_syslog(get_class($this)."::update_status ".$errmsg, LOG_ERR);
608
-                $this->error.=($this->error?', '.$errmsg:$errmsg);
608
+                $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
609 609
             }
610 610
             $this->db->rollback();
611
-            return -1*$error;
611
+            return -1 * $error;
612 612
         }
613 613
         else
614 614
         {
Please login to merge, or discard this patch.
Braces   +29 added lines, -25 removed lines patch added patch discarded remove patch
@@ -114,8 +114,7 @@  discard block
 block discarded – undo
114 114
             }
115 115
             $this->db->rollback();
116 116
             return -1*$error;
117
-        }
118
-        else
117
+        } else
119 118
         {
120 119
             $this->db->commit();
121 120
             return $this->id;
@@ -152,13 +151,11 @@  discard block
 block discarded – undo
152 151
                 $this->last_status		= $obj->last_status;
153 152
                 $this->checkParameters();
154 153
                 return 1;
155
-            }
156
-            else
154
+            } else
157 155
             {
158 156
                 return 0;
159 157
             }
160
-        }
161
-        else
158
+        } else
162 159
         {
163 160
             $this->error="Error ".$this->db->lasterror();
164 161
             return -1;
@@ -219,8 +216,7 @@  discard block
 block discarded – undo
219 216
             }
220 217
             $this->db->rollback();
221 218
             return -1*$error;
222
-        }
223
-        else
219
+        } else
224 220
         {
225 221
             $this->db->commit();
226 222
             return 1;
@@ -275,8 +271,7 @@  discard block
 block discarded – undo
275 271
             }
276 272
             $this->db->rollback();
277 273
             return -1*$error;
278
-        }
279
-        else
274
+        } else
280 275
         {
281 276
             $this->db->commit();
282 277
             return 1;
@@ -325,15 +320,28 @@  discard block
 block discarded – undo
325 320
     function checkParameters()
326 321
     {
327 322
         // Clean parameters
328
-        if (isset($this->description)) $this->description=trim($this->description);
329
-        if (isset($this->parameters)) $this->parameters=trim($this->parameters);
330
-        else $this->parameters="";
331
-        if (isset($this->last_status)) $this->last_status=trim($this->last_status);
323
+        if (isset($this->description)) {
324
+        	$this->description=trim($this->description);
325
+        }
326
+        if (isset($this->parameters)) {
327
+        	$this->parameters=trim($this->parameters);
328
+        } else {
329
+        	$this->parameters="";
330
+        }
331
+        if (isset($this->last_status)) {
332
+        	$this->last_status=trim($this->last_status);
333
+        }
332 334
 
333 335
         // Check parameters
334
-        if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type=0;
335
-        if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval=$this->update_min;
336
-        if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update=0;
336
+        if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) {
337
+        	$this->type=0;
338
+        }
339
+        if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) {
340
+        	$this->update_interval=$this->update_min;
341
+        }
342
+        if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) {
343
+        	$this->next_update=0;
344
+        }
337 345
     }
338 346
 
339 347
     /**
@@ -369,8 +377,7 @@  discard block
 block discarded – undo
369 377
 
370 378
             $this->db->free($resql);
371 379
             return $retarray;
372
-        }
373
-        else
380
+        } else
374 381
         {
375 382
             $this->error=$this->db->error();
376 383
             return -1;
@@ -411,8 +418,7 @@  discard block
 block discarded – undo
411 418
 
412 419
             $this->db->free($resql);
413 420
             return $retarray;
414
-        }
415
-        else
421
+        } else
416 422
         {
417 423
             $this->error=$this->db->error();
418 424
             return -1;
@@ -565,8 +571,7 @@  discard block
 block discarded – undo
565 571
             }
566 572
             $this->db->rollback();
567 573
             return -1*$error;
568
-        }
569
-        else
574
+        } else
570 575
         {
571 576
             $this->db->commit();
572 577
             return 1;
@@ -609,8 +614,7 @@  discard block
 block discarded – undo
609 614
             }
610 615
             $this->db->rollback();
611 616
             return -1*$error;
612
-        }
613
-        else
617
+        } else
614 618
         {
615 619
             $this->db->commit();
616 620
             return 1;
Please login to merge, or discard this patch.
htdocs/societe/class/societe.class.php 4 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1577,7 +1577,7 @@  discard block
 block discarded – undo
1577 1577
      *    	@param	float	$remise     Amount of discount
1578 1578
      *    	@param  User	$user       User adding discount
1579 1579
      *    	@param  string	$desc		Reason of discount
1580
-     *      @param  float	$tva_tx     VAT rate
1580
+     *      @param  integer	$tva_tx     VAT rate
1581 1581
      *		@return	int					<0 if KO, id of discount record if OK
1582 1582
      */
1583 1583
     function set_remise_except($remise, User $user, $desc, $tva_tx=0)
@@ -2235,7 +2235,7 @@  discard block
 block discarded – undo
2235 2235
      *  Attribut un code client a partir du module de controle des codes.
2236 2236
      *  Return value is stored into this->code_client
2237 2237
      *
2238
-     *	@param	Societe		$objsoc		Object thirdparty
2238
+     *	@param	integer		$objsoc		Object thirdparty
2239 2239
      *	@param	int			$type		Should be 0 to say customer
2240 2240
      *  @return void
2241 2241
      */
@@ -2265,7 +2265,7 @@  discard block
 block discarded – undo
2265 2265
      *  Attribut un code fournisseur a partir du module de controle des codes.
2266 2266
      *  Return value is stored into this->code_fournisseur
2267 2267
      *
2268
-     *	@param	Societe		$objsoc		Object thirdparty
2268
+     *	@param	integer		$objsoc		Object thirdparty
2269 2269
      *	@param	int			$type		Should be 1 to say supplier
2270 2270
      *  @return void
2271 2271
      */
@@ -2806,7 +2806,7 @@  discard block
 block discarded – undo
2806 2806
     /**
2807 2807
      *  Return if third party is a company (Business) or an end user (Consumer)
2808 2808
      *
2809
-     *  @return    boolean     true=is a company, false=a and user
2809
+     *  @return    integer     true=is a company, false=a and user
2810 2810
      */
2811 2811
     function isACompany()
2812 2812
     {
Please login to merge, or discard this patch.
Indentation   +3077 added lines, -3077 removed lines patch added patch discarded remove patch
@@ -40,28 +40,28 @@  discard block
 block discarded – undo
40 40
  */
41 41
 class Societe extends CommonObject
42 42
 {
43
-    public $element='societe';
44
-    public $table_element = 'societe';
43
+	public $element='societe';
44
+	public $table_element = 'societe';
45 45
 	public $fk_element='fk_soc';
46
-    protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord');    // To test if we can delete object
46
+	protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord');    // To test if we can delete object
47 47
 	protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
48 48
 
49 49
 
50 50
 	/**
51
-     * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
52
-     * @var int
53
-     */
54
-    protected $ismultientitymanaged = 1;
51
+	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
52
+	 * @var int
53
+	 */
54
+	protected $ismultientitymanaged = 1;
55 55
 
56
-    public $entity;
56
+	public $entity;
57 57
 
58
-    /**
59
-     * Thirdparty name
60
-     * @var string
61
-     * @deprecated Use $name instead
62
-     * @see name
63
-     */
64
-    public $nom;
58
+	/**
59
+	 * Thirdparty name
60
+	 * @var string
61
+	 * @deprecated Use $name instead
62
+	 * @see name
63
+	 */
64
+	public $nom;
65 65
 
66 66
 	/**
67 67
 	 * Alias names (commercial, trademark or alias names)
@@ -69,46 +69,46 @@  discard block
 block discarded – undo
69 69
 	 */
70 70
 	public $name_alias;
71 71
 
72
-    public $particulier;
73
-    public $address;
74
-    public $zip;
75
-    public $town;
76
-
77
-    /**
78
-     * Thirdparty status : 0=activity ceased, 1= in activity
79
-     * @var int
80
-     */
81
-    var $status;
82
-
83
-    /**
84
-     * Id of department
85
-     * @var int
86
-     */
87
-    var $state_id;
88
-    var $state_code;
89
-    var $state;
90
-
91
-    /**
92
-     * State code
93
-     * @var string
94
-     * @deprecated Use state_code instead
95
-     * @see state_code
96
-     */
97
-    var $departement_code;
98
-
99
-    /**
100
-     * @var string
101
-     * @deprecated Use state instead
102
-     * @see state
103
-     */
104
-    var $departement;
105
-
106
-    /**
107
-     * @var string
108
-     * @deprecated Use country instead
109
-     * @see country
110
-     */
111
-    var $pays;
72
+	public $particulier;
73
+	public $address;
74
+	public $zip;
75
+	public $town;
76
+
77
+	/**
78
+	 * Thirdparty status : 0=activity ceased, 1= in activity
79
+	 * @var int
80
+	 */
81
+	var $status;
82
+
83
+	/**
84
+	 * Id of department
85
+	 * @var int
86
+	 */
87
+	var $state_id;
88
+	var $state_code;
89
+	var $state;
90
+
91
+	/**
92
+	 * State code
93
+	 * @var string
94
+	 * @deprecated Use state_code instead
95
+	 * @see state_code
96
+	 */
97
+	var $departement_code;
98
+
99
+	/**
100
+	 * @var string
101
+	 * @deprecated Use state instead
102
+	 * @see state
103
+	 */
104
+	var $departement;
105
+
106
+	/**
107
+	 * @var string
108
+	 * @deprecated Use country instead
109
+	 * @see country
110
+	 */
111
+	var $pays;
112 112
 
113 113
 	/**
114 114
 	 * Phone number
@@ -137,77 +137,77 @@  discard block
 block discarded – undo
137 137
 	var $url;
138 138
 
139 139
 	//! barcode
140
-    /**
141
-     * Barcode value
142
-     * @var string
143
-     */
144
-    var $barcode;
145
-
146
-    // 6 professional id (usage depends on country)
147
-
148
-    /**
149
-     * Professional ID 1 (Ex: Siren in France)
150
-     * @var string
151
-     */
152
-    var $idprof1;
153
-
154
-    /**
155
-     * Professional ID 2 (Ex: Siret in France)
156
-     * @var string
157
-     */
158
-    var $idprof2;
159
-
160
-    /**
161
-     * Professional ID 3 (Ex: Ape in France)
162
-     * @var string
163
-     */
164
-    var $idprof3;
165
-
166
-    /**
167
-     * Professional ID 4 (Ex: RCS in France)
168
-     * @var string
169
-     */
170
-    var $idprof4;
171
-
172
-    /**
173
-     * Professional ID 5
174
-     * @var string
175
-     */
176
-    var $idprof5;
177
-
178
-    /**
179
-     * Professional ID 6
180
-     * @var string
181
-     */
182
-    var $idprof6;
183
-
184
-    var $prefix_comm;
185
-
186
-    var $tva_assuj;
187
-    /**
188
-     * Intracommunitary VAT ID
189
-     * @var string
190
-     */
191
-    var $tva_intra;
192
-
193
-    // Local taxes
194
-    var $localtax1_assuj;
195
-    var $localtax1_value;
196
-    var $localtax2_assuj;
197
-    var $localtax2_value;
198
-
199
-    var $managers;
200
-    var $capital;
201
-    var $typent_id;
202
-    var $typent_code;
203
-    var $effectif;
204
-    var $effectif_id;
205
-    var $forme_juridique_code;
206
-    var $forme_juridique;
207
-
208
-    var $remise_percent;
209
-    var $mode_reglement_supplier_id;
210
-    var $cond_reglement_supplier_id;
140
+	/**
141
+	 * Barcode value
142
+	 * @var string
143
+	 */
144
+	var $barcode;
145
+
146
+	// 6 professional id (usage depends on country)
147
+
148
+	/**
149
+	 * Professional ID 1 (Ex: Siren in France)
150
+	 * @var string
151
+	 */
152
+	var $idprof1;
153
+
154
+	/**
155
+	 * Professional ID 2 (Ex: Siret in France)
156
+	 * @var string
157
+	 */
158
+	var $idprof2;
159
+
160
+	/**
161
+	 * Professional ID 3 (Ex: Ape in France)
162
+	 * @var string
163
+	 */
164
+	var $idprof3;
165
+
166
+	/**
167
+	 * Professional ID 4 (Ex: RCS in France)
168
+	 * @var string
169
+	 */
170
+	var $idprof4;
171
+
172
+	/**
173
+	 * Professional ID 5
174
+	 * @var string
175
+	 */
176
+	var $idprof5;
177
+
178
+	/**
179
+	 * Professional ID 6
180
+	 * @var string
181
+	 */
182
+	var $idprof6;
183
+
184
+	var $prefix_comm;
185
+
186
+	var $tva_assuj;
187
+	/**
188
+	 * Intracommunitary VAT ID
189
+	 * @var string
190
+	 */
191
+	var $tva_intra;
192
+
193
+	// Local taxes
194
+	var $localtax1_assuj;
195
+	var $localtax1_value;
196
+	var $localtax2_assuj;
197
+	var $localtax2_value;
198
+
199
+	var $managers;
200
+	var $capital;
201
+	var $typent_id;
202
+	var $typent_code;
203
+	var $effectif;
204
+	var $effectif_id;
205
+	var $forme_juridique_code;
206
+	var $forme_juridique;
207
+
208
+	var $remise_percent;
209
+	var $mode_reglement_supplier_id;
210
+	var $cond_reglement_supplier_id;
211 211
 	var $fk_prospectlevel;
212 212
 	var $name_bis;
213 213
 
@@ -215,541 +215,206 @@  discard block
 block discarded – undo
215 215
 
216 216
 	/**
217 217
 	 * Date of last update
218
-     * @var string
218
+	 * @var string
219 219
 	 */
220 220
 	var $date_modification;
221 221
 	/**
222 222
 	 * User that made last update
223
-     * @var string
223
+	 * @var string
224 224
 	 */
225 225
 	var $user_modification;
226 226
 	/**
227 227
 	 * Date of creation
228
-     * @var string
228
+	 * @var string
229 229
 	 */
230 230
 	var $date_creation;
231 231
 	/**
232 232
 	 * User that created the thirdparty
233
-     * @var User
233
+	 * @var User
234 234
 	 */
235 235
 	var $user_creation;
236 236
 
237 237
 
238
-    var $specimen;
239
-
240
-    /**
241
-     * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
242
-     * @var int
243
-     */
244
-    var $client;
245
-    /**
246
-     * 0=no prospect, 1=prospect
247
-     * @var int
248
-     */
249
-    var $prospect;
250
-    /**
251
-     * 0=no supplier, 1=supplier
252
-     * @var int
253
-     */
254
-    var $fournisseur;
255
-
256
-    /**
257
-     * Client code. E.g: CU2014-003
258
-     * @var string
259
-     */
260
-    var $code_client;
261
-
262
-    /**
263
-     * Supplier code. E.g: SU2014-003
264
-     * @var string
265
-     */
266
-    var $code_fournisseur;
267
-
268
-    /**
269
-     * Accounting code for client
270
-     * @var string
271
-     */
272
-    var $code_compta;
273
-
274
-    /**
275
-     * Accounting code for suppliers
276
-     * @var string
277
-     */
278
-    var $code_compta_fournisseur;
279
-
280
-    /**
281
-     * @var string
282
-     * @deprecated Note is split in public and private notes
283
-     * @see note_public, note_private
284
-     */
285
-    var $note;
286
-
287
-    /**
288
-     * Private note
289
-     * @var string
290
-     */
291
-    var $note_private;
292
-
293
-    /**
294
-     * Public note
295
-     * @var string
296
-     */
297
-    var $note_public;
298
-
299
-    //! code statut prospect
300
-    var $stcomm_id;
301
-    var $statut_commercial;
302
-
303
-    /**
304
-     * Assigned price level
305
-     * @var int
306
-     */
307
-    var $price_level;
308
-    var $outstanding_limit;
309
-
310
-    /**
311
-     * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
312
-     * @var int
313
-     */
314
-    var $commercial_id;
315
-    /**
316
-     * Id of parent thirdparty (if one)
317
-     * @var int
318
-     */
319
-    var $parent;
320
-    /**
321
-     * Default language code of thirdparty (en_US, ...)
322
-     * @var string
323
-     */
324
-    var $default_lang;
325
-
326
-    var $ref;
327
-    var $ref_int;
328
-    /**
329
-     * External user reference.
330
-     * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
331
-     * build.
332
-     * @var string
333
-     */
334
-    var $ref_ext;
335
-
336
-    /**
337
-     * Import key.
338
-     * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
339
-     * to an import process
340
-     * @var string
341
-     */
342
-    var $import_key;
343
-
344
-    /**
345
-     * Supplier WebServices URL
346
-     * @var string
347
-     */
348
-    var $webservices_url;
349
-
350
-    /**
351
-     * Supplier WebServices Key
352
-     * @var string
353
-     */
354
-    var $webservices_key;
355
-
356
-    var $logo;
357
-    var $logo_small;
358
-    var $logo_mini;
359
-
360
-    var $array_options;
238
+	var $specimen;
361 239
 
362
-	// Incoterms
363
-	var $fk_incoterms;
364
-	var $location_incoterms;
365
-	var $libelle_incoterms;  //Used into tooltip
240
+	/**
241
+	 * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
242
+	 * @var int
243
+	 */
244
+	var $client;
245
+	/**
246
+	 * 0=no prospect, 1=prospect
247
+	 * @var int
248
+	 */
249
+	var $prospect;
250
+	/**
251
+	 * 0=no supplier, 1=supplier
252
+	 * @var int
253
+	 */
254
+	var $fournisseur;
366 255
 
367
-	// Multicurrency
368
-	var $fk_multicurrency;
369
-	var $multicurrency_code;
256
+	/**
257
+	 * Client code. E.g: CU2014-003
258
+	 * @var string
259
+	 */
260
+	var $code_client;
370 261
 
371
-    /**
372
-     * To contains a clone of this when we need to save old properties of object
373
-     *  @var Societe
374
-     */
375
-    var $oldcopy;
376
-
377
-    /**
378
-     *    Constructor
379
-     *
380
-     *    @param	DoliDB		$db		Database handler
381
-     */
382
-    public function __construct($db)
383
-    {
384
-        $this->db = $db;
385
-
386
-        $this->client = 0;
387
-        $this->prospect = 0;
388
-        $this->fournisseur = 0;
389
-        $this->typent_id  = 0;
390
-        $this->effectif_id  = 0;
391
-        $this->forme_juridique_code  = 0;
392
-        $this->tva_assuj = 1;
393
-        $this->status = 1;
394
-    }
395
-
396
-
397
-    /**
398
-     *    Create third party in database.
399
-     *    $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
400
-     *
401
-     *    @param	User	$user       Object of user that ask creation
402
-     *    @return   int         		>= 0 if OK, < 0 if KO
403
-     */
404
-    function create($user)
405
-    {
406
-        global $langs,$conf,$mysoc;
262
+	/**
263
+	 * Supplier code. E.g: SU2014-003
264
+	 * @var string
265
+	 */
266
+	var $code_fournisseur;
407 267
 
408
-		$error=0;
268
+	/**
269
+	 * Accounting code for client
270
+	 * @var string
271
+	 */
272
+	var $code_compta;
409 273
 
410
-        // Clean parameters
411
-        if (empty($this->status)) $this->status=0;
412
-        $this->name=$this->name?trim($this->name):trim($this->nom);
413
-        if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
414
-        $this->nom=$this->name; // For backward compatibility
415
-        if (empty($this->client))      $this->client=0;
416
-        if (empty($this->fournisseur)) $this->fournisseur=0;
417
-        $this->import_key = trim($this->import_key);
274
+	/**
275
+	 * Accounting code for suppliers
276
+	 * @var string
277
+	 */
278
+	var $code_compta_fournisseur;
418 279
 
419
-		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
420
-		if (empty($this->fk_multicurrency))
421
-		{
422
-			$this->multicurrency_code = '';
423
-			$this->fk_multicurrency = 0;
424
-		}
280
+	/**
281
+	 * @var string
282
+	 * @deprecated Note is split in public and private notes
283
+	 * @see note_public, note_private
284
+	 */
285
+	var $note;
425 286
 
426
-        dol_syslog(get_class($this)."::create ".$this->name);
287
+	/**
288
+	 * Private note
289
+	 * @var string
290
+	 */
291
+	var $note_private;
427 292
 
428
-        $now=dol_now();
293
+	/**
294
+	 * Public note
295
+	 * @var string
296
+	 */
297
+	var $note_public;
429 298
 
430
-        $this->db->begin();
299
+	//! code statut prospect
300
+	var $stcomm_id;
301
+	var $statut_commercial;
431 302
 
432
-        // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
433
-        if ($this->code_client == -1)      $this->get_codeclient($this,0);
434
-        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
303
+	/**
304
+	 * Assigned price level
305
+	 * @var int
306
+	 */
307
+	var $price_level;
308
+	var $outstanding_limit;
435 309
 
436
-        // Check more parameters (including mandatory setup
437
-        // If error, this->errors[] is filled
438
-        $result = $this->verify();
310
+	/**
311
+	 * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
312
+	 * @var int
313
+	 */
314
+	var $commercial_id;
315
+	/**
316
+	 * Id of parent thirdparty (if one)
317
+	 * @var int
318
+	 */
319
+	var $parent;
320
+	/**
321
+	 * Default language code of thirdparty (en_US, ...)
322
+	 * @var string
323
+	 */
324
+	var $default_lang;
439 325
 
440
-        if ($result >= 0)
441
-        {
442
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
443
-            $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'";
444
-            $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
445
-            $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
446
-            $sql.= ", ".$this->status;
447
-            $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
448
-            $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
449
-            $sql.= ", 0";
450
-			$sql.= ", ".(int) $this->fk_incoterms;
451
-			$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
452
-            $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
453
-            $sql.= ", ".(int) $this->fk_multicurrency;
454
-            $sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
455
-
456
-            dol_syslog(get_class($this)."::create", LOG_DEBUG);
457
-            $result=$this->db->query($sql);
458
-            if ($result)
459
-            {
460
-                $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
461
-
462
-                $ret = $this->update($this->id,$user,0,1,1,'add');
463
-
464
-                // Ajout du commercial affecte
465
-                if ($this->commercial_id != '' && $this->commercial_id != -1)
466
-                {
467
-                    $this->add_commercial($user, $this->commercial_id);
468
-                }
469
-                // si un commercial cree un client il lui est affecte automatiquement
470
-                else if (empty($user->rights->societe->client->voir))
471
-                {
472
-                    $this->add_commercial($user, $user->id);
473
-                }
474
-
475
-                if ($ret >= 0)
476
-                {
477
-                    // Call trigger
478
-                    $result=$this->call_trigger('COMPANY_CREATE',$user);
479
-                    if ($result < 0) $error++;
480
-                    // End call triggers
481
-                }
482
-                else $error++;
483
-
484
-                if (! $error)
485
-                {
486
-                    dol_syslog(get_class($this)."::Create success id=".$this->id);
487
-                    $this->db->commit();
488
-                    return $this->id;
489
-                }
490
-                else
491
-                {
492
-                    dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
493
-                    $this->db->rollback();
494
-                    return -4;
495
-                }
496
-            }
497
-            else
498
-            {
499
-                if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
500
-                {
501
-                    $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
502
-                    $result=-1;
503
-                }
504
-                else
505
-                {
506
-                    $this->error=$this->db->lasterror();
507
-                    $result=-2;
508
-                }
509
-                $this->db->rollback();
510
-                return $result;
511
-            }
326
+	var $ref;
327
+	var $ref_int;
328
+	/**
329
+	 * External user reference.
330
+	 * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
331
+	 * build.
332
+	 * @var string
333
+	 */
334
+	var $ref_ext;
512 335
 
513
-        }
514
-        else
515
-        {
516
-            $this->db->rollback();
517
-            dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
518
-            return -3;
519
-        }
520
-    }
521
-
522
-
523
-    /**
524
-     * Create a contact/address from thirdparty
525
-     *
526
-     * @param 	User	$user		Object user
527
-     * @return 	int					<0 if KO, >0 if OK
528
-     */
529
-    function create_individual(User $user)
530
-    {
531
-        require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
532
-        $contact=new Contact($this->db);
533
-
534
-        $contact->name              = $this->name_bis;
535
-        $contact->firstname         = $this->firstname;
536
-        $contact->civility_id       = $this->civility_id;
537
-        $contact->socid             = $this->id;	// fk_soc
538
-        $contact->statut            = 1;
539
-        $contact->priv              = 0;
540
-        $contact->country_id        = $this->country_id;
541
-        $contact->state_id          = $this->state_id;
542
-        $contact->address           = $this->address;
543
-        $contact->email             = $this->email;
544
-        $contact->zip               = $this->zip;
545
-        $contact->town              = $this->town;
546
-        $contact->phone_pro         = $this->phone;
547
-
548
-        $result = $contact->create($user);
549
-        if ($result < 0)
550
-        {
551
-            $this->error = $contact->error;
552
-            $this->errors = $contact->errors;
553
-            dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
554
-        }
336
+	/**
337
+	 * Import key.
338
+	 * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
339
+	 * to an import process
340
+	 * @var string
341
+	 */
342
+	var $import_key;
555 343
 
556
-        return $result;
557
-    }
558
-
559
-    /**
560
-     *    Check properties of third party are ok (like name, third party codes, ...)
561
-     *    Used before an add or update.
562
-     *
563
-     *    @return     int		0 if OK, <0 if KO
564
-     */
565
-    function verify()
566
-    {
567
-    	global $conf, $langs, $mysoc;
568
-
569
-    	$error = 0;
570
-        $this->errors=array();
571
-
572
-        $result = 0;
573
-        $this->name	= trim($this->name);
574
-        $this->nom=$this->name; // For backward compatibility
575
-
576
-        if (! $this->name)
577
-        {
578
-            $this->errors[] = 'ErrorBadThirdPartyName';
579
-            $result = -2;
580
-        }
344
+	/**
345
+	 * Supplier WebServices URL
346
+	 * @var string
347
+	 */
348
+	var $webservices_url;
581 349
 
582
-        if ($this->client)
583
-        {
584
-            $rescode = $this->check_codeclient();
585
-            if ($rescode <> 0)
586
-            {
587
-                if ($rescode == -1)
588
-                {
589
-                    $this->errors[] = 'ErrorBadCustomerCodeSyntax';
590
-                }
591
-                if ($rescode == -2)
592
-                {
593
-                    $this->errors[] = 'ErrorCustomerCodeRequired';
594
-                }
595
-                if ($rescode == -3)
596
-                {
597
-                    $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
598
-                }
599
-                if ($rescode == -4)
600
-                {
601
-                    $this->errors[] = 'ErrorPrefixRequired';
602
-                }
603
-                $result = -3;
604
-            }
605
-        }
350
+	/**
351
+	 * Supplier WebServices Key
352
+	 * @var string
353
+	 */
354
+	var $webservices_key;
606 355
 
607
-        if ($this->fournisseur)
608
-        {
609
-            $rescode = $this->check_codefournisseur();
610
-            if ($rescode <> 0)
611
-            {
612
-                if ($rescode == -1)
613
-                {
614
-                    $this->errors[] = 'ErrorBadSupplierCodeSyntax';
615
-                }
616
-                if ($rescode == -2)
617
-                {
618
-                    $this->errors[] = 'ErrorSupplierCodeRequired';
619
-                }
620
-                if ($rescode == -3)
621
-                {
622
-                    $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
623
-                }
624
-                if ($rescode == -5)
625
-                {
626
-                    $this->errors[] = 'ErrorprefixRequired';
627
-                }
628
-                $result = -3;
629
-            }
630
-        }
356
+	var $logo;
357
+	var $logo_small;
358
+	var $logo_mini;
359
+
360
+	var $array_options;
361
+
362
+	// Incoterms
363
+	var $fk_incoterms;
364
+	var $location_incoterms;
365
+	var $libelle_incoterms;  //Used into tooltip
366
+
367
+	// Multicurrency
368
+	var $fk_multicurrency;
369
+	var $multicurrency_code;
370
+
371
+	/**
372
+	 * To contains a clone of this when we need to save old properties of object
373
+	 *  @var Societe
374
+	 */
375
+	var $oldcopy;
376
+
377
+	/**
378
+	 *    Constructor
379
+	 *
380
+	 *    @param	DoliDB		$db		Database handler
381
+	 */
382
+	public function __construct($db)
383
+	{
384
+		$this->db = $db;
385
+
386
+		$this->client = 0;
387
+		$this->prospect = 0;
388
+		$this->fournisseur = 0;
389
+		$this->typent_id  = 0;
390
+		$this->effectif_id  = 0;
391
+		$this->forme_juridique_code  = 0;
392
+		$this->tva_assuj = 1;
393
+		$this->status = 1;
394
+	}
631 395
 
632
-        // Check for duplicate or mandatory fields defined into setup
633
-        $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
634
-        foreach($array_to_check as $key)
635
-        {
636
-        	$keymin=strtolower($key);
637
-        	$i=(int) preg_replace('/[^0-9]/','',$key);
638
-        	$vallabel=$this->$keymin;
639
-
640
-        	if ($i > 0)
641
-        	{
642
-        		if ($this->isACompany())
643
-        		{
644
-        			// Check for unicity
645
-        			if ($vallabel && $this->id_prof_verifiable($i))
646
-        			{
647
-        				if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
648
-        				{
649
-        					$langs->load("errors");
650
-        					$error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
651
-        				}
652
-        			}
653
-
654
-        			// Check for mandatory prof id (but only if country is other than ours)
655
-        			if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
656
-        			{
657
-        				$idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
658
-        				if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
659
-        				{
660
-        					$langs->load("errors");
661
-        					$error++;
662
-        					$this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
663
-        				}
664
-        			}
665
-        		}
666
-        	}
667
-        	else
668
-        	{
669
-        		//var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
670
-        		if ($key == 'EMAIL')
671
-        		{
672
-        			// Check for unicity
673
-        			if ($vallabel)
674
-        			{
675
-        				if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
676
-        				{
677
-        					$langs->load("errors");
678
-        					$error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
679
-        				}
680
-        			}
681
-
682
-        			// Check for mandatory
683
-        			if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
684
-        			{
685
-        				$langs->load("errors");
686
-        				$error++;
687
-        				$this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
688
-        			}
689
-        		}
690
-        	}
691
-        }
692 396
 
693
-        if ($error) $result = -4;
694
-
695
-        return $result;
696
-    }
697
-
698
-    /**
699
-     *      Update parameters of third party
700
-     *
701
-     *      @param	int		$id              			id societe
702
-     *      @param  User	$user            			Utilisateur qui demande la mise a jour
703
-     *      @param  int		$call_trigger    			0=non, 1=oui
704
-     *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
705
-     *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
706
-     *		@param	string	$action						'add' or 'update'
707
-     *		@param	int		$nosyncmember				Do not synchronize info of linked member
708
-     *      @return int  			           			<0 if KO, >=0 if OK
709
-     */
710
-    function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
711
-    {
712
-        global $langs,$conf,$hookmanager;
713
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
397
+	/**
398
+	 *    Create third party in database.
399
+	 *    $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
400
+	 *
401
+	 *    @param	User	$user       Object of user that ask creation
402
+	 *    @return   int         		>= 0 if OK, < 0 if KO
403
+	 */
404
+	function create($user)
405
+	{
406
+		global $langs,$conf,$mysoc;
714 407
 
715 408
 		$error=0;
716 409
 
717
-        dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
718
-
719
-        $now=dol_now();
720
-
721
-        // Clean parameters
722
-        $this->id			= $id;
723
-        $this->name			= $this->name?trim($this->name):trim($this->nom);
724
-        $this->nom			= $this->name;	// For backward compatibility
725
-	    $this->name_alias = trim($this->name_alias);
726
-        $this->ref_ext		= trim($this->ref_ext);
727
-        $this->address		= $this->address?trim($this->address):trim($this->address);
728
-        $this->zip			= $this->zip?trim($this->zip):trim($this->zip);
729
-        $this->town			= $this->town?trim($this->town):trim($this->town);
730
-        $this->state_id		= trim($this->state_id);
731
-        $this->country_id	= ($this->country_id > 0)?$this->country_id:0;
732
-        $this->phone		= trim($this->phone);
733
-        $this->phone		= preg_replace("/\s/","",$this->phone);
734
-        $this->phone		= preg_replace("/\./","",$this->phone);
735
-        $this->fax			= trim($this->fax);
736
-        $this->fax			= preg_replace("/\s/","",$this->fax);
737
-        $this->fax			= preg_replace("/\./","",$this->fax);
738
-        $this->email		= trim($this->email);
739
-        $this->skype		= trim($this->skype);
740
-        $this->url			= $this->url?clean_url($this->url,0):'';
741
-        $this->idprof1		= trim($this->idprof1);
742
-        $this->idprof2		= trim($this->idprof2);
743
-        $this->idprof3		= trim($this->idprof3);
744
-        $this->idprof4		= trim($this->idprof4);
745
-        $this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
746
-        $this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
747
-        $this->prefix_comm	= trim($this->prefix_comm);
748
-        $this->outstanding_limit = price2num($this->outstanding_limit);
749
-
750
-        $this->tva_assuj	= trim($this->tva_assuj);
751
-        $this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
752
-        if (empty($this->status)) $this->status = 0;
410
+		// Clean parameters
411
+		if (empty($this->status)) $this->status=0;
412
+		$this->name=$this->name?trim($this->name):trim($this->nom);
413
+		if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
414
+		$this->nom=$this->name; // For backward compatibility
415
+		if (empty($this->client))      $this->client=0;
416
+		if (empty($this->fournisseur)) $this->fournisseur=0;
417
+		$this->import_key = trim($this->import_key);
753 418
 
754 419
 		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
755 420
 		if (empty($this->fk_multicurrency))
@@ -758,2308 +423,2643 @@  discard block
 block discarded – undo
758 423
 			$this->fk_multicurrency = 0;
759 424
 		}
760 425
 
761
-        // Local taxes
762
-        $this->localtax1_assuj=trim($this->localtax1_assuj);
763
-        $this->localtax2_assuj=trim($this->localtax2_assuj);
426
+		dol_syslog(get_class($this)."::create ".$this->name);
764 427
 
765
-        $this->localtax1_value=trim($this->localtax1_value);
766
-        $this->localtax2_value=trim($this->localtax2_value);
428
+		$now=dol_now();
767 429
 
768
-        if ($this->capital != '') $this->capital=price2num(trim($this->capital));
769
-        if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
430
+		$this->db->begin();
770 431
 
771
-        $this->effectif_id=trim($this->effectif_id);
772
-        $this->forme_juridique_code=trim($this->forme_juridique_code);
432
+		// For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
433
+		if ($this->code_client == -1)      $this->get_codeclient($this,0);
434
+		if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
773 435
 
774
-        //Gencod
775
-        $this->barcode=trim($this->barcode);
776
-
777
-        // For automatic creation
778
-        if ($this->code_client == -1) $this->get_codeclient($this,0);
779
-        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
780
-
781
-        $this->code_compta=trim($this->code_compta);
782
-        $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
783
-
784
-        // Check parameters. More tests are done later in the ->verify()
785
-        if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
786
-        {
787
-            $langs->load("errors");
788
-            $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
789
-            return -1;
790
-        }
791
-
792
-        $customer=false;
793
-        if (! empty($allowmodcodeclient) && ! empty($this->client))
794
-        {
795
-        	// Attention get_codecompta peut modifier le code suivant le module utilise
796
-        	if (empty($this->code_compta))
797
-        	{
798
-        		$ret=$this->get_codecompta('customer');
799
-        		if ($ret < 0) return -1;
800
-        	}
801
-
802
-        	$customer=true;
803
-        }
804
-
805
-        $supplier=false;
806
-        if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
807
-        {
808
-        	// Attention get_codecompta peut modifier le code suivant le module utilise
809
-        	if (empty($this->code_compta_fournisseur))
810
-        	{
811
-        		$ret=$this->get_codecompta('supplier');
812
-        		if ($ret < 0) return -1;
813
-        	}
814
-
815
-        	$supplier=true;
816
-        }
436
+		// Check more parameters (including mandatory setup
437
+		// If error, this->errors[] is filled
438
+		$result = $this->verify();
817 439
 
818
-        //Web services
819
-        $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
820
-        $this->webservices_key = trim($this->webservices_key);
440
+		if ($result >= 0)
441
+		{
442
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
443
+			$sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'";
444
+			$sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
445
+			$sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
446
+			$sql.= ", ".$this->status;
447
+			$sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
448
+			$sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
449
+			$sql.= ", 0";
450
+			$sql.= ", ".(int) $this->fk_incoterms;
451
+			$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
452
+			$sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
453
+			$sql.= ", ".(int) $this->fk_multicurrency;
454
+			$sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
821 455
 
822
-        //Incoterms
823
-        $this->fk_incoterms = (int) $this->fk_incoterms;
824
-		$this->location_incoterms = trim($this->location_incoterms);
456
+			dol_syslog(get_class($this)."::create", LOG_DEBUG);
457
+			$result=$this->db->query($sql);
458
+			if ($result)
459
+			{
460
+				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
825 461
 
826
-        $this->db->begin();
827
-
828
-        // Check name is required and codes are ok or unique.
829
-        // If error, this->errors[] is filled
830
-        $result = 0;
831
-        if ($action != 'add') $result = $this->verify();	// We don't check when update called during a create because verify was already done
832
-
833
-        if ($result >= 0)
834
-        {
835
-            dol_syslog(get_class($this)."::update verify ok or not done");
836
-
837
-            $sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
838
-            $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
839
-            $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
840
-            $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
841
-            $sql .= ",address = '" . $this->db->escape($this->address) ."'";
842
-
843
-            $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
844
-            $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
845
-
846
-            $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
847
-            $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
848
-
849
-            $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
850
-            $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
851
-            $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
852
-            $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
853
-            $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
854
-
855
-            $sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
856
-            $sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
857
-            $sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
858
-            $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
859
-            $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
860
-            $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
861
-
862
-            $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
863
-            $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
864
-            $sql .= ",status = " .$this->status;
865
-
866
-            // Local taxes
867
-            $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
868
-            $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
869
-            if($this->localtax1_assuj==1)
870
-            {
871
-            	if($this->localtax1_value!='')
872
-            	{
873
-            		$sql .=",localtax1_value =".$this->localtax1_value;
874
-            	}
875
-            	else $sql .=",localtax1_value =0.000";
876
-
877
-            }
878
-            else $sql .=",localtax1_value =0.000";
879
-
880
-            if($this->localtax2_assuj==1)
881
-            {
882
-            	if($this->localtax2_value!='')
883
-            	{
884
-            		$sql .=",localtax2_value =".$this->localtax2_value;
885
-            	}
886
-            	else $sql .=",localtax2_value =0.000";
887
-
888
-            }
889
-            else $sql .=",localtax2_value =0.000";
890
-
891
-            $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
892
-
893
-            $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
894
-
895
-            $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
896
-            if (isset($this->stcomm_id))
897
-            {
898
-                $sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? $this->stcomm_id : "0");
899
-            }
900
-            $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
901
-
902
-            $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
903
-
904
-            $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
905
-            $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
906
-            $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
907
-            $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
908
-            $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
909
-
910
-            $sql .= ",client = " . (! empty($this->client)?$this->client:0);
911
-            $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
912
-            $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
913
-            $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
914
-            $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
915
-            $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
916
-            $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
917
-
918
-            $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
919
-            $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
462
+				$ret = $this->update($this->id,$user,0,1,1,'add');
920 463
 
921
-			//Incoterms
922
-			$sql.= ", fk_incoterms = ".$this->fk_incoterms;
923
-			$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
464
+				// Ajout du commercial affecte
465
+				if ($this->commercial_id != '' && $this->commercial_id != -1)
466
+				{
467
+					$this->add_commercial($user, $this->commercial_id);
468
+				}
469
+				// si un commercial cree un client il lui est affecte automatiquement
470
+				else if (empty($user->rights->societe->client->voir))
471
+				{
472
+					$this->add_commercial($user, $user->id);
473
+				}
924 474
 
925
-            if ($customer)
926
-            {
927
-                $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
928
-                $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
929
-            }
930
-
931
-            if ($supplier)
932
-            {
933
-                $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
934
-                $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
935
-            }
936
-            $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
937
-			$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
938
-			$sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'";
939
-            $sql .= " WHERE rowid = '" . $id ."'";
940
-
941
-            $resql=$this->db->query($sql);
942
-            if ($resql)
943
-            {
944
-            	unset($this->country_code);		// We clean this because it may have been changed after an update of country_id
945
-            	unset($this->country);
946
-            	unset($this->state_code);
947
-            	unset($this->state);
948
-
949
-            	$nbrowsaffected = $this->db->affected_rows($resql);
950
-
951
-            	if (! $error && $nbrowsaffected)
952
-            	{
953
-            		// Update information on linked member if it is an update
954
-	            	if (! $nosyncmember && ! empty($conf->adherent->enabled))
955
-	            	{
956
-		            	require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
957
-
958
-		            	dol_syslog(get_class($this)."::update update linked member");
959
-
960
-		            	$lmember=new Adherent($this->db);
961
-		            	$result=$lmember->fetch(0, 0, $this->id);
962
-
963
-		            	if ($result > 0)
964
-		            	{
965
-		            		$lmember->societe=$this->name;
966
-		            		//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
967
-		            		//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
968
-		            		$lmember->address=$this->address;
969
-		            		$lmember->email=$this->email;
970
-                    		$lmember->skype=$this->skype;
971
-		            		$lmember->phone=$this->phone;
972
-
973
-		            		$result=$lmember->update($user,0,1,1,1);	// Use nosync to 1 to avoid cyclic updates
974
-		            		if ($result < 0)
975
-		            		{
976
-		            			$this->error=$lmember->error;
977
-		            			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
978
-		            			$error++;
979
-		            		}
980
-		            	}
981
-		            	else if ($result < 0)
982
-		            	{
983
-		            		$this->error=$lmember->error;
984
-		            		$error++;
985
-		            	}
986
-	            	}
987
-            	}
988
-
989
-            	$action='update';
990
-
991
-                // Actions on extra fields (by external module or standard code)
992
-                // TODO le hook fait double emploi avec le trigger !!
993
-                $hookmanager->initHooks(array('thirdpartydao'));
994
-                $parameters=array('socid'=>$this->id);
995
-                $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
996
-                if (empty($reshook))
997
-                {
998
-                	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
999
-                	{
1000
-                		$result=$this->insertExtraFields();
1001
-                		if ($result < 0)
1002
-                		{
1003
-                			$error++;
1004
-                		}
1005
-                	}
1006
-                }
1007
-                else if ($reshook < 0) $error++;
1008
-
1009
-                if (! $error && $call_trigger)
1010
-                {
1011
-                    // Call trigger
1012
-                    $result=$this->call_trigger('COMPANY_MODIFY',$user);
1013
-                    if ($result < 0) $error++;
1014
-                    // End call triggers
1015
-                }
1016
-
1017
-                if (! $error)
1018
-                {
1019
-                    dol_syslog(get_class($this)."::Update success");
1020
-                    $this->db->commit();
1021
-                    return 1;
1022
-                }
1023
-                else
475
+				if ($ret >= 0)
1024 476
 				{
1025
-                    $this->db->rollback();
1026
-                    return -1;
1027
-                }
1028
-            }
1029
-            else
1030
-			{
1031
-                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1032
-                {
1033
-                    // Doublon
1034
-                    $this->error = $langs->trans("ErrorDuplicateField");
1035
-                    $result = -1;
1036
-                }
1037
-                else
1038
-                {
1039
-                    $this->error = $this->db->lasterror();
1040
-                    $result = -2;
1041
-                }
1042
-                $this->db->rollback();
1043
-                return $result;
1044
-            }
1045
-        }
1046
-        else
1047
-       {
1048
-            $this->db->rollback();
1049
-            dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
1050
-            return -3;
1051
-        }
1052
-    }
1053
-
1054
-    /**
1055
-     *    Load a third party from database into memory
1056
-     *
1057
-     *    @param	int		$rowid			Id of third party to load
1058
-     *    @param    string	$ref			Reference of third party, name (Warning, this can return several records)
1059
-     *    @param    string	$ref_ext       	External reference of third party (Warning, this information is a free field not provided by Dolibarr)
1060
-     *    @param    string	$ref_int       	Internal reference of third party (not used by dolibarr)
1061
-     *    @param    string	$idprof1		Prof id 1 of third party (Warning, this can return several records)
1062
-     *    @param    string	$idprof2		Prof id 2 of third party (Warning, this can return several records)
1063
-     *    @param    string	$idprof3		Prof id 3 of third party (Warning, this can return several records)
1064
-     *    @param    string	$idprof4		Prof id 4 of third party (Warning, this can return several records)
1065
-     *    @param    string	$idprof5		Prof id 5 of third party (Warning, this can return several records)
1066
-     *    @param    string	$idprof6		Prof id 6 of third party (Warning, this can return several records)
1067
-     *    @param    string	$email   		Email (Warning, this can return several records)
1068
-     *    @return   int						>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
1069
-     */
1070
-    function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='')
1071
-    {
1072
-        global $langs;
1073
-        global $conf;
1074
-
1075
-        if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1076
-
1077
-        $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1078
-        $sql .= ', s.status';
1079
-        $sql .= ', s.price_level';
1080
-        $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1081
-        $sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1082
-        $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1083
-        $sql .= ', s.capital, s.tva_intra';
1084
-        $sql .= ', s.fk_typent as typent_id';
1085
-        $sql .= ', s.fk_effectif as effectif_id';
1086
-        $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1087
-        $sql .= ', s.webservices_url, s.webservices_key';
1088
-        $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1089
-        $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
1090
-        $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
1091
-        $sql .= ', s.fk_shipping_method';
1092
-        $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1093
-		$sql .= ', s.fk_multicurrency, s.multicurrency_code';
1094
-        $sql .= ', fj.libelle as forme_juridique';
1095
-        $sql .= ', e.libelle as effectif';
1096
-        $sql .= ', c.code as country_code, c.label as country';
1097
-        $sql .= ', d.code_departement as state_code, d.nom as state';
1098
-        $sql .= ', st.libelle as stcomm';
1099
-        $sql .= ', te.code as typent_code';
1100
-		$sql .= ', i.libelle as libelle_incoterms';
1101
-        $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1102
-        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1103
-        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1104
-        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1105
-        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1106
-        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1107
-        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1108
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1109
-		$sql .= ' WHERE s.entity IN ('.getEntity($this->element, 1).')';
1110
-        if ($rowid)   $sql .= ' AND s.rowid = '.$rowid;
1111
-        if ($ref)     $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1112
-        if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1113
-        if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1114
-        if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1115
-        if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1116
-        if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1117
-        if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1118
-        if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1119
-        if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1120
-        if ($email)   $sql .= " AND email = '".$this->db->escape($email)."'";
1121
-
1122
-        $resql=$this->db->query($sql);
1123
-        if ($resql)
1124
-        {
1125
-            $num=$this->db->num_rows($resql);
1126
-            if ($num > 1)
1127
-            {
1128
-                $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1129
-                dol_syslog($this->error, LOG_ERR);
1130
-                $result = -2;
1131
-            }
1132
-            elseif ($num)   // $num = 1
1133
-            {
1134
-                $obj = $this->db->fetch_object($resql);
1135
-
1136
-                $this->id           = $obj->rowid;
1137
-                $this->entity       = $obj->entity;
1138
-                $this->canvas		= $obj->canvas;
1139
-
1140
-                $this->ref          = $obj->rowid;
1141
-                $this->name 		= $obj->name;
1142
-                $this->nom          = $obj->name;		// deprecated
1143
-	            $this->name_alias = $obj->name_alias;
1144
-                $this->ref_ext      = $obj->ref_ext;
1145
-                $this->ref_int      = $obj->ref_int;
1146
-
1147
-                $this->date_creation     = $this->db->jdate($obj->date_creation);
1148
-                $this->date_modification = $this->db->jdate($obj->date_modification);
1149
-                $this->user_creation     = $obj->fk_user_creat;
1150
-                $this->user_modification = $obj->fk_user_modif;
1151
-
1152
-                $this->address 		= $obj->address;
1153
-                $this->zip 			= $obj->zip;
1154
-                $this->town 		= $obj->town;
1155
-
1156
-                $this->country_id   = $obj->country_id;
1157
-                $this->country_code = $obj->country_id?$obj->country_code:'';
1158
-                $this->country 		= $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1159
-
1160
-                $this->state_id     = $obj->fk_departement;
1161
-                $this->state_code   = $obj->state_code;
1162
-                $this->state        = ($obj->state!='-'?$obj->state:'');
1163
-
1164
-                $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1165
-                $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1166
-                $this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
1167
-                $this->statut_commercial = $libelle;    // libelle statut commercial
1168
-
1169
-                $this->email = $obj->email;
1170
-                $this->skype = $obj->skype;
1171
-                $this->url = $obj->url;
1172
-                $this->phone = $obj->phone;
1173
-                $this->fax = $obj->fax;
1174
-
1175
-                $this->parent    = $obj->parent;
1176
-
1177
-                $this->idprof1		= $obj->idprof1;
1178
-                $this->idprof2		= $obj->idprof2;
1179
-                $this->idprof3		= $obj->idprof3;
1180
-                $this->idprof4		= $obj->idprof4;
1181
-                $this->idprof5		= $obj->idprof5;
1182
-                $this->idprof6		= $obj->idprof6;
1183
-
1184
-                $this->capital   = $obj->capital;
1185
-
1186
-                $this->code_client = $obj->code_client;
1187
-                $this->code_fournisseur = $obj->code_fournisseur;
1188
-
1189
-                $this->code_compta = $obj->code_compta;
1190
-                $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1191
-
1192
-                $this->barcode = $obj->barcode;
1193
-
1194
-                $this->tva_assuj      = $obj->tva_assuj;
1195
-                $this->tva_intra      = $obj->tva_intra;
1196
-                $this->status = $obj->status;
1197
-
1198
-                // Local Taxes
1199
-                $this->localtax1_assuj      = $obj->localtax1_assuj;
1200
-                $this->localtax2_assuj      = $obj->localtax2_assuj;
1201
-
1202
-                $this->localtax1_value		= $obj->localtax1_value;
1203
-                $this->localtax2_value		= $obj->localtax2_value;
1204
-
1205
-                $this->typent_id      = $obj->typent_id;
1206
-                $this->typent_code    = $obj->typent_code;
1207
-
1208
-                $this->effectif_id    = $obj->effectif_id;
1209
-                $this->effectif       = $obj->effectif_id?$obj->effectif:'';
1210
-
1211
-                $this->forme_juridique_code= $obj->forme_juridique_code;
1212
-                $this->forme_juridique     = $obj->forme_juridique_code?$obj->forme_juridique:'';
1213
-
1214
-                $this->fk_prospectlevel = $obj->fk_prospectlevel;
1215
-
1216
-                $this->prefix_comm = $obj->prefix_comm;
1217
-
1218
-                $this->remise_percent		= $obj->remise_client;
1219
-                $this->mode_reglement_id 	= $obj->mode_reglement;
1220
-                $this->cond_reglement_id 	= $obj->cond_reglement;
1221
-                $this->mode_reglement_supplier_id 	= $obj->mode_reglement_supplier;
1222
-                $this->cond_reglement_supplier_id 	= $obj->cond_reglement_supplier;
1223
-                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1224
-				$this->fk_account			= $obj->fk_account;
477
+					// Call trigger
478
+					$result=$this->call_trigger('COMPANY_CREATE',$user);
479
+					if ($result < 0) $error++;
480
+					// End call triggers
481
+				}
482
+				else $error++;
1225 483
 
1226
-                $this->client      = $obj->client;
1227
-                $this->fournisseur = $obj->fournisseur;
484
+				if (! $error)
485
+				{
486
+					dol_syslog(get_class($this)."::Create success id=".$this->id);
487
+					$this->db->commit();
488
+					return $this->id;
489
+				}
490
+				else
491
+				{
492
+					dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
493
+					$this->db->rollback();
494
+					return -4;
495
+				}
496
+			}
497
+			else
498
+			{
499
+				if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
500
+				{
501
+					$this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
502
+					$result=-1;
503
+				}
504
+				else
505
+				{
506
+					$this->error=$this->db->lasterror();
507
+					$result=-2;
508
+				}
509
+				$this->db->rollback();
510
+				return $result;
511
+			}
1228 512
 
1229
-                $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1230
-                $this->note_private = $obj->note_private;
1231
-                $this->note_public = $obj->note_public;
1232
-                $this->modelpdf = $obj->model_pdf;
1233
-                $this->default_lang = $obj->default_lang;
1234
-                $this->logo = $obj->logo;
513
+		}
514
+		else
515
+		{
516
+			$this->db->rollback();
517
+			dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
518
+			return -3;
519
+		}
520
+	}
1235 521
 
1236
-                $this->webservices_url = $obj->webservices_url;
1237
-                $this->webservices_key = $obj->webservices_key;
1238 522
 
1239
-                $this->outstanding_limit		= $obj->outstanding_limit;
523
+	/**
524
+	 * Create a contact/address from thirdparty
525
+	 *
526
+	 * @param 	User	$user		Object user
527
+	 * @return 	int					<0 if KO, >0 if OK
528
+	 */
529
+	function create_individual(User $user)
530
+	{
531
+		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
532
+		$contact=new Contact($this->db);
533
+
534
+		$contact->name              = $this->name_bis;
535
+		$contact->firstname         = $this->firstname;
536
+		$contact->civility_id       = $this->civility_id;
537
+		$contact->socid             = $this->id;	// fk_soc
538
+		$contact->statut            = 1;
539
+		$contact->priv              = 0;
540
+		$contact->country_id        = $this->country_id;
541
+		$contact->state_id          = $this->state_id;
542
+		$contact->address           = $this->address;
543
+		$contact->email             = $this->email;
544
+		$contact->zip               = $this->zip;
545
+		$contact->town              = $this->town;
546
+		$contact->phone_pro         = $this->phone;
547
+
548
+		$result = $contact->create($user);
549
+		if ($result < 0)
550
+		{
551
+			$this->error = $contact->error;
552
+			$this->errors = $contact->errors;
553
+			dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
554
+		}
1240 555
 
1241
-                // multiprix
1242
-                $this->price_level = $obj->price_level;
556
+		return $result;
557
+	}
1243 558
 
1244
-                $this->import_key = $obj->import_key;
559
+	/**
560
+	 *    Check properties of third party are ok (like name, third party codes, ...)
561
+	 *    Used before an add or update.
562
+	 *
563
+	 *    @return     int		0 if OK, <0 if KO
564
+	 */
565
+	function verify()
566
+	{
567
+		global $conf, $langs, $mysoc;
1245 568
 
1246
-				//Incoterms
1247
-				$this->fk_incoterms = $obj->fk_incoterms;
1248
-				$this->location_incoterms = $obj->location_incoterms;
1249
-				$this->libelle_incoterms = $obj->libelle_incoterms;
569
+		$error = 0;
570
+		$this->errors=array();
1250 571
 
1251
-				// multicurrency
1252
-				$this->fk_multicurrency = $obj->fk_multicurrency;
1253
-				$this->multicurrency_code = $obj->multicurrency_code;
572
+		$result = 0;
573
+		$this->name	= trim($this->name);
574
+		$this->nom=$this->name; // For backward compatibility
1254 575
 
1255
-                $result = 1;
576
+		if (! $this->name)
577
+		{
578
+			$this->errors[] = 'ErrorBadThirdPartyName';
579
+			$result = -2;
580
+		}
1256 581
 
1257
-                // Retreive all extrafield for thirdparty
1258
-               	$this->fetch_optionals();
1259
-            }
1260
-            else
582
+		if ($this->client)
583
+		{
584
+			$rescode = $this->check_codeclient();
585
+			if ($rescode <> 0)
1261 586
 			{
1262
-                $result = 0;
1263
-            }
587
+				if ($rescode == -1)
588
+				{
589
+					$this->errors[] = 'ErrorBadCustomerCodeSyntax';
590
+				}
591
+				if ($rescode == -2)
592
+				{
593
+					$this->errors[] = 'ErrorCustomerCodeRequired';
594
+				}
595
+				if ($rescode == -3)
596
+				{
597
+					$this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
598
+				}
599
+				if ($rescode == -4)
600
+				{
601
+					$this->errors[] = 'ErrorPrefixRequired';
602
+				}
603
+				$result = -3;
604
+			}
605
+		}
1264 606
 
1265
-            $this->db->free($resql);
1266
-        }
1267
-        else
607
+		if ($this->fournisseur)
1268 608
 		{
1269
-            $this->error=$this->db->lasterror();
1270
-            $result = -3;
1271
-        }
609
+			$rescode = $this->check_codefournisseur();
610
+			if ($rescode <> 0)
611
+			{
612
+				if ($rescode == -1)
613
+				{
614
+					$this->errors[] = 'ErrorBadSupplierCodeSyntax';
615
+				}
616
+				if ($rescode == -2)
617
+				{
618
+					$this->errors[] = 'ErrorSupplierCodeRequired';
619
+				}
620
+				if ($rescode == -3)
621
+				{
622
+					$this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
623
+				}
624
+				if ($rescode == -5)
625
+				{
626
+					$this->errors[] = 'ErrorprefixRequired';
627
+				}
628
+				$result = -3;
629
+			}
630
+		}
1272 631
 
1273
-        // Use first price level if level not defined for third party
1274
-        if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1275
-
1276
-        return $result;
1277
-    }
1278
-
1279
-    /**
1280
-     * 	Search and fetch thirparties by name
1281
-     *
1282
-     * 	@param		string		$name		Name
1283
-     * 	@param		int			$type		Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier)
1284
-     * 	@param		array		$filters	Array of couple field name/value to filter the companies with the same name
1285
-     * 	@param		boolean		$exact		Exact string search (true/false)
1286
-     * 	@param		boolean		$case		Case sensitive (true/false)
1287
-     * 	@param		boolean		$similar	Add test if string inside name into database, or name into database inside string. Do not use this: Not compatible with other database.
1288
-     * 	@param		string		$clause		Clause for filters
1289
-     * 	@return		array|int				<0 if KO, array of thirdparties object if OK
1290
-     */
1291
-    function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
1292
-    {
1293
-    	$thirdparties = array();
1294
-
1295
-    	dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact);
1296
-
1297
-    	// Check parameter
1298
-    	if (empty($name))
1299
-    	{
1300
-    		$this->errors[]='ErrorBadValueForParameter';
1301
-    		return -1;
1302
-    	}
1303
-
1304
-    	// Generation requete recherche
1305
-    	$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
1306
-    	$sql.= " WHERE entity IN (".getEntity('category').")";
1307
-    	if (! empty($type))
1308
-    	{
1309
-    		if ($type == 1 || $type == 2)
1310
-    			$sql.= " AND client = ".$type;
1311
-    		elseif ($type == 3)
1312
-    			$sql.= " AND fournisseur = 1";
1313
-    	}
1314
-    	if (! empty($name))
1315
-    	{
1316
-    		if (! $exact)
1317
-    		{
1318
-    			if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
1319
-    			{
1320
-    				$name = str_replace('*', '%', $name);
1321
-    			}
1322
-    			else
1323
-    			{
1324
-    				$name = '%'.$name.'%';
1325
-    			}
1326
-    		}
1327
-    		$sql.= " AND ";
1328
-    		if (is_array($filters) && ! empty($filters))
1329
-    			$sql.= "(";
1330
-    		if ($similar)
1331
-    		{
1332
-    			// For test similitude (string inside name into database, or name into database inside string)
1333
-    			// Do not use this. Not compatible with other database.
1334
-    			$sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
1335
-    		}
1336
-    		else
1337
-    		{
1338
-    			if (! $case)
1339
-    				$sql.= "nom LIKE '".$this->db->escape($name)."'";
1340
-    			else
1341
-    				$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
1342
-    		}
1343
-    	}
1344
-    	if (is_array($filters) && ! empty($filters))
1345
-    	{
1346
-    		foreach($filters as $field => $value)
1347
-    		{
1348
-    			if (! $exact)
1349
-    			{
1350
-    				if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
1351
-    				{
1352
-    					$value = str_replace('*', '%', $value);
1353
-    				}
1354
-    				else
1355
-    				{
1356
-    					$value = '%'.$value.'%';
1357
-    				}
1358
-    			}
1359
-    			if (! $case)
1360
-    				$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1361
-    			else
1362
-    				$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1363
-    		}
1364
-    		if (! empty($name))
1365
-    			$sql.= ")";
1366
-    	}
1367
-
1368
-    	$res  = $this->db->query($sql);
1369
-    	if ($res)
1370
-    	{
1371
-    		while ($rec = $this->db->fetch_array($res))
1372
-    		{
1373
-    			$soc = new Societe($this->db);
1374
-    			$soc->fetch($rec['rowid']);
1375
-    			$thirdparties[] = $soc;
1376
-    		}
1377
-
1378
-    		return $thirdparties;
1379
-    	}
1380
-    	else
1381
-    	{
1382
-    		$this->error=$this->db->lasterror();
1383
-    		return -1;
1384
-    	}
1385
-    }
1386
-
1387
-    /**
1388
-     *    Delete a third party from database and all its dependencies (contacts, rib...)
1389
-     *
1390
-     *    @param	int		$id             Id of third party to delete
1391
-     *    @param    User    $fuser          User who ask to delete thirparty
1392
-     *    @param    int		$call_trigger   0=No, 1=yes
1393
-     *    @return	int						<0 if KO, 0 if nothing done, >0 if OK
1394
-     */
1395
-    function delete($id, User $fuser=null, $call_trigger=1)
1396
-    {
1397
-        global $langs, $conf, $user;
1398
-
1399
-        if (empty($fuser)) $fuser=$user;
1400
-
1401
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1402
-
1403
-        $entity=isset($this->entity)?$this->entity:$conf->entity;
1404
-
1405
-        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1406
-        $error = 0;
1407
-
1408
-        // Test if child exists
1409
-        $objectisused = $this->isObjectUsed($id);
1410
-		if (empty($objectisused))
632
+		// Check for duplicate or mandatory fields defined into setup
633
+		$array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
634
+		foreach($array_to_check as $key)
1411 635
 		{
1412
-            $this->db->begin();
636
+			$keymin=strtolower($key);
637
+			$i=(int) preg_replace('/[^0-9]/','',$key);
638
+			$vallabel=$this->$keymin;
639
+
640
+			if ($i > 0)
641
+			{
642
+				if ($this->isACompany())
643
+				{
644
+					// Check for unicity
645
+					if ($vallabel && $this->id_prof_verifiable($i))
646
+					{
647
+						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
648
+						{
649
+							$langs->load("errors");
650
+							$error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
651
+						}
652
+					}
653
+
654
+					// Check for mandatory prof id (but only if country is other than ours)
655
+					if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
656
+					{
657
+						$idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
658
+						if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
659
+						{
660
+							$langs->load("errors");
661
+							$error++;
662
+							$this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
663
+						}
664
+					}
665
+				}
666
+			}
667
+			else
668
+			{
669
+				//var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
670
+				if ($key == 'EMAIL')
671
+				{
672
+					// Check for unicity
673
+					if ($vallabel)
674
+					{
675
+						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
676
+						{
677
+							$langs->load("errors");
678
+							$error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
679
+						}
680
+					}
681
+
682
+					// Check for mandatory
683
+					if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
684
+					{
685
+						$langs->load("errors");
686
+						$error++;
687
+						$this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
688
+					}
689
+				}
690
+			}
691
+		}
692
+
693
+		if ($error) $result = -4;
694
+
695
+		return $result;
696
+	}
697
+
698
+	/**
699
+	 *      Update parameters of third party
700
+	 *
701
+	 *      @param	int		$id              			id societe
702
+	 *      @param  User	$user            			Utilisateur qui demande la mise a jour
703
+	 *      @param  int		$call_trigger    			0=non, 1=oui
704
+	 *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
705
+	 *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
706
+	 *		@param	string	$action						'add' or 'update'
707
+	 *		@param	int		$nosyncmember				Do not synchronize info of linked member
708
+	 *      @return int  			           			<0 if KO, >=0 if OK
709
+	 */
710
+	function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
711
+	{
712
+		global $langs,$conf,$hookmanager;
713
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
714
+
715
+		$error=0;
716
+
717
+		dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
718
+
719
+		$now=dol_now();
720
+
721
+		// Clean parameters
722
+		$this->id			= $id;
723
+		$this->name			= $this->name?trim($this->name):trim($this->nom);
724
+		$this->nom			= $this->name;	// For backward compatibility
725
+		$this->name_alias = trim($this->name_alias);
726
+		$this->ref_ext		= trim($this->ref_ext);
727
+		$this->address		= $this->address?trim($this->address):trim($this->address);
728
+		$this->zip			= $this->zip?trim($this->zip):trim($this->zip);
729
+		$this->town			= $this->town?trim($this->town):trim($this->town);
730
+		$this->state_id		= trim($this->state_id);
731
+		$this->country_id	= ($this->country_id > 0)?$this->country_id:0;
732
+		$this->phone		= trim($this->phone);
733
+		$this->phone		= preg_replace("/\s/","",$this->phone);
734
+		$this->phone		= preg_replace("/\./","",$this->phone);
735
+		$this->fax			= trim($this->fax);
736
+		$this->fax			= preg_replace("/\s/","",$this->fax);
737
+		$this->fax			= preg_replace("/\./","",$this->fax);
738
+		$this->email		= trim($this->email);
739
+		$this->skype		= trim($this->skype);
740
+		$this->url			= $this->url?clean_url($this->url,0):'';
741
+		$this->idprof1		= trim($this->idprof1);
742
+		$this->idprof2		= trim($this->idprof2);
743
+		$this->idprof3		= trim($this->idprof3);
744
+		$this->idprof4		= trim($this->idprof4);
745
+		$this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
746
+		$this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
747
+		$this->prefix_comm	= trim($this->prefix_comm);
748
+		$this->outstanding_limit = price2num($this->outstanding_limit);
749
+
750
+		$this->tva_assuj	= trim($this->tva_assuj);
751
+		$this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
752
+		if (empty($this->status)) $this->status = 0;
753
+
754
+		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
755
+		if (empty($this->fk_multicurrency))
756
+		{
757
+			$this->multicurrency_code = '';
758
+			$this->fk_multicurrency = 0;
759
+		}
760
+
761
+		// Local taxes
762
+		$this->localtax1_assuj=trim($this->localtax1_assuj);
763
+		$this->localtax2_assuj=trim($this->localtax2_assuj);
764
+
765
+		$this->localtax1_value=trim($this->localtax1_value);
766
+		$this->localtax2_value=trim($this->localtax2_value);
767
+
768
+		if ($this->capital != '') $this->capital=price2num(trim($this->capital));
769
+		if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
770
+
771
+		$this->effectif_id=trim($this->effectif_id);
772
+		$this->forme_juridique_code=trim($this->forme_juridique_code);
773
+
774
+		//Gencod
775
+		$this->barcode=trim($this->barcode);
776
+
777
+		// For automatic creation
778
+		if ($this->code_client == -1) $this->get_codeclient($this,0);
779
+		if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
780
+
781
+		$this->code_compta=trim($this->code_compta);
782
+		$this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
783
+
784
+		// Check parameters. More tests are done later in the ->verify()
785
+		if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
786
+		{
787
+			$langs->load("errors");
788
+			$this->error = $langs->trans("BadValueForParameterClientOrSupplier");
789
+			return -1;
790
+		}
791
+
792
+		$customer=false;
793
+		if (! empty($allowmodcodeclient) && ! empty($this->client))
794
+		{
795
+			// Attention get_codecompta peut modifier le code suivant le module utilise
796
+			if (empty($this->code_compta))
797
+			{
798
+				$ret=$this->get_codecompta('customer');
799
+				if ($ret < 0) return -1;
800
+			}
801
+
802
+			$customer=true;
803
+		}
804
+
805
+		$supplier=false;
806
+		if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
807
+		{
808
+			// Attention get_codecompta peut modifier le code suivant le module utilise
809
+			if (empty($this->code_compta_fournisseur))
810
+			{
811
+				$ret=$this->get_codecompta('supplier');
812
+				if ($ret < 0) return -1;
813
+			}
814
+
815
+			$supplier=true;
816
+		}
817
+
818
+		//Web services
819
+		$this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
820
+		$this->webservices_key = trim($this->webservices_key);
821
+
822
+		//Incoterms
823
+		$this->fk_incoterms = (int) $this->fk_incoterms;
824
+		$this->location_incoterms = trim($this->location_incoterms);
825
+
826
+		$this->db->begin();
827
+
828
+		// Check name is required and codes are ok or unique.
829
+		// If error, this->errors[] is filled
830
+		$result = 0;
831
+		if ($action != 'add') $result = $this->verify();	// We don't check when update called during a create because verify was already done
832
+
833
+		if ($result >= 0)
834
+		{
835
+			dol_syslog(get_class($this)."::update verify ok or not done");
836
+
837
+			$sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
838
+			$sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
839
+			$sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
840
+			$sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
841
+			$sql .= ",address = '" . $this->db->escape($this->address) ."'";
842
+
843
+			$sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
844
+			$sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
845
+
846
+			$sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
847
+			$sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
848
+
849
+			$sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
850
+			$sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
851
+			$sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
852
+			$sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
853
+			$sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
854
+
855
+			$sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
856
+			$sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
857
+			$sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
858
+			$sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
859
+			$sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
860
+			$sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
861
+
862
+			$sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
863
+			$sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
864
+			$sql .= ",status = " .$this->status;
865
+
866
+			// Local taxes
867
+			$sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
868
+			$sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
869
+			if($this->localtax1_assuj==1)
870
+			{
871
+				if($this->localtax1_value!='')
872
+				{
873
+					$sql .=",localtax1_value =".$this->localtax1_value;
874
+				}
875
+				else $sql .=",localtax1_value =0.000";
876
+
877
+			}
878
+			else $sql .=",localtax1_value =0.000";
879
+
880
+			if($this->localtax2_assuj==1)
881
+			{
882
+				if($this->localtax2_value!='')
883
+				{
884
+					$sql .=",localtax2_value =".$this->localtax2_value;
885
+				}
886
+				else $sql .=",localtax2_value =0.000";
887
+
888
+			}
889
+			else $sql .=",localtax2_value =0.000";
890
+
891
+			$sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
892
+
893
+			$sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
894
+
895
+			$sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
896
+			if (isset($this->stcomm_id))
897
+			{
898
+				$sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? $this->stcomm_id : "0");
899
+			}
900
+			$sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
901
+
902
+			$sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
903
+
904
+			$sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
905
+			$sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
906
+			$sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
907
+			$sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
908
+			$sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
909
+
910
+			$sql .= ",client = " . (! empty($this->client)?$this->client:0);
911
+			$sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
912
+			$sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
913
+			$sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
914
+			$sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
915
+			$sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
916
+			$sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
917
+
918
+			$sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
919
+			$sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
920
+
921
+			//Incoterms
922
+			$sql.= ", fk_incoterms = ".$this->fk_incoterms;
923
+			$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
924
+
925
+			if ($customer)
926
+			{
927
+				$sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
928
+				$sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
929
+			}
930
+
931
+			if ($supplier)
932
+			{
933
+				$sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
934
+				$sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
935
+			}
936
+			$sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
937
+			$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
938
+			$sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'";
939
+			$sql .= " WHERE rowid = '" . $id ."'";
940
+
941
+			$resql=$this->db->query($sql);
942
+			if ($resql)
943
+			{
944
+				unset($this->country_code);		// We clean this because it may have been changed after an update of country_id
945
+				unset($this->country);
946
+				unset($this->state_code);
947
+				unset($this->state);
948
+
949
+				$nbrowsaffected = $this->db->affected_rows($resql);
950
+
951
+				if (! $error && $nbrowsaffected)
952
+				{
953
+					// Update information on linked member if it is an update
954
+					if (! $nosyncmember && ! empty($conf->adherent->enabled))
955
+					{
956
+						require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
957
+
958
+						dol_syslog(get_class($this)."::update update linked member");
959
+
960
+						$lmember=new Adherent($this->db);
961
+						$result=$lmember->fetch(0, 0, $this->id);
962
+
963
+						if ($result > 0)
964
+						{
965
+							$lmember->societe=$this->name;
966
+							//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
967
+							//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
968
+							$lmember->address=$this->address;
969
+							$lmember->email=$this->email;
970
+							$lmember->skype=$this->skype;
971
+							$lmember->phone=$this->phone;
972
+
973
+							$result=$lmember->update($user,0,1,1,1);	// Use nosync to 1 to avoid cyclic updates
974
+							if ($result < 0)
975
+							{
976
+								$this->error=$lmember->error;
977
+								dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
978
+								$error++;
979
+							}
980
+						}
981
+						else if ($result < 0)
982
+						{
983
+							$this->error=$lmember->error;
984
+							$error++;
985
+						}
986
+					}
987
+				}
988
+
989
+				$action='update';
990
+
991
+				// Actions on extra fields (by external module or standard code)
992
+				// TODO le hook fait double emploi avec le trigger !!
993
+				$hookmanager->initHooks(array('thirdpartydao'));
994
+				$parameters=array('socid'=>$this->id);
995
+				$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
996
+				if (empty($reshook))
997
+				{
998
+					if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
999
+					{
1000
+						$result=$this->insertExtraFields();
1001
+						if ($result < 0)
1002
+						{
1003
+							$error++;
1004
+						}
1005
+					}
1006
+				}
1007
+				else if ($reshook < 0) $error++;
1008
+
1009
+				if (! $error && $call_trigger)
1010
+				{
1011
+					// Call trigger
1012
+					$result=$this->call_trigger('COMPANY_MODIFY',$user);
1013
+					if ($result < 0) $error++;
1014
+					// End call triggers
1015
+				}
1016
+
1017
+				if (! $error)
1018
+				{
1019
+					dol_syslog(get_class($this)."::Update success");
1020
+					$this->db->commit();
1021
+					return 1;
1022
+				}
1023
+				else
1024
+				{
1025
+					$this->db->rollback();
1026
+					return -1;
1027
+				}
1028
+			}
1029
+			else
1030
+			{
1031
+				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1032
+				{
1033
+					// Doublon
1034
+					$this->error = $langs->trans("ErrorDuplicateField");
1035
+					$result = -1;
1036
+				}
1037
+				else
1038
+				{
1039
+					$this->error = $this->db->lasterror();
1040
+					$result = -2;
1041
+				}
1042
+				$this->db->rollback();
1043
+				return $result;
1044
+			}
1045
+		}
1046
+		else
1047
+	   {
1048
+			$this->db->rollback();
1049
+			dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
1050
+			return -3;
1051
+		}
1052
+	}
1053
+
1054
+	/**
1055
+	 *    Load a third party from database into memory
1056
+	 *
1057
+	 *    @param	int		$rowid			Id of third party to load
1058
+	 *    @param    string	$ref			Reference of third party, name (Warning, this can return several records)
1059
+	 *    @param    string	$ref_ext       	External reference of third party (Warning, this information is a free field not provided by Dolibarr)
1060
+	 *    @param    string	$ref_int       	Internal reference of third party (not used by dolibarr)
1061
+	 *    @param    string	$idprof1		Prof id 1 of third party (Warning, this can return several records)
1062
+	 *    @param    string	$idprof2		Prof id 2 of third party (Warning, this can return several records)
1063
+	 *    @param    string	$idprof3		Prof id 3 of third party (Warning, this can return several records)
1064
+	 *    @param    string	$idprof4		Prof id 4 of third party (Warning, this can return several records)
1065
+	 *    @param    string	$idprof5		Prof id 5 of third party (Warning, this can return several records)
1066
+	 *    @param    string	$idprof6		Prof id 6 of third party (Warning, this can return several records)
1067
+	 *    @param    string	$email   		Email (Warning, this can return several records)
1068
+	 *    @return   int						>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
1069
+	 */
1070
+	function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='')
1071
+	{
1072
+		global $langs;
1073
+		global $conf;
1074
+
1075
+		if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1076
+
1077
+		$sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1078
+		$sql .= ', s.status';
1079
+		$sql .= ', s.price_level';
1080
+		$sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1081
+		$sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1082
+		$sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1083
+		$sql .= ', s.capital, s.tva_intra';
1084
+		$sql .= ', s.fk_typent as typent_id';
1085
+		$sql .= ', s.fk_effectif as effectif_id';
1086
+		$sql .= ', s.fk_forme_juridique as forme_juridique_code';
1087
+		$sql .= ', s.webservices_url, s.webservices_key';
1088
+		$sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1089
+		$sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
1090
+		$sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
1091
+		$sql .= ', s.fk_shipping_method';
1092
+		$sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1093
+		$sql .= ', s.fk_multicurrency, s.multicurrency_code';
1094
+		$sql .= ', fj.libelle as forme_juridique';
1095
+		$sql .= ', e.libelle as effectif';
1096
+		$sql .= ', c.code as country_code, c.label as country';
1097
+		$sql .= ', d.code_departement as state_code, d.nom as state';
1098
+		$sql .= ', st.libelle as stcomm';
1099
+		$sql .= ', te.code as typent_code';
1100
+		$sql .= ', i.libelle as libelle_incoterms';
1101
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1102
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1103
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1104
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1105
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1106
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1107
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1108
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1109
+		$sql .= ' WHERE s.entity IN ('.getEntity($this->element, 1).')';
1110
+		if ($rowid)   $sql .= ' AND s.rowid = '.$rowid;
1111
+		if ($ref)     $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1112
+		if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1113
+		if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1114
+		if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1115
+		if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1116
+		if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1117
+		if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1118
+		if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1119
+		if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1120
+		if ($email)   $sql .= " AND email = '".$this->db->escape($email)."'";
1121
+
1122
+		$resql=$this->db->query($sql);
1123
+		if ($resql)
1124
+		{
1125
+			$num=$this->db->num_rows($resql);
1126
+			if ($num > 1)
1127
+			{
1128
+				$this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1129
+				dol_syslog($this->error, LOG_ERR);
1130
+				$result = -2;
1131
+			}
1132
+			elseif ($num)   // $num = 1
1133
+			{
1134
+				$obj = $this->db->fetch_object($resql);
1135
+
1136
+				$this->id           = $obj->rowid;
1137
+				$this->entity       = $obj->entity;
1138
+				$this->canvas		= $obj->canvas;
1139
+
1140
+				$this->ref          = $obj->rowid;
1141
+				$this->name 		= $obj->name;
1142
+				$this->nom          = $obj->name;		// deprecated
1143
+				$this->name_alias = $obj->name_alias;
1144
+				$this->ref_ext      = $obj->ref_ext;
1145
+				$this->ref_int      = $obj->ref_int;
1146
+
1147
+				$this->date_creation     = $this->db->jdate($obj->date_creation);
1148
+				$this->date_modification = $this->db->jdate($obj->date_modification);
1149
+				$this->user_creation     = $obj->fk_user_creat;
1150
+				$this->user_modification = $obj->fk_user_modif;
1151
+
1152
+				$this->address 		= $obj->address;
1153
+				$this->zip 			= $obj->zip;
1154
+				$this->town 		= $obj->town;
1155
+
1156
+				$this->country_id   = $obj->country_id;
1157
+				$this->country_code = $obj->country_id?$obj->country_code:'';
1158
+				$this->country 		= $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1159
+
1160
+				$this->state_id     = $obj->fk_departement;
1161
+				$this->state_code   = $obj->state_code;
1162
+				$this->state        = ($obj->state!='-'?$obj->state:'');
1163
+
1164
+				$transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1165
+				$libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1166
+				$this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
1167
+				$this->statut_commercial = $libelle;    // libelle statut commercial
1168
+
1169
+				$this->email = $obj->email;
1170
+				$this->skype = $obj->skype;
1171
+				$this->url = $obj->url;
1172
+				$this->phone = $obj->phone;
1173
+				$this->fax = $obj->fax;
1174
+
1175
+				$this->parent    = $obj->parent;
1176
+
1177
+				$this->idprof1		= $obj->idprof1;
1178
+				$this->idprof2		= $obj->idprof2;
1179
+				$this->idprof3		= $obj->idprof3;
1180
+				$this->idprof4		= $obj->idprof4;
1181
+				$this->idprof5		= $obj->idprof5;
1182
+				$this->idprof6		= $obj->idprof6;
1183
+
1184
+				$this->capital   = $obj->capital;
1185
+
1186
+				$this->code_client = $obj->code_client;
1187
+				$this->code_fournisseur = $obj->code_fournisseur;
1188
+
1189
+				$this->code_compta = $obj->code_compta;
1190
+				$this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1191
+
1192
+				$this->barcode = $obj->barcode;
1193
+
1194
+				$this->tva_assuj      = $obj->tva_assuj;
1195
+				$this->tva_intra      = $obj->tva_intra;
1196
+				$this->status = $obj->status;
1197
+
1198
+				// Local Taxes
1199
+				$this->localtax1_assuj      = $obj->localtax1_assuj;
1200
+				$this->localtax2_assuj      = $obj->localtax2_assuj;
1201
+
1202
+				$this->localtax1_value		= $obj->localtax1_value;
1203
+				$this->localtax2_value		= $obj->localtax2_value;
1204
+
1205
+				$this->typent_id      = $obj->typent_id;
1206
+				$this->typent_code    = $obj->typent_code;
1207
+
1208
+				$this->effectif_id    = $obj->effectif_id;
1209
+				$this->effectif       = $obj->effectif_id?$obj->effectif:'';
1210
+
1211
+				$this->forme_juridique_code= $obj->forme_juridique_code;
1212
+				$this->forme_juridique     = $obj->forme_juridique_code?$obj->forme_juridique:'';
1213
+
1214
+				$this->fk_prospectlevel = $obj->fk_prospectlevel;
1215
+
1216
+				$this->prefix_comm = $obj->prefix_comm;
1217
+
1218
+				$this->remise_percent		= $obj->remise_client;
1219
+				$this->mode_reglement_id 	= $obj->mode_reglement;
1220
+				$this->cond_reglement_id 	= $obj->cond_reglement;
1221
+				$this->mode_reglement_supplier_id 	= $obj->mode_reglement_supplier;
1222
+				$this->cond_reglement_supplier_id 	= $obj->cond_reglement_supplier;
1223
+				$this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1224
+				$this->fk_account			= $obj->fk_account;
1225
+
1226
+				$this->client      = $obj->client;
1227
+				$this->fournisseur = $obj->fournisseur;
1228
+
1229
+				$this->note = $obj->note_private; // TODO Deprecated for backward comtability
1230
+				$this->note_private = $obj->note_private;
1231
+				$this->note_public = $obj->note_public;
1232
+				$this->modelpdf = $obj->model_pdf;
1233
+				$this->default_lang = $obj->default_lang;
1234
+				$this->logo = $obj->logo;
1235
+
1236
+				$this->webservices_url = $obj->webservices_url;
1237
+				$this->webservices_key = $obj->webservices_key;
1238
+
1239
+				$this->outstanding_limit		= $obj->outstanding_limit;
1240
+
1241
+				// multiprix
1242
+				$this->price_level = $obj->price_level;
1243
+
1244
+				$this->import_key = $obj->import_key;
1245
+
1246
+				//Incoterms
1247
+				$this->fk_incoterms = $obj->fk_incoterms;
1248
+				$this->location_incoterms = $obj->location_incoterms;
1249
+				$this->libelle_incoterms = $obj->libelle_incoterms;
1250
+
1251
+				// multicurrency
1252
+				$this->fk_multicurrency = $obj->fk_multicurrency;
1253
+				$this->multicurrency_code = $obj->multicurrency_code;
1254
+
1255
+				$result = 1;
1256
+
1257
+				// Retreive all extrafield for thirdparty
1258
+			   	$this->fetch_optionals();
1259
+			}
1260
+			else
1261
+			{
1262
+				$result = 0;
1263
+			}
1264
+
1265
+			$this->db->free($resql);
1266
+		}
1267
+		else
1268
+		{
1269
+			$this->error=$this->db->lasterror();
1270
+			$result = -3;
1271
+		}
1272
+
1273
+		// Use first price level if level not defined for third party
1274
+		if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1275
+
1276
+		return $result;
1277
+	}
1278
+
1279
+	/**
1280
+	 * 	Search and fetch thirparties by name
1281
+	 *
1282
+	 * 	@param		string		$name		Name
1283
+	 * 	@param		int			$type		Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier)
1284
+	 * 	@param		array		$filters	Array of couple field name/value to filter the companies with the same name
1285
+	 * 	@param		boolean		$exact		Exact string search (true/false)
1286
+	 * 	@param		boolean		$case		Case sensitive (true/false)
1287
+	 * 	@param		boolean		$similar	Add test if string inside name into database, or name into database inside string. Do not use this: Not compatible with other database.
1288
+	 * 	@param		string		$clause		Clause for filters
1289
+	 * 	@return		array|int				<0 if KO, array of thirdparties object if OK
1290
+	 */
1291
+	function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
1292
+	{
1293
+		$thirdparties = array();
1294
+
1295
+		dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact);
1296
+
1297
+		// Check parameter
1298
+		if (empty($name))
1299
+		{
1300
+			$this->errors[]='ErrorBadValueForParameter';
1301
+			return -1;
1302
+		}
1303
+
1304
+		// Generation requete recherche
1305
+		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
1306
+		$sql.= " WHERE entity IN (".getEntity('category').")";
1307
+		if (! empty($type))
1308
+		{
1309
+			if ($type == 1 || $type == 2)
1310
+				$sql.= " AND client = ".$type;
1311
+			elseif ($type == 3)
1312
+				$sql.= " AND fournisseur = 1";
1313
+		}
1314
+		if (! empty($name))
1315
+		{
1316
+			if (! $exact)
1317
+			{
1318
+				if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
1319
+				{
1320
+					$name = str_replace('*', '%', $name);
1321
+				}
1322
+				else
1323
+				{
1324
+					$name = '%'.$name.'%';
1325
+				}
1326
+			}
1327
+			$sql.= " AND ";
1328
+			if (is_array($filters) && ! empty($filters))
1329
+				$sql.= "(";
1330
+			if ($similar)
1331
+			{
1332
+				// For test similitude (string inside name into database, or name into database inside string)
1333
+				// Do not use this. Not compatible with other database.
1334
+				$sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
1335
+			}
1336
+			else
1337
+			{
1338
+				if (! $case)
1339
+					$sql.= "nom LIKE '".$this->db->escape($name)."'";
1340
+				else
1341
+					$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
1342
+			}
1343
+		}
1344
+		if (is_array($filters) && ! empty($filters))
1345
+		{
1346
+			foreach($filters as $field => $value)
1347
+			{
1348
+				if (! $exact)
1349
+				{
1350
+					if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
1351
+					{
1352
+						$value = str_replace('*', '%', $value);
1353
+					}
1354
+					else
1355
+					{
1356
+						$value = '%'.$value.'%';
1357
+					}
1358
+				}
1359
+				if (! $case)
1360
+					$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1361
+				else
1362
+					$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1363
+			}
1364
+			if (! empty($name))
1365
+				$sql.= ")";
1366
+		}
1367
+
1368
+		$res  = $this->db->query($sql);
1369
+		if ($res)
1370
+		{
1371
+			while ($rec = $this->db->fetch_array($res))
1372
+			{
1373
+				$soc = new Societe($this->db);
1374
+				$soc->fetch($rec['rowid']);
1375
+				$thirdparties[] = $soc;
1376
+			}
1377
+
1378
+			return $thirdparties;
1379
+		}
1380
+		else
1381
+		{
1382
+			$this->error=$this->db->lasterror();
1383
+			return -1;
1384
+		}
1385
+	}
1386
+
1387
+	/**
1388
+	 *    Delete a third party from database and all its dependencies (contacts, rib...)
1389
+	 *
1390
+	 *    @param	int		$id             Id of third party to delete
1391
+	 *    @param    User    $fuser          User who ask to delete thirparty
1392
+	 *    @param    int		$call_trigger   0=No, 1=yes
1393
+	 *    @return	int						<0 if KO, 0 if nothing done, >0 if OK
1394
+	 */
1395
+	function delete($id, User $fuser=null, $call_trigger=1)
1396
+	{
1397
+		global $langs, $conf, $user;
1398
+
1399
+		if (empty($fuser)) $fuser=$user;
1400
+
1401
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1402
+
1403
+		$entity=isset($this->entity)?$this->entity:$conf->entity;
1404
+
1405
+		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1406
+		$error = 0;
1407
+
1408
+		// Test if child exists
1409
+		$objectisused = $this->isObjectUsed($id);
1410
+		if (empty($objectisused))
1411
+		{
1412
+			$this->db->begin();
1413
+
1414
+			// User is mandatory for trigger call
1415
+			if (! $error && $call_trigger)
1416
+			{
1417
+				// Call trigger
1418
+				$result=$this->call_trigger('COMPANY_DELETE',$fuser);
1419
+				if ($result < 0) $error++;
1420
+				// End call triggers
1421
+			}
1422
+
1423
+			if (! $error)
1424
+			{
1425
+				require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1426
+				$static_cat = new Categorie($this->db);
1427
+				$toute_categs = array();
1428
+
1429
+				// Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1430
+				if ($this->client || $this->prospect)
1431
+				{
1432
+					$toute_categs['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
1433
+				}
1434
+				if ($this->fournisseur)
1435
+				{
1436
+					$toute_categs['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
1437
+				}
1438
+
1439
+				// Remove each "Categorie"
1440
+				foreach ($toute_categs as $type => $categs_type)
1441
+				{
1442
+					foreach ($categs_type as $cat)
1443
+					{
1444
+						$cat->del_type($this, $type);
1445
+					}
1446
+				}
1447
+			}
1448
+
1449
+			foreach ($this->childtablesoncascade as $tabletodelete)
1450
+			{
1451
+				if (! $error)
1452
+				{
1453
+					$sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1454
+					$sql.= " WHERE fk_soc = " . $id;
1455
+					if (! $this->db->query($sql))
1456
+					{
1457
+						$error++;
1458
+						$this->errors[] = $this->db->lasterror();
1459
+					}
1460
+				}
1461
+			}
1462
+
1463
+			// Removed extrafields
1464
+			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1465
+			{
1466
+				$result=$this->deleteExtraFields();
1467
+				if ($result < 0)
1468
+				{
1469
+					$error++;
1470
+					dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1471
+				}
1472
+			}
1473
+
1474
+			// Remove third party
1475
+			if (! $error)
1476
+			{
1477
+				$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1478
+				$sql.= " WHERE rowid = " . $id;
1479
+				if (! $this->db->query($sql))
1480
+				{
1481
+					$error++;
1482
+					$this->errors[] = $this->db->lasterror();
1483
+				}
1484
+			}
1485
+
1486
+			if (! $error)
1487
+			{
1488
+				$this->db->commit();
1489
+
1490
+				// Delete directory
1491
+				if (! empty($conf->societe->multidir_output[$entity]))
1492
+				{
1493
+					$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1494
+					if (dol_is_dir($docdir))
1495
+					{
1496
+						dol_delete_dir_recursive($docdir);
1497
+					}
1498
+				}
1499
+
1500
+				return 1;
1501
+			}
1502
+			else
1503
+			{
1504
+				dol_syslog($this->error, LOG_ERR);
1505
+				$this->db->rollback();
1506
+				return -1;
1507
+			}
1508
+		}
1509
+		else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1510
+		return 0;
1511
+	}
1512
+
1513
+	/**
1514
+	 *  Define third party as a customer
1515
+	 *
1516
+	 *	@return		int		<0 if KO, >0 if OK
1517
+	 */
1518
+	function set_as_client()
1519
+	{
1520
+		if ($this->id)
1521
+		{
1522
+			$newclient=1;
1523
+			if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1524
+			$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1525
+			$sql.= " SET client = ".$newclient;
1526
+			$sql.= " WHERE rowid = " . $this->id;
1527
+
1528
+			$resql=$this->db->query($sql);
1529
+			if ($resql)
1530
+			{
1531
+				$this->client = $newclient;
1532
+				return 1;
1533
+			}
1534
+			else return -1;
1535
+		}
1536
+		return 0;
1537
+	}
1538
+
1539
+	/**
1540
+	 *  Definit la societe comme un client
1541
+	 *
1542
+	 *  @param	float	$remise		Valeur en % de la remise
1543
+	 *  @param  string	$note		Note/Motif de modification de la remise
1544
+	 *  @param  User	$user		Utilisateur qui definie la remise
1545
+	 *	@return	int					<0 if KO, >0 if OK
1546
+	 */
1547
+	function set_remise_client($remise, $note, User $user)
1548
+	{
1549
+		global $conf, $langs;
1550
+
1551
+		// Nettoyage parametres
1552
+		$note=trim($note);
1553
+		if (! $note)
1554
+		{
1555
+			$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1556
+			return -2;
1557
+		}
1558
+
1559
+		dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1560
+
1561
+		if ($this->id)
1562
+		{
1563
+			$this->db->begin();
1564
+
1565
+			$now=dol_now();
1566
+
1567
+			// Positionne remise courante
1568
+			$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1569
+			$sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1570
+			$sql.= " WHERE rowid = " . $this->id;
1571
+			$resql=$this->db->query($sql);
1572
+			if (! $resql)
1573
+			{
1574
+				$this->db->rollback();
1575
+				$this->error=$this->db->error();
1576
+				return -1;
1577
+			}
1578
+
1579
+			// Ecrit trace dans historique des remises
1580
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1581
+			$sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1582
+			$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1583
+			$sql.= " '".$this->db->escape($note)."',";
1584
+			$sql.= " ".$user->id;
1585
+			$sql.= ")";
1586
+
1587
+			$resql=$this->db->query($sql);
1588
+			if (! $resql)
1589
+			{
1590
+				$this->db->rollback();
1591
+				$this->error=$this->db->lasterror();
1592
+				return -1;
1593
+			}
1594
+
1595
+			$this->db->commit();
1596
+			return 1;
1597
+		}
1598
+	}
1599
+
1600
+	/**
1601
+	 *    	Add a discount for third party
1602
+	 *
1603
+	 *    	@param	float	$remise     Amount of discount
1604
+	 *    	@param  User	$user       User adding discount
1605
+	 *    	@param  string	$desc		Reason of discount
1606
+	 *      @param  float	$tva_tx     VAT rate
1607
+	 *		@return	int					<0 if KO, id of discount record if OK
1608
+	 */
1609
+	function set_remise_except($remise, User $user, $desc, $tva_tx=0)
1610
+	{
1611
+		global $langs;
1612
+
1613
+		// Clean parameters
1614
+		$remise = price2num($remise);
1615
+		$desc = trim($desc);
1616
+
1617
+		// Check parameters
1618
+		if (! $remise > 0)
1619
+		{
1620
+			$this->error=$langs->trans("ErrorWrongValueForParameter","1");
1621
+			return -1;
1622
+		}
1623
+		if (! $desc)
1624
+		{
1625
+			$this->error=$langs->trans("ErrorWrongValueForParameter","3");
1626
+			return -2;
1627
+		}
1628
+
1629
+		if ($this->id)
1630
+		{
1631
+			require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1632
+
1633
+			$discount = new DiscountAbsolute($this->db);
1634
+			$discount->fk_soc=$this->id;
1635
+			$discount->amount_ht=price2num($remise,'MT');
1636
+			$discount->amount_tva=price2num($remise*$tva_tx/100,'MT');
1637
+			$discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
1638
+			$discount->tva_tx=price2num($tva_tx,'MT');
1639
+			$discount->description=$desc;
1640
+			$result=$discount->create($user);
1641
+			if ($result > 0)
1642
+			{
1643
+				return $result;
1644
+			}
1645
+			else
1646
+			{
1647
+				$this->error=$discount->error;
1648
+				return -3;
1649
+			}
1650
+		}
1651
+		else return 0;
1652
+	}
1653
+
1654
+	/**
1655
+	 *  Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
1656
+	 *
1657
+	 *	@param	User	$user		Filtre sur un user auteur des remises
1658
+	 * 	@param	string	$filter		Filtre autre
1659
+	 * 	@param	integer	$maxvalue	Filter on max value for discount
1660
+	 *	@return	int					<0 if KO, Credit note amount otherwise
1661
+	 */
1662
+	function getAvailableDiscounts($user='',$filter='',$maxvalue=0)
1663
+	{
1664
+		require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1665
+
1666
+		$discountstatic=new DiscountAbsolute($this->db);
1667
+		$result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue);
1668
+		if ($result >= 0)
1669
+		{
1670
+			return $result;
1671
+		}
1672
+		else
1673
+		{
1674
+			$this->error=$discountstatic->error;
1675
+			return -1;
1676
+		}
1677
+	}
1678
+
1679
+	/**
1680
+	 *  Return array of sales representatives
1681
+	 *
1682
+	 *  @param	User	$user		Object user
1683
+	 *  @return array       		Array of sales representatives of third party
1684
+	 */
1685
+	function getSalesRepresentatives(User $user)
1686
+	{
1687
+		global $conf;
1688
+
1689
+		$reparray=array();
1690
+
1691
+		$sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1692
+		$sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1693
+		if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1694
+		{
1695
+			$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1696
+			$sql.= " WHERE ((ug.fk_user = sc.fk_user";
1697
+			$sql.= " AND ug.entity = ".$conf->entity.")";
1698
+			$sql.= " OR u.admin = 1)";
1699
+		}
1700
+		else
1701
+			$sql.= " WHERE entity in (0, ".$conf->entity.")";
1702
+
1703
+		$sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1704
+
1705
+		$resql = $this->db->query($sql);
1706
+		if ($resql)
1707
+		{
1708
+			$num = $this->db->num_rows($resql);
1709
+			$i=0;
1710
+			while ($i < $num)
1711
+			{
1712
+				$obj = $this->db->fetch_object($resql);
1713
+				$reparray[$i]['id']=$obj->rowid;
1714
+				$reparray[$i]['lastname']=$obj->lastname;
1715
+				$reparray[$i]['firstname']=$obj->firstname;
1716
+				$reparray[$i]['email']=$obj->email;
1717
+				$reparray[$i]['statut']=$obj->statut;
1718
+				$reparray[$i]['entity']=$obj->entity;
1719
+				$reparray[$i]['login']=$obj->login;
1720
+				$reparray[$i]['photo']=$obj->photo;
1721
+				$i++;
1722
+			}
1723
+			return $reparray;
1724
+		}
1725
+		else {
1726
+			dol_print_error($this->db);
1727
+			return -1;
1728
+		}
1729
+	}
1730
+
1731
+	/**
1732
+	 * Set the price level
1733
+	 *
1734
+	 * @param 	int		$price_level	Level of price
1735
+	 * @param 	User	$user			Use making change
1736
+	 * @return	int						<0 if KO, >0 if OK
1737
+	 */
1738
+	function set_price_level($price_level, User $user)
1739
+	{
1740
+		if ($this->id)
1741
+		{
1742
+			$now=dol_now();
1743
+
1744
+			$sql  = "UPDATE ".MAIN_DB_PREFIX."societe";
1745
+			$sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1746
+			$sql .= " WHERE rowid = " . $this->id;
1747
+
1748
+			if (! $this->db->query($sql))
1749
+			{
1750
+				dol_print_error($this->db);
1751
+				return -1;
1752
+			}
1753
+
1754
+			$sql  = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
1755
+			$sql .= " (datec, fk_soc, price_level, fk_user_author)";
1756
+			$sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1757
+
1758
+			if (! $this->db->query($sql))
1759
+			{
1760
+				dol_print_error($this->db);
1761
+				return -1;
1762
+			}
1763
+			return 1;
1764
+		}
1765
+		return -1;
1766
+	}
1767
+
1768
+	/**
1769
+	 *	Add link to sales representative
1770
+	 *
1771
+	 *	@param	User	$user		Object user
1772
+	 *	@param	int		$commid		Id of user
1773
+	 *	@return	void
1774
+	 */
1775
+	function add_commercial(User $user, $commid)
1776
+	{
1777
+		if ($this->id > 0 && $commid > 0)
1778
+		{
1779
+			$sql = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux";
1780
+			$sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1781
+
1782
+			$this->db->query($sql);
1783
+
1784
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1785
+			$sql.= " ( fk_soc, fk_user )";
1786
+			$sql.= " VALUES (".$this->id.",".$commid.")";
1787
+
1788
+			if (! $this->db->query($sql) )
1789
+			{
1790
+				dol_syslog(get_class($this)."::add_commercial Erreur");
1791
+			}
1792
+		}
1793
+	}
1794
+
1795
+	/**
1796
+	 *	Add link to sales representative
1797
+	 *
1798
+	 *	@param	User	$user		Object user
1799
+	 *	@param	int		$commid		Id of user
1800
+	 *	@return	void
1801
+	 */
1802
+	function del_commercial(User $user, $commid)
1803
+	{
1804
+		if ($this->id > 0 && $commid > 0)
1805
+		{
1806
+			$sql  = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux ";
1807
+			$sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1808
+
1809
+			if (! $this->db->query($sql) )
1810
+			{
1811
+				dol_syslog(get_class($this)."::del_commercial Erreur");
1812
+			}
1813
+		}
1814
+	}
1815
+
1816
+
1817
+	/**
1818
+	 *    	Return a link on thirdparty (with picto)
1819
+	 *
1820
+	 *		@param	int		$withpicto		          Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
1821
+	 *		@param	string	$option			          Target of link ('', 'customer', 'prospect', 'supplier', 'project')
1822
+	 *		@param	int		$maxlen			          Max length of name
1823
+	 *      @param	int  	$notooltip		          1=Disable tooltip
1824
+	 *      @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1825
+	 *		@return	string					          String with URL
1826
+	 */
1827
+	function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
1828
+	{
1829
+		global $conf, $langs, $hookmanager;
1830
+
1831
+		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1832
+
1833
+		$name=$this->name?$this->name:$this->nom;
1834
+
1835
+		if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
1836
+		{
1837
+			if (($this->client) && (! empty ( $this->code_client ))
1838
+				&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1839
+				|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
1840
+				)
1841
+			)
1842
+			$code = $this->code_client . ' - ';
1843
+
1844
+			if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
1845
+				&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1846
+				|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
1847
+				)
1848
+			)
1849
+			$code .= $this->code_fournisseur . ' - ';
1850
+
1851
+			if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
1852
+				$name =$code.' '.$name;
1853
+			else
1854
+				$name =$code;
1855
+		}
1856
+
1857
+		if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
1858
+
1859
+		$result=''; $label='';
1860
+		$linkstart=''; $linkend='';
1861
+
1862
+		if (! empty($this->logo) && class_exists('Form'))
1863
+		{
1864
+			$label.= '<div class="photointooltip">';
1865
+			$label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini');
1866
+			$label.= '</div><div style="clear: both;"></div>';
1867
+		}
1868
+
1869
+		$label.= '<div class="centpercent">';
1870
+
1871
+		if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
1872
+		{
1873
+		   $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
1874
+		   $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1875
+		}
1876
+		else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1877
+		{
1878
+			$label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
1879
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1880
+		}
1881
+		else if ($option == 'supplier')
1882
+		{
1883
+			$label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
1884
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
1885
+		}
1886
+		else if ($option == 'agenda')
1887
+		{
1888
+			$label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
1889
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
1890
+		}
1891
+		else if ($option == 'project')
1892
+		{
1893
+			$label.= '<u>' . $langs->trans("ShowProject") . '</u>';
1894
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
1895
+		}
1896
+		else if ($option == 'margin')
1897
+		{
1898
+			$label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
1899
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
1900
+		}
1901
+		else if ($option == 'contact')
1902
+		{
1903
+			$label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
1904
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
1905
+		}
1906
+
1907
+		// By default
1908
+		if (empty($linkstart))
1909
+		{
1910
+			$label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
1911
+			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
1912
+		}
1913
+
1914
+		if (! empty($this->name))
1915
+		{
1916
+			$label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
1917
+			if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
1918
+			$label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
1919
+		}
1920
+		if (! empty($this->country_code))
1921
+			$label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
1922
+		if (! empty($this->tva_intra))
1923
+			$label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra;
1924
+			if (! empty($this->code_client) && $this->client)
1925
+			$label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
1926
+		if (! empty($this->code_fournisseur) && $this->fournisseur)
1927
+			$label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
1928
+		if (! empty($conf->accounting->enabled) && $this->client)
1929
+			$label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
1930
+		if (! empty($conf->accounting->enabled) && $this->fournisseur)
1931
+			$label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
1932
+
1933
+		$label.= '</div>';
1934
+
1935
+		// Add type of canvas
1936
+		$linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
1937
+		// Add param to save lastsearch_values or not
1938
+		$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1939
+		if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1940
+		if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
1941
+		$linkstart.='"';
1942
+
1943
+		$linkclose='';
1944
+		if (empty($notooltip))
1945
+		{
1946
+			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1947
+			{
1948
+				$label=$langs->trans("ShowCompany");
1949
+				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1950
+			}
1951
+			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1952
+			$linkclose.=' class="classfortooltip"';
1953
+
1954
+		 	if (! is_object($hookmanager))
1955
+			{
1956
+				include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1957
+				$hookmanager=new HookManager($this->db);
1958
+			}
1959
+			$hookmanager->initHooks(array('societedao'));
1960
+			$parameters=array('id'=>$this->id);
1961
+			$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1962
+			if ($reshook > 0) $linkclose = $hookmanager->resPrint;
1963
+		}
1964
+		$linkstart.=$linkclose.'>';
1965
+		$linkend='</a>';
1966
+
1967
+		global $user;
1968
+		if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
1969
+		{
1970
+			$linkstart='';
1971
+			$linkend='';
1972
+		}
1973
+
1974
+		if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend);
1975
+		if ($withpicto && $withpicto != 2) $result.=' ';
1976
+		if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
1977
+
1978
+		return $result;
1979
+	}
1980
+
1981
+	/**
1982
+	 *    Return label of status (activity, closed)
1983
+	 *
1984
+	 *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
1985
+	 *    @return   string        		Libelle
1986
+	 */
1987
+	function getLibStatut($mode=0)
1988
+	{
1989
+		return $this->LibStatut($this->status,$mode);
1990
+	}
1991
+
1992
+	/**
1993
+	 *  Renvoi le libelle d'un statut donne
1994
+	 *
1995
+	 *  @param	int		$statut         Id statut
1996
+	 *  @param	int		$mode           0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1997
+	 *  @return	string          		Libelle du statut
1998
+	 */
1999
+	function LibStatut($statut,$mode=0)
2000
+	{
2001
+		global $langs;
2002
+		$langs->load('companies');
2003
+
2004
+		if ($mode == 0)
2005
+		{
2006
+			if ($statut==0) return $langs->trans("ActivityCeased");
2007
+			if ($statut==1) return $langs->trans("InActivity");
2008
+		}
2009
+		if ($mode == 1)
2010
+		{
2011
+			if ($statut==0) return $langs->trans("ActivityCeased");
2012
+			if ($statut==1) return $langs->trans("InActivity");
2013
+		}
2014
+		if ($mode == 2)
2015
+		{
2016
+			if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2017
+			if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2018
+		}
2019
+		if ($mode == 3)
2020
+		{
2021
+			if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2022
+			if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2023
+		}
2024
+		if ($mode == 4)
2025
+		{
2026
+			if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2027
+			if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2028
+		}
2029
+		if ($mode == 5)
2030
+		{
2031
+			if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2032
+			if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2033
+		}
2034
+	}
2035
+
2036
+	/**
2037
+	 *    Return list of contacts emails existing for third party
2038
+	 *
2039
+	 *	  @param	  int		$addthirdparty		1=Add also a record for thirdparty email
2040
+	 *    @return     array       					Array of contacts emails
2041
+	 */
2042
+	function thirdparty_and_contact_email_array($addthirdparty=0)
2043
+	{
2044
+		global $langs;
2045
+
2046
+		$contact_emails = $this->contact_property_array('email',1);
2047
+		if ($this->email && $addthirdparty)
2048
+		{
2049
+			if (empty($this->name)) $this->name=$this->nom;
2050
+			$contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->email."&gt;";
2051
+		}
2052
+		//var_dump($contact_emails)
2053
+		return $contact_emails;
2054
+	}
2055
+
2056
+	/**
2057
+	 *    Return list of contacts mobile phone existing for third party
2058
+	 *
2059
+	 *    @return     array       Array of contacts emails
2060
+	 */
2061
+	function thirdparty_and_contact_phone_array()
2062
+	{
2063
+		global $langs;
2064
+
2065
+		$contact_phone = $this->contact_property_array('mobile');
2066
+
2067
+		if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2068
+		{
2069
+			if (empty($this->name)) $this->name=$this->nom;
2070
+			// TODO: Tester si tel non deja present dans tableau contact
2071
+			$contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->phone."&gt;";
2072
+		}
2073
+		return $contact_phone;
2074
+	}
2075
+
2076
+	/**
2077
+	 *  Return list of contacts emails or mobile existing for third party
2078
+	 *
2079
+	 *  @param	string	$mode       		'email' or 'mobile'
2080
+	 * 	@param	int		$hidedisabled		1=Hide contact if disabled
2081
+	 *  @return array       				Array of contacts emails or mobile array(id=>'Name <email>')
2082
+	 */
2083
+	function contact_property_array($mode='email', $hidedisabled=0)
2084
+	{
2085
+		global $langs;
2086
+
2087
+		$contact_property = array();
2088
+
2089
+
2090
+		$sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2091
+		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2092
+		$sql.= " WHERE fk_soc = ".$this->id;
2093
+
2094
+		$resql=$this->db->query($sql);
2095
+		if ($resql)
2096
+		{
2097
+			$nump = $this->db->num_rows($resql);
2098
+			if ($nump)
2099
+			{
2100
+				$sepa="("; $sepb=")";
2101
+				if ($mode == 'email')
2102
+				{
2103
+					$sepa="&lt;"; $sepb="&gt;";
2104
+				}
2105
+				$i = 0;
2106
+				while ($i < $nump)
2107
+				{
2108
+					$obj = $this->db->fetch_object($resql);
2109
+					if ($mode == 'email') $property=$obj->email;
2110
+					else if ($mode == 'mobile') $property=$obj->phone_mobile;
2111
+					else $property=$obj->$mode;
2112
+
2113
+					// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2114
+					if ($obj->statut == 1 || empty($hidedisabled))
2115
+					{
2116
+						if (empty($property))
2117
+						{
2118
+							if ($mode == 'email') $property=$langs->trans("NoEMail");
2119
+							else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone");
2120
+						}
2121
+
2122
+						if (!empty($obj->poste))
2123
+						{
2124
+							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2125
+						}
2126
+						else
2127
+						{
2128
+							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2129
+						}
2130
+					}
2131
+					$i++;
2132
+				}
2133
+			}
2134
+		}
2135
+		else
2136
+		{
2137
+			dol_print_error($this->db);
2138
+		}
2139
+		return $contact_property;
2140
+	}
2141
+
2142
+
2143
+	/**
2144
+	 *    Renvoie la liste des contacts de cette societe
2145
+	 *
2146
+	 *    @return     array      tableau des contacts
2147
+	 */
2148
+	function contact_array()
2149
+	{
2150
+		$contacts = array();
2151
+
2152
+		$sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2153
+		$resql=$this->db->query($sql);
2154
+		if ($resql)
2155
+		{
2156
+			$nump = $this->db->num_rows($resql);
2157
+			if ($nump)
2158
+			{
2159
+				$i = 0;
2160
+				while ($i < $nump)
2161
+				{
2162
+					$obj = $this->db->fetch_object($resql);
2163
+					$contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
2164
+					$i++;
2165
+				}
2166
+			}
2167
+		}
2168
+		else
2169
+		{
2170
+			dol_print_error($this->db);
2171
+		}
2172
+		return $contacts;
2173
+	}
2174
+
2175
+	/**
2176
+	 *    Renvoie la liste des contacts de cette societe
2177
+	 *
2178
+	 *    @return    array    $contacts    tableau des contacts
2179
+	 */
2180
+	function contact_array_objects()
2181
+	{
2182
+		require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2183
+		$contacts = array();
2184
+
2185
+		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2186
+		$resql=$this->db->query($sql);
2187
+		if ($resql)
2188
+		{
2189
+			$nump = $this->db->num_rows($resql);
2190
+			if ($nump)
2191
+			{
2192
+				$i = 0;
2193
+				while ($i < $nump)
2194
+				{
2195
+					$obj = $this->db->fetch_object($resql);
2196
+					$contact = new Contact($this->db);
2197
+					$contact->fetch($obj->rowid);
2198
+					$contacts[] = $contact;
2199
+					$i++;
2200
+				}
2201
+			}
2202
+		}
2203
+		else
2204
+		{
2205
+			dol_print_error($this->db);
2206
+		}
2207
+		return $contacts;
2208
+	}
2209
+
2210
+	/**
2211
+	 *  Return property of contact from its id
2212
+	 *
2213
+	 *  @param	int		$rowid      id of contact
2214
+	 *  @param  string	$mode       'email' or 'mobile'
2215
+	 *  @return string  			Email of contact with format: "Full name <email>"
2216
+	 */
2217
+	function contact_get_property($rowid,$mode)
2218
+	{
2219
+		$contact_property='';
2220
+
2221
+		if (empty($rowid)) return '';
2222
+
2223
+		$sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2224
+		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2225
+		$sql.= " WHERE rowid = '".$rowid."'";
2226
+
2227
+		$resql=$this->db->query($sql);
2228
+		if ($resql)
2229
+		{
2230
+			$nump = $this->db->num_rows($resql);
2231
+
2232
+			if ($nump)
2233
+			{
2234
+				$obj = $this->db->fetch_object($resql);
2235
+
2236
+				if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
2237
+				else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2238
+			}
2239
+			return $contact_property;
2240
+		}
2241
+		else
2242
+		{
2243
+			dol_print_error($this->db);
2244
+		}
2245
+
2246
+	}
2247
+
2248
+
2249
+	/**
2250
+	 *  Return bank number property of thirdparty (label or rum)
2251
+	 *
2252
+	 *	@param	string	$mode	'label' or 'rum'
2253
+	 *  @return	string			Bank number
2254
+	 */
2255
+	function display_rib($mode='label')
2256
+	{
2257
+		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2258
+
2259
+		$bac = new CompanyBankAccount($this->db);
2260
+		$bac->fetch(0,$this->id);
2261
+
2262
+		if ($mode == 'label')
2263
+		{
2264
+			return $bac->getRibLabel(true);
2265
+		}
2266
+		elseif ($mode == 'rum')
2267
+		{
2268
+			if (empty($bac->rum))
2269
+			{
2270
+				require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2271
+				$prelevement = new BonPrelevement($this->db);
2272
+				$bac->fetch_thirdparty();
2273
+				$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2274
+			}
2275
+			return $bac->rum;
2276
+		}
2277
+
2278
+		return 'BadParameterToFunctionDisplayRib';
2279
+	}
2280
+
2281
+	/**
2282
+	 * Return Array of RIB
2283
+	 *
2284
+	 * @return     array|int        0 if KO, Array of CompanyBanckAccount if OK
2285
+	 */
2286
+	function get_all_rib()
2287
+	{
2288
+		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2289
+		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id;
2290
+		$result = $this->db->query($sql);
2291
+		if (!$result) {
2292
+			$this->error++;
2293
+			$this->errors[] = $this->db->lasterror;
2294
+			return 0;
2295
+		} else {
2296
+			$num_rows = $this->db->num_rows($result);
2297
+			$rib_array = array();
2298
+			if ($num_rows) {
2299
+				while ($obj = $this->db->fetch_object($result)) {
2300
+					$rib = new CompanyBankAccount($this->db);
2301
+					$rib->fetch($obj->rowid);
2302
+					$rib_array[] = $rib;
2303
+				}
2304
+			}
2305
+			return $rib_array;
2306
+		}
2307
+	}
2308
+
2309
+	/**
2310
+	 *  Attribut un code client a partir du module de controle des codes.
2311
+	 *  Return value is stored into this->code_client
2312
+	 *
2313
+	 *	@param	Societe		$objsoc		Object thirdparty
2314
+	 *	@param	int			$type		Should be 0 to say customer
2315
+	 *  @return void
2316
+	 */
2317
+	function get_codeclient($objsoc=0,$type=0)
2318
+	{
2319
+		global $conf;
2320
+		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2321
+		{
2322
+			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2323
+
2324
+			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2325
+			foreach ($dirsociete as $dirroot)
2326
+			{
2327
+				$res=dol_include_once($dirroot.$module.'.php');
2328
+				if ($res) break;
2329
+			}
2330
+			$mod = new $module();
2331
+
2332
+			$this->code_client = $mod->getNextValue($objsoc,$type);
2333
+			$this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2334
+
2335
+			dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2336
+		}
2337
+	}
2338
+
2339
+	/**
2340
+	 *  Attribut un code fournisseur a partir du module de controle des codes.
2341
+	 *  Return value is stored into this->code_fournisseur
2342
+	 *
2343
+	 *	@param	Societe		$objsoc		Object thirdparty
2344
+	 *	@param	int			$type		Should be 1 to say supplier
2345
+	 *  @return void
2346
+	 */
2347
+	function get_codefournisseur($objsoc=0,$type=1)
2348
+	{
2349
+		global $conf;
2350
+		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2351
+		{
2352
+			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2353
+
2354
+			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2355
+			foreach ($dirsociete as $dirroot)
2356
+			{
2357
+				$res=dol_include_once($dirroot.$module.'.php');
2358
+				if ($res) break;
2359
+			}
2360
+			$mod = new $module();
2361
+
2362
+			$this->code_fournisseur = $mod->getNextValue($objsoc,$type);
2363
+
2364
+			dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2365
+		}
2366
+	}
2367
+
2368
+	/**
2369
+	 *    Verifie si un code client est modifiable en fonction des parametres
2370
+	 *    du module de controle des codes.
2371
+	 *
2372
+	 *    @return     int		0=No, 1=Yes
2373
+	 */
2374
+	function codeclient_modifiable()
2375
+	{
2376
+		global $conf;
2377
+		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2378
+		{
2379
+			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2380
+
2381
+			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2382
+			foreach ($dirsociete as $dirroot)
2383
+			{
2384
+				$res=dol_include_once($dirroot.$module.'.php');
2385
+				if ($res) break;
2386
+			}
2387
+
2388
+			$mod = new $module();
2389
+
2390
+			dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2391
+			if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2392
+			if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2393
+			if ($mod->code_modifiable) return 1;	// A mettre en dernier
2394
+			return 0;
2395
+		}
2396
+		else
2397
+		{
2398
+			return 0;
2399
+		}
2400
+	}
2401
+
2402
+
2403
+	/**
2404
+	 *    Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
2405
+	 *
2406
+	 *    @return     int		0=No, 1=Yes
2407
+	 */
2408
+	function codefournisseur_modifiable()
2409
+	{
2410
+		global $conf;
2411
+		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2412
+		{
2413
+			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2414
+
2415
+			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2416
+			foreach ($dirsociete as $dirroot)
2417
+			{
2418
+				$res=dol_include_once($dirroot.$module.'.php');
2419
+				if ($res) break;
2420
+			}
2421
+
2422
+			$mod = new $module();
2423
+
2424
+			dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2425
+			if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2426
+			if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2427
+			if ($mod->code_modifiable) return 1;	// A mettre en dernier
2428
+			return 0;
2429
+		}
2430
+		else
2431
+		{
2432
+			return 0;
2433
+		}
2434
+	}
2435
+
2436
+
2437
+	/**
2438
+	 *  Check customer code
2439
+	 *
2440
+	 *  @return     int				0 if OK
2441
+	 * 								-1 ErrorBadCustomerCodeSyntax
2442
+	 * 								-2 ErrorCustomerCodeRequired
2443
+	 * 								-3 ErrorCustomerCodeAlreadyUsed
2444
+	 * 								-4 ErrorPrefixRequired
2445
+	 */
2446
+	function check_codeclient()
2447
+	{
2448
+		global $conf;
2449
+		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2450
+		{
2451
+			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2452
+
2453
+			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2454
+			foreach ($dirsociete as $dirroot)
2455
+			{
2456
+				$res=dol_include_once($dirroot.$module.'.php');
2457
+				if ($res) break;
2458
+			}
2459
+
2460
+			$mod = new $module();
2461
+
2462
+		   	dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2463
+		   	$result = $mod->verif($this->db, $this->code_client, $this, 0);
2464
+			return $result;
2465
+		}
2466
+		else
2467
+		{
2468
+			return 0;
2469
+		}
2470
+	}
2471
+
2472
+	/**
2473
+	 *    Check supplier code
2474
+	 *
2475
+	 *    @return     int		0 if OK
2476
+	 * 							-1 ErrorBadCustomerCodeSyntax
2477
+	 * 							-2 ErrorCustomerCodeRequired
2478
+	 * 							-3 ErrorCustomerCodeAlreadyUsed
2479
+	 * 							-4 ErrorPrefixRequired
2480
+	 */
2481
+	function check_codefournisseur()
2482
+	{
2483
+		global $conf;
2484
+		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2485
+		{
2486
+			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2487
+
2488
+			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2489
+			foreach ($dirsociete as $dirroot)
2490
+			{
2491
+				$res=dol_include_once($dirroot.$module.'.php');
2492
+				if ($res) break;
2493
+			}
2494
+
2495
+			$mod = new $module();
2496
+
2497
+			dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2498
+			$result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2499
+			return $result;
2500
+		}
2501
+		else
2502
+		{
2503
+			return 0;
2504
+		}
2505
+	}
2506
+
2507
+	/**
2508
+	 *    	Renvoie un code compta, suivant le module de code compta.
2509
+	 *      Peut etre identique a celui saisit ou genere automatiquement.
2510
+	 *      A ce jour seule la generation automatique est implementee
2511
+	 *
2512
+	 *    	@param	string	$type		Type of thirdparty ('customer' or 'supplier')
2513
+	 *		@return	string				Code compta si ok, 0 si aucun, <0 si ko
2514
+	 */
2515
+	function get_codecompta($type)
2516
+	{
2517
+		global $conf;
2518
+
2519
+		if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2520
+		{
2521
+			$file='';
2522
+			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2523
+			foreach ($dirsociete as $dirroot)
2524
+			{
2525
+				if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
2526
+				{
2527
+					$file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
2528
+					break;
2529
+				}
2530
+			}
2531
+
2532
+			if (! empty($file))
2533
+			{
2534
+				dol_include_once($file);
2535
+
2536
+				$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
2537
+				$mod = new $classname;
2538
+
2539
+				// Defini code compta dans $mod->code
2540
+				$result = $mod->get_code($this->db, $this, $type);
2541
+
2542
+				if ($type == 'customer') $this->code_compta = $mod->code;
2543
+				else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2544
+
2545
+				return $result;
2546
+			}
2547
+			else
2548
+			{
2549
+				$this->error = 'ErrorAccountancyCodeNotDefined';
2550
+				return -1;
2551
+			}
2552
+		}
2553
+		else
2554
+		{
2555
+			if ($type == 'customer') $this->code_compta = '';
2556
+			else if ($type == 'supplier') $this->code_compta_fournisseur = '';
2557
+
2558
+			return 0;
2559
+		}
2560
+	}
2561
+
2562
+	/**
2563
+	 *    Define parent commany of current company
2564
+	 *
2565
+	 *    @param	int		$id     Id of thirdparty to set or '' to remove
2566
+	 *    @return	int     		<0 if KO, >0 if OK
2567
+	 */
2568
+	function set_parent($id)
2569
+	{
2570
+		if ($this->id)
2571
+		{
2572
+			$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2573
+			$sql.= " SET parent = ".($id > 0 ? $id : "null");
2574
+			$sql.= " WHERE rowid = " . $this->id;
2575
+			dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2576
+			$resql=$this->db->query($sql);
2577
+			if ($resql)
2578
+			{
2579
+				$this->parent = $id;
2580
+				return 1;
2581
+			}
2582
+			else
2583
+			{
2584
+				return -1;
2585
+			}
2586
+		}
2587
+		else return -1;
2588
+	}
2589
+
2590
+	/**
2591
+	 *  Returns if a profid sould be verified
2592
+	 *
2593
+	 *  @param	int		$idprof		1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
2594
+	 *  @return boolean         	true , false
2595
+	 */
2596
+	function id_prof_verifiable($idprof)
2597
+	{
2598
+		global $conf;
2599
+
2600
+	 	switch($idprof)
2601
+		{
2602
+			case 1:
2603
+				$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2604
+				break;
2605
+			case 2:
2606
+				$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2607
+				break;
2608
+			case 3:
2609
+				$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2610
+				break;
2611
+			case 4:
2612
+				$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2613
+				break;
2614
+			case 5:
2615
+				$ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2616
+				break;
2617
+			case 6:
2618
+				$ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2619
+				break;
2620
+			default:
2621
+				$ret=false;
2622
+		}
2623
+
2624
+		return $ret;
2625
+	}
2626
+
2627
+	/**
2628
+	 *    Verify if a profid exists into database for others thirds
2629
+	 *
2630
+	 *    @param	string	$idprof		'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
2631
+	 *    @param	string	$value		Value of profid
2632
+	 *    @param	int		$socid		Id of thirdparty to exclude (if update)
2633
+	 *    @return   boolean				True if exists, False if not
2634
+	 */
2635
+	function id_prof_exists($idprof, $value, $socid=0)
2636
+	{
2637
+		$field = $idprof;
2638
+
2639
+	 	switch($idprof)	// For backward compatibility
2640
+		{
2641
+			case '1':
2642
+			case 'idprof1':
2643
+				$field="siren";
2644
+				break;
2645
+			case '2':
2646
+			case 'idprof2':
2647
+				$field="siret";
2648
+				break;
2649
+			case '3':
2650
+			case 'idprof3':
2651
+				$field="ape";
2652
+				break;
2653
+			case '4':
2654
+			case 'idprof4':
2655
+				$field="idprof4";
2656
+				break;
2657
+			case '5':
2658
+				$field="idprof5";
2659
+				break;
2660
+			case '6':
2661
+				$field="idprof6";
2662
+				break;
2663
+	 	}
2664
+
2665
+		 //Verify duplicate entries
2666
+		$sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2667
+		if($socid) $sql .= " AND rowid <> ".$socid;
2668
+		$resql = $this->db->query($sql);
2669
+		if ($resql)
2670
+		{
2671
+			$obj = $this->db->fetch_object($resql);
2672
+			$count = $obj->idprof;
2673
+		}
2674
+		else
2675
+		{
2676
+			$count = 0;
2677
+			print $this->db->error();
2678
+		}
2679
+		$this->db->free($resql);
2680
+
2681
+		if ($count > 0) return true;
2682
+		else return false;
2683
+	}
2684
+
2685
+	/**
2686
+	 *  Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
2687
+	 *
2688
+	 *  @param	int			$idprof         1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
2689
+	 *  @param  Societe		$soc            Objet societe
2690
+	 *  @return int             			<=0 if KO, >0 if OK
2691
+	 *  TODO better to have this in a lib than into a business class
2692
+	 */
2693
+	function id_prof_check($idprof,$soc)
2694
+	{
2695
+		global $conf;
2696
+
2697
+		$ok=1;
2698
+
2699
+		if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2700
+
2701
+		// Verifie SIREN si pays FR
2702
+		if ($idprof == 1 && $soc->country_code == 'FR')
2703
+		{
2704
+			$chaine=trim($this->idprof1);
2705
+			$chaine=preg_replace('/(\s)/','',$chaine);
2706
+
2707
+			if (dol_strlen($chaine) != 9) return -1;
2708
+
2709
+			$sum = 0;
2710
+
2711
+			for ($i = 0 ; $i < 10 ; $i = $i+2)
2712
+			{
2713
+				$sum = $sum + substr($this->idprof1, (8 - $i), 1);
2714
+			}
2715
+
2716
+			for ($i = 1 ; $i < 9 ; $i = $i+2)
2717
+			{
2718
+				$ps = 2 * substr($this->idprof1, (8 - $i), 1);
2719
+
2720
+				if ($ps > 9)
2721
+				{
2722
+					$ps = substr($ps, 0,1) + substr($ps, 1, 1);
2723
+				}
2724
+				$sum = $sum + $ps;
2725
+			}
2726
+
2727
+			if (substr($sum, -1) != 0) return -1;
2728
+		}
2729
+
2730
+		// Verifie SIRET si pays FR
2731
+		if ($idprof == 2 && $soc->country_code == 'FR')
2732
+		{
2733
+			$chaine=trim($this->idprof2);
2734
+			$chaine=preg_replace('/(\s)/','',$chaine);
2735
+
2736
+			if (dol_strlen($chaine) != 14) return -1;
2737
+		}
2738
+
2739
+		//Verify CIF/NIF/NIE if pays ES
2740
+		//Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
2741
+		if ($idprof == 1 && $soc->country_code == 'ES')
2742
+		{
2743
+			$string=trim($this->idprof1);
2744
+			$string=preg_replace('/(\s)/','',$string);
2745
+			$string = strtoupper($string);
2746
+
2747
+			for ($i = 0; $i < 9; $i ++)
2748
+			$num[$i] = substr($string, $i, 1);
2749
+
2750
+			//Check format
2751
+			if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
2752
+			return 0;
2753
+
2754
+			//Check NIF
2755
+			if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
2756
+			if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
2757
+			return 1;
2758
+			else
2759
+			return -1;
2760
+
2761
+			//algorithm checking type code CIF
2762
+			$sum = $num[2] + $num[4] + $num[6];
2763
+			for ($i = 1; $i < 8; $i += 2)
2764
+			$sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
2765
+			$n = 10 - substr($sum, strlen($sum) - 1, 1);
2766
+
2767
+			//Chek special NIF
2768
+			if (preg_match('/^[KLM]{1}/', $string))
2769
+			if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
2770
+			return 1;
2771
+			else
2772
+			return -1;
2773
+
2774
+			//Check CIF
2775
+			if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
2776
+			if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
2777
+			return 2;
2778
+			else
2779
+			return -2;
2780
+
2781
+			//Check NIE T
2782
+			if (preg_match('/^[T]{1}/', $string))
2783
+			if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
2784
+			return 3;
2785
+			else
2786
+			return -3;
2787
+
2788
+			//Check NIE XYZ
2789
+			if (preg_match('/^[XYZ]{1}/', $string))
2790
+			if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
2791
+			return 3;
2792
+			else
2793
+			return -3;
1413 2794
 
1414
-            // User is mandatory for trigger call
1415
-            if (! $error && $call_trigger)
1416
-            {
1417
-                // Call trigger
1418
-                $result=$this->call_trigger('COMPANY_DELETE',$fuser);
1419
-                if ($result < 0) $error++;
1420
-                // End call triggers
1421
-            }
2795
+			//Can not be verified
2796
+			return -4;
2797
+		}
1422 2798
 
1423
-			if (! $error)
1424
-			{
1425
-	            require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1426
-	            $static_cat = new Categorie($this->db);
1427
-	            $toute_categs = array();
1428
-
1429
-	            // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1430
-	            if ($this->client || $this->prospect)
1431
-	            {
1432
-	                $toute_categs['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
1433
-	            }
1434
-	            if ($this->fournisseur)
1435
-	            {
1436
-	                $toute_categs['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
1437
-	            }
1438
-
1439
-	            // Remove each "Categorie"
1440
-	            foreach ($toute_categs as $type => $categs_type)
1441
-	            {
1442
-	                foreach ($categs_type as $cat)
1443
-	                {
1444
-	                    $cat->del_type($this, $type);
1445
-	                }
1446
-	            }
1447
-			}
2799
+		return $ok;
2800
+	}
1448 2801
 
1449
-			foreach ($this->childtablesoncascade as $tabletodelete)
1450
-			{
1451
-				if (! $error)
1452
-				{
1453
-					$sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1454
-					$sql.= " WHERE fk_soc = " . $id;
1455
-					if (! $this->db->query($sql))
1456
-					{
1457
-						$error++;
1458
-						$this->errors[] = $this->db->lasterror();
1459
-					}
1460
-				}
1461
-			}
2802
+	/**
2803
+	 *   Return an url to check online a professional id or empty string
2804
+	 *
2805
+	 *   @param		int		$idprof         1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
2806
+	 *   @param 	Societe	$thirdparty     Object thirdparty
2807
+	 *   @return	string          		Url or empty string if no URL known
2808
+	 *   TODO better in a lib than into business class
2809
+	 */
2810
+	function id_prof_url($idprof,$thirdparty)
2811
+	{
2812
+		global $conf,$langs,$hookmanager;
1462 2813
 
1463
-            // Removed extrafields
1464
-            if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1465
-            {
1466
-            	$result=$this->deleteExtraFields();
1467
-            	if ($result < 0)
1468
-            	{
1469
-            		$error++;
1470
-            		dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1471
-            	}
1472
-            }
1473
-
1474
-            // Remove third party
1475
-            if (! $error)
1476
-            {
1477
-                $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1478
-                $sql.= " WHERE rowid = " . $id;
1479
-                if (! $this->db->query($sql))
1480
-                {
1481
-                    $error++;
1482
-                    $this->errors[] = $this->db->lasterror();
1483
-                }
1484
-            }
1485
-
1486
-            if (! $error)
1487
-            {
1488
-                $this->db->commit();
1489
-
1490
-                // Delete directory
1491
-                if (! empty($conf->societe->multidir_output[$entity]))
1492
-                {
1493
-                	$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1494
-                	if (dol_is_dir($docdir))
1495
-                	{
1496
-                    	dol_delete_dir_recursive($docdir);
1497
-                	}
1498
-                }
1499
-
1500
-                return 1;
1501
-            }
1502
-            else
1503
-			{
1504
-				dol_syslog($this->error, LOG_ERR);
1505
-                $this->db->rollback();
1506
-                return -1;
1507
-            }
1508
-        }
1509
-		else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1510
-        return 0;
1511
-    }
1512
-
1513
-    /**
1514
-     *  Define third party as a customer
1515
-     *
1516
-     *	@return		int		<0 if KO, >0 if OK
1517
-     */
1518
-    function set_as_client()
1519
-    {
1520
-        if ($this->id)
1521
-        {
1522
-            $newclient=1;
1523
-            if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1524
-            $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1525
-            $sql.= " SET client = ".$newclient;
1526
-            $sql.= " WHERE rowid = " . $this->id;
1527
-
1528
-            $resql=$this->db->query($sql);
1529
-            if ($resql)
1530
-            {
1531
-                $this->client = $newclient;
1532
-                return 1;
1533
-            }
1534
-            else return -1;
1535
-        }
1536
-        return 0;
1537
-    }
1538
-
1539
-    /**
1540
-     *  Definit la societe comme un client
1541
-     *
1542
-     *  @param	float	$remise		Valeur en % de la remise
1543
-     *  @param  string	$note		Note/Motif de modification de la remise
1544
-     *  @param  User	$user		Utilisateur qui definie la remise
1545
-     *	@return	int					<0 if KO, >0 if OK
1546
-     */
1547
-    function set_remise_client($remise, $note, User $user)
1548
-    {
1549
-        global $conf, $langs;
1550
-
1551
-        // Nettoyage parametres
1552
-        $note=trim($note);
1553
-        if (! $note)
1554
-        {
1555
-            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1556
-            return -2;
1557
-        }
2814
+		$url='';
2815
+		$action = '';
1558 2816
 
1559
-        dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1560
-
1561
-        if ($this->id)
1562
-        {
1563
-            $this->db->begin();
1564
-
1565
-            $now=dol_now();
1566
-
1567
-            // Positionne remise courante
1568
-            $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1569
-            $sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1570
-            $sql.= " WHERE rowid = " . $this->id;
1571
-            $resql=$this->db->query($sql);
1572
-            if (! $resql)
1573
-            {
1574
-                $this->db->rollback();
1575
-                $this->error=$this->db->error();
1576
-                return -1;
1577
-            }
1578
-
1579
-            // Ecrit trace dans historique des remises
1580
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1581
-            $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1582
-            $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1583
-            $sql.= " '".$this->db->escape($note)."',";
1584
-            $sql.= " ".$user->id;
1585
-            $sql.= ")";
1586
-
1587
-            $resql=$this->db->query($sql);
1588
-            if (! $resql)
1589
-            {
1590
-                $this->db->rollback();
1591
-                $this->error=$this->db->lasterror();
1592
-                return -1;
1593
-            }
1594
-
1595
-            $this->db->commit();
1596
-            return 1;
1597
-        }
1598
-    }
1599
-
1600
-    /**
1601
-     *    	Add a discount for third party
1602
-     *
1603
-     *    	@param	float	$remise     Amount of discount
1604
-     *    	@param  User	$user       User adding discount
1605
-     *    	@param  string	$desc		Reason of discount
1606
-     *      @param  float	$tva_tx     VAT rate
1607
-     *		@return	int					<0 if KO, id of discount record if OK
1608
-     */
1609
-    function set_remise_except($remise, User $user, $desc, $tva_tx=0)
1610
-    {
1611
-        global $langs;
1612
-
1613
-        // Clean parameters
1614
-        $remise = price2num($remise);
1615
-        $desc = trim($desc);
1616
-
1617
-        // Check parameters
1618
-        if (! $remise > 0)
1619
-        {
1620
-            $this->error=$langs->trans("ErrorWrongValueForParameter","1");
1621
-            return -1;
1622
-        }
1623
-        if (! $desc)
1624
-        {
1625
-            $this->error=$langs->trans("ErrorWrongValueForParameter","3");
1626
-            return -2;
1627
-        }
2817
+		$hookmanager->initHooks(array('idprofurl'));
2818
+		$parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
2819
+		$reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2820
+		if (empty($reshook))
2821
+		{
2822
+			if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
1628 2823
 
1629
-        if ($this->id)
1630
-        {
1631
-            require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1632
-
1633
-            $discount = new DiscountAbsolute($this->db);
1634
-            $discount->fk_soc=$this->id;
1635
-            $discount->amount_ht=price2num($remise,'MT');
1636
-            $discount->amount_tva=price2num($remise*$tva_tx/100,'MT');
1637
-            $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
1638
-            $discount->tva_tx=price2num($tva_tx,'MT');
1639
-            $discount->description=$desc;
1640
-            $result=$discount->create($user);
1641
-            if ($result > 0)
1642
-            {
1643
-                return $result;
1644
-            }
1645
-            else
1646
-            {
1647
-                $this->error=$discount->error;
1648
-                return -3;
1649
-            }
1650
-        }
1651
-        else return 0;
1652
-    }
1653
-
1654
-    /**
1655
-     *  Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
1656
-     *
1657
-     *	@param	User	$user		Filtre sur un user auteur des remises
1658
-     * 	@param	string	$filter		Filtre autre
1659
-     * 	@param	integer	$maxvalue	Filter on max value for discount
1660
-     *	@return	int					<0 if KO, Credit note amount otherwise
1661
-     */
1662
-    function getAvailableDiscounts($user='',$filter='',$maxvalue=0)
1663
-    {
1664
-        require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1665
-
1666
-        $discountstatic=new DiscountAbsolute($this->db);
1667
-        $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue);
1668
-        if ($result >= 0)
1669
-        {
1670
-            return $result;
1671
-        }
1672
-        else
1673
-        {
1674
-            $this->error=$discountstatic->error;
1675
-            return -1;
1676
-        }
1677
-    }
1678
-
1679
-    /**
1680
-     *  Return array of sales representatives
1681
-     *
1682
-     *  @param	User	$user		Object user
1683
-     *  @return array       		Array of sales representatives of third party
1684
-     */
1685
-    function getSalesRepresentatives(User $user)
1686
-    {
1687
-        global $conf;
1688
-
1689
-        $reparray=array();
1690
-
1691
-        $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1692
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1693
-        if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1694
-        {
1695
-        	$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1696
-        	$sql.= " WHERE ((ug.fk_user = sc.fk_user";
1697
-        	$sql.= " AND ug.entity = ".$conf->entity.")";
1698
-        	$sql.= " OR u.admin = 1)";
1699
-        }
1700
-        else
1701
-        	$sql.= " WHERE entity in (0, ".$conf->entity.")";
1702
-
1703
-        $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1704
-
1705
-        $resql = $this->db->query($sql);
1706
-        if ($resql)
1707
-        {
1708
-            $num = $this->db->num_rows($resql);
1709
-            $i=0;
1710
-            while ($i < $num)
1711
-            {
1712
-                $obj = $this->db->fetch_object($resql);
1713
-                $reparray[$i]['id']=$obj->rowid;
1714
-                $reparray[$i]['lastname']=$obj->lastname;
1715
-                $reparray[$i]['firstname']=$obj->firstname;
1716
-                $reparray[$i]['email']=$obj->email;
1717
-                $reparray[$i]['statut']=$obj->statut;
1718
-                $reparray[$i]['entity']=$obj->entity;
1719
-                $reparray[$i]['login']=$obj->login;
1720
-                $reparray[$i]['photo']=$obj->photo;
1721
-                $i++;
1722
-            }
1723
-            return $reparray;
1724
-        }
1725
-        else {
1726
-            dol_print_error($this->db);
1727
-            return -1;
1728
-        }
1729
-    }
1730
-
1731
-    /**
1732
-     * Set the price level
1733
-     *
1734
-     * @param 	int		$price_level	Level of price
1735
-     * @param 	User	$user			Use making change
1736
-     * @return	int						<0 if KO, >0 if OK
1737
-     */
1738
-    function set_price_level($price_level, User $user)
1739
-    {
1740
-        if ($this->id)
1741
-        {
1742
-        	$now=dol_now();
1743
-
1744
-            $sql  = "UPDATE ".MAIN_DB_PREFIX."societe";
1745
-            $sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1746
-            $sql .= " WHERE rowid = " . $this->id;
1747
-
1748
-            if (! $this->db->query($sql))
1749
-            {
1750
-                dol_print_error($this->db);
1751
-                return -1;
1752
-            }
1753
-
1754
-            $sql  = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
1755
-            $sql .= " (datec, fk_soc, price_level, fk_user_author)";
1756
-            $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1757
-
1758
-            if (! $this->db->query($sql))
1759
-            {
1760
-                dol_print_error($this->db);
1761
-                return -1;
1762
-            }
1763
-            return 1;
1764
-        }
1765
-        return -1;
1766
-    }
1767
-
1768
-    /**
1769
-     *	Add link to sales representative
1770
-     *
1771
-     *	@param	User	$user		Object user
1772
-     *	@param	int		$commid		Id of user
1773
-     *	@return	void
1774
-     */
1775
-    function add_commercial(User $user, $commid)
1776
-    {
1777
-        if ($this->id > 0 && $commid > 0)
1778
-        {
1779
-            $sql = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux";
1780
-            $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1781
-
1782
-            $this->db->query($sql);
1783
-
1784
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1785
-            $sql.= " ( fk_soc, fk_user )";
1786
-            $sql.= " VALUES (".$this->id.",".$commid.")";
1787
-
1788
-            if (! $this->db->query($sql) )
1789
-            {
1790
-                dol_syslog(get_class($this)."::add_commercial Erreur");
1791
-            }
1792
-        }
1793
-    }
1794
-
1795
-    /**
1796
-     *	Add link to sales representative
1797
-     *
1798
-     *	@param	User	$user		Object user
1799
-     *	@param	int		$commid		Id of user
1800
-     *	@return	void
1801
-     */
1802
-    function del_commercial(User $user, $commid)
1803
-    {
1804
-        if ($this->id > 0 && $commid > 0)
1805
-        {
1806
-            $sql  = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux ";
1807
-            $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1808
-
1809
-            if (! $this->db->query($sql) )
1810
-            {
1811
-                dol_syslog(get_class($this)."::del_commercial Erreur");
1812
-            }
1813
-        }
1814
-    }
1815
-
1816
-
1817
-    /**
1818
-     *    	Return a link on thirdparty (with picto)
1819
-     *
1820
-     *		@param	int		$withpicto		          Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
1821
-     *		@param	string	$option			          Target of link ('', 'customer', 'prospect', 'supplier', 'project')
1822
-     *		@param	int		$maxlen			          Max length of name
1823
-     *      @param	int  	$notooltip		          1=Disable tooltip
1824
-     *      @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1825
-     *		@return	string					          String with URL
1826
-     */
1827
-    function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
1828
-    {
1829
-        global $conf, $langs, $hookmanager;
1830
-
1831
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1832
-
1833
-        $name=$this->name?$this->name:$this->nom;
1834
-
1835
-    	if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
1836
-    	{
1837
-    		if (($this->client) && (! empty ( $this->code_client ))
1838
-    			&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1839
-    			|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
1840
-    			)
1841
-    		)
1842
-    		$code = $this->code_client . ' - ';
1843
-
1844
-    		if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
1845
-    			&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1846
-    			|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
1847
-    			)
1848
-    		)
1849
-    		$code .= $this->code_fournisseur . ' - ';
1850
-
1851
-    		if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
1852
-    			$name =$code.' '.$name;
1853
-    		else
1854
-    			$name =$code;
1855
-    	}
1856
-
1857
-    	if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
1858
-
1859
-        $result=''; $label='';
1860
-        $linkstart=''; $linkend='';
1861
-
1862
-        if (! empty($this->logo) && class_exists('Form'))
1863
-        {
1864
-            $label.= '<div class="photointooltip">';
1865
-            $label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini');
1866
-            $label.= '</div><div style="clear: both;"></div>';
1867
-        }
2824
+			// TODO Move links to validate professional ID into a dictionary table "country" + "link"
2825
+			if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1;    // See also http://avis-situation-sirene.insee.fr/
2826
+			//if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/';     // Link no more valid
2827
+			if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
2828
+			if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
1868 2829
 
1869
-        $label.= '<div class="centpercent">';
2830
+			if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
2831
+		}
2832
+		else
2833
+		{
2834
+			return $hookmanager->resPrint;
2835
+		}
1870 2836
 
1871
-        if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
1872
-        {
1873
-           $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
1874
-           $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1875
-        }
1876
-        else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1877
-        {
1878
-            $label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
1879
-            $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1880
-        }
1881
-        else if ($option == 'supplier')
1882
-        {
1883
-            $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
1884
-            $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
1885
-        }
1886
-        else if ($option == 'agenda')
1887
-        {
1888
-            $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
1889
-            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
1890
-        }
1891
-        else if ($option == 'project')
1892
-        {
1893
-            $label.= '<u>' . $langs->trans("ShowProject") . '</u>';
1894
-            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
1895
-        }
1896
-        else if ($option == 'margin')
1897
-        {
1898
-            $label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
1899
-            $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
1900
-        }
1901
-        else if ($option == 'contact')
1902
-        {
1903
-        	$label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
1904
-        	$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
1905
-        }
2837
+		return '';
2838
+	}
1906 2839
 
1907
-        // By default
1908
-        if (empty($linkstart))
1909
-        {
1910
-            $label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
1911
-            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
1912
-        }
2840
+	/**
2841
+	 *   Indique si la societe a des projets
2842
+	 *
2843
+	 *   @return     bool	   true si la societe a des projets, false sinon
2844
+	 */
2845
+	function has_projects()
2846
+	{
2847
+		$sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
2848
+		$resql = $this->db->query($sql);
2849
+		if ($resql)
2850
+		{
2851
+			$obj = $this->db->fetch_object($resql);
2852
+			$count = $obj->numproj;
2853
+		}
2854
+		else
2855
+		{
2856
+			$count = 0;
2857
+			print $this->db->error();
2858
+		}
2859
+		$this->db->free($resql);
2860
+		return ($count > 0);
2861
+	}
1913 2862
 
1914
-        if (! empty($this->name))
1915
-        {
1916
-            $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
1917
-            if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
1918
-            $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
1919
-        }
1920
-        if (! empty($this->country_code))
1921
-            $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
1922
-        if (! empty($this->tva_intra))
1923
-            $label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra;
1924
-            if (! empty($this->code_client) && $this->client)
1925
-            $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
1926
-        if (! empty($this->code_fournisseur) && $this->fournisseur)
1927
-            $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
1928
-        if (! empty($conf->accounting->enabled) && $this->client)
1929
-            $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
1930
-        if (! empty($conf->accounting->enabled) && $this->fournisseur)
1931
-            $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
1932
-
1933
-        $label.= '</div>';
1934
-
1935
-        // Add type of canvas
1936
-        $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
1937
-        // Add param to save lastsearch_values or not
1938
-        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1939
-        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1940
-        if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
1941
-        $linkstart.='"';
1942
-
1943
-        $linkclose='';
1944
-        if (empty($notooltip))
1945
-        {
1946
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1947
-            {
1948
-                $label=$langs->trans("ShowCompany");
1949
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1950
-            }
1951
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1952
-            $linkclose.=' class="classfortooltip"';
1953
-
1954
-         	if (! is_object($hookmanager))
1955
-    		{
1956
-    			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1957
-    			$hookmanager=new HookManager($this->db);
1958
-    		}
1959
-    		$hookmanager->initHooks(array('societedao'));
1960
-    		$parameters=array('id'=>$this->id);
1961
-    		$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1962
-    		if ($reshook > 0) $linkclose = $hookmanager->resPrint;
1963
-        }
1964
-        $linkstart.=$linkclose.'>';
1965
-        $linkend='</a>';
1966
-
1967
-        global $user;
1968
-        if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
1969
-        {
1970
-            $linkstart='';
1971
-            $linkend='';
1972
-        }
1973 2863
 
1974
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend);
1975
-        if ($withpicto && $withpicto != 2) $result.=' ';
1976
-        if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
1977
-
1978
-        return $result;
1979
-    }
1980
-
1981
-    /**
1982
-     *    Return label of status (activity, closed)
1983
-     *
1984
-     *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
1985
-     *    @return   string        		Libelle
1986
-     */
1987
-    function getLibStatut($mode=0)
1988
-    {
1989
-        return $this->LibStatut($this->status,$mode);
1990
-    }
1991
-
1992
-    /**
1993
-     *  Renvoi le libelle d'un statut donne
1994
-     *
1995
-     *  @param	int		$statut         Id statut
1996
-     *  @param	int		$mode           0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1997
-     *  @return	string          		Libelle du statut
1998
-     */
1999
-    function LibStatut($statut,$mode=0)
2000
-    {
2001
-        global $langs;
2002
-        $langs->load('companies');
2003
-
2004
-        if ($mode == 0)
2005
-        {
2006
-            if ($statut==0) return $langs->trans("ActivityCeased");
2007
-            if ($statut==1) return $langs->trans("InActivity");
2008
-        }
2009
-        if ($mode == 1)
2010
-        {
2011
-            if ($statut==0) return $langs->trans("ActivityCeased");
2012
-            if ($statut==1) return $langs->trans("InActivity");
2013
-        }
2014
-        if ($mode == 2)
2015
-        {
2016
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2017
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2018
-        }
2019
-        if ($mode == 3)
2020
-        {
2021
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2022
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2023
-        }
2024
-        if ($mode == 4)
2025
-        {
2026
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2027
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2028
-        }
2029
-        if ($mode == 5)
2030
-        {
2031
-            if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2032
-            if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2033
-        }
2034
-    }
2035
-
2036
-    /**
2037
-     *    Return list of contacts emails existing for third party
2038
-     *
2039
-     *	  @param	  int		$addthirdparty		1=Add also a record for thirdparty email
2040
-     *    @return     array       					Array of contacts emails
2041
-     */
2042
-    function thirdparty_and_contact_email_array($addthirdparty=0)
2043
-    {
2044
-        global $langs;
2045
-
2046
-        $contact_emails = $this->contact_property_array('email',1);
2047
-        if ($this->email && $addthirdparty)
2048
-        {
2049
-            if (empty($this->name)) $this->name=$this->nom;
2050
-            $contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->email."&gt;";
2051
-        }
2052
-        //var_dump($contact_emails)
2053
-        return $contact_emails;
2054
-    }
2055
-
2056
-    /**
2057
-     *    Return list of contacts mobile phone existing for third party
2058
-     *
2059
-     *    @return     array       Array of contacts emails
2060
-     */
2061
-    function thirdparty_and_contact_phone_array()
2062
-    {
2063
-        global $langs;
2064
-
2065
-        $contact_phone = $this->contact_property_array('mobile');
2066
-
2067
-        if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2068
-        {
2069
-            if (empty($this->name)) $this->name=$this->nom;
2070
-            // TODO: Tester si tel non deja present dans tableau contact
2071
-            $contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->phone."&gt;";
2072
-        }
2073
-        return $contact_phone;
2074
-    }
2864
+	/**
2865
+	 *  Load information for tab info
2866
+	 *
2867
+	 *  @param  int		$id     Id of thirdparty to load
2868
+	 *  @return	void
2869
+	 */
2870
+	function info($id)
2871
+	{
2872
+		$sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
2873
+		$sql.= " fk_user_creat, fk_user_modif";
2874
+		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
2875
+		$sql.= " WHERE s.rowid = ".$id;
2075 2876
 
2076
-    /**
2077
-     *  Return list of contacts emails or mobile existing for third party
2078
-     *
2079
-     *  @param	string	$mode       		'email' or 'mobile'
2080
-	 * 	@param	int		$hidedisabled		1=Hide contact if disabled
2081
-     *  @return array       				Array of contacts emails or mobile array(id=>'Name <email>')
2082
-     */
2083
-    function contact_property_array($mode='email', $hidedisabled=0)
2084
-    {
2085
-    	global $langs;
2086
-
2087
-        $contact_property = array();
2088
-
2089
-
2090
-        $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2091
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2092
-        $sql.= " WHERE fk_soc = ".$this->id;
2093
-
2094
-        $resql=$this->db->query($sql);
2095
-        if ($resql)
2096
-        {
2097
-            $nump = $this->db->num_rows($resql);
2098
-            if ($nump)
2099
-            {
2100
-            	$sepa="("; $sepb=")";
2101
-            	if ($mode == 'email')
2102
-            	{
2103
-            		$sepa="&lt;"; $sepb="&gt;";
2104
-            	}
2105
-                $i = 0;
2106
-                while ($i < $nump)
2107
-                {
2108
-                    $obj = $this->db->fetch_object($resql);
2109
-                    if ($mode == 'email') $property=$obj->email;
2110
-                    else if ($mode == 'mobile') $property=$obj->phone_mobile;
2111
-                    else $property=$obj->$mode;
2877
+		$result=$this->db->query($sql);
2878
+		if ($result)
2879
+		{
2880
+			if ($this->db->num_rows($result))
2881
+			{
2882
+				$obj = $this->db->fetch_object($result);
2112 2883
 
2113
-					// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2114
-                    if ($obj->statut == 1 || empty($hidedisabled))
2115
-                    {
2116
-                    	if (empty($property))
2117
-                    	{
2118
-                    		if ($mode == 'email') $property=$langs->trans("NoEMail");
2119
-                    		else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone");
2120
-                    	}
2121
-
2122
-	                    if (!empty($obj->poste))
2123
-    	                {
2124
-							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2125
-						}
2126
-						else
2127
-						{
2128
-							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2129
-						}
2130
-                    }
2131
-                    $i++;
2132
-                }
2133
-            }
2134
-        }
2135
-        else
2136
-        {
2137
-            dol_print_error($this->db);
2138
-        }
2139
-        return $contact_property;
2140
-    }
2141
-
2142
-
2143
-    /**
2144
-     *    Renvoie la liste des contacts de cette societe
2145
-     *
2146
-     *    @return     array      tableau des contacts
2147
-     */
2148
-    function contact_array()
2149
-    {
2150
-        $contacts = array();
2151
-
2152
-        $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2153
-        $resql=$this->db->query($sql);
2154
-        if ($resql)
2155
-        {
2156
-            $nump = $this->db->num_rows($resql);
2157
-            if ($nump)
2158
-            {
2159
-                $i = 0;
2160
-                while ($i < $nump)
2161
-                {
2162
-                    $obj = $this->db->fetch_object($resql);
2163
-                    $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
2164
-                    $i++;
2165
-                }
2166
-            }
2167
-        }
2168
-        else
2169
-        {
2170
-            dol_print_error($this->db);
2171
-        }
2172
-        return $contacts;
2173
-    }
2174
-
2175
-    /**
2176
-     *    Renvoie la liste des contacts de cette societe
2177
-     *
2178
-     *    @return    array    $contacts    tableau des contacts
2179
-     */
2180
-    function contact_array_objects()
2181
-    {
2182
-        require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2183
-        $contacts = array();
2184
-
2185
-        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2186
-        $resql=$this->db->query($sql);
2187
-        if ($resql)
2188
-        {
2189
-            $nump = $this->db->num_rows($resql);
2190
-            if ($nump)
2191
-            {
2192
-                $i = 0;
2193
-                while ($i < $nump)
2194
-                {
2195
-                    $obj = $this->db->fetch_object($resql);
2196
-                    $contact = new Contact($this->db);
2197
-                    $contact->fetch($obj->rowid);
2198
-                    $contacts[] = $contact;
2199
-                    $i++;
2200
-                }
2201
-            }
2202
-        }
2203
-        else
2204
-        {
2205
-            dol_print_error($this->db);
2206
-        }
2207
-        return $contacts;
2208
-    }
2209
-
2210
-    /**
2211
-     *  Return property of contact from its id
2212
-     *
2213
-     *  @param	int		$rowid      id of contact
2214
-     *  @param  string	$mode       'email' or 'mobile'
2215
-     *  @return string  			Email of contact with format: "Full name <email>"
2216
-     */
2217
-    function contact_get_property($rowid,$mode)
2218
-    {
2219
-        $contact_property='';
2220
-
2221
-        if (empty($rowid)) return '';
2222
-
2223
-        $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2224
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2225
-        $sql.= " WHERE rowid = '".$rowid."'";
2226
-
2227
-        $resql=$this->db->query($sql);
2228
-        if ($resql)
2229
-        {
2230
-            $nump = $this->db->num_rows($resql);
2231
-
2232
-            if ($nump)
2233
-            {
2234
-                $obj = $this->db->fetch_object($resql);
2235
-
2236
-                if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
2237
-                else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2238
-            }
2239
-            return $contact_property;
2240
-        }
2241
-        else
2242
-        {
2243
-            dol_print_error($this->db);
2244
-        }
2884
+				$this->id = $obj->rowid;
2245 2885
 
2246
-    }
2886
+				if ($obj->fk_user_creat) {
2887
+					$cuser = new User($this->db);
2888
+					$cuser->fetch($obj->fk_user_creat);
2889
+					$this->user_creation     = $cuser;
2890
+				}
2247 2891
 
2892
+				if ($obj->fk_user_modif) {
2893
+					$muser = new User($this->db);
2894
+					$muser->fetch($obj->fk_user_modif);
2895
+					$this->user_modification = $muser;
2896
+				}
2248 2897
 
2249
-    /**
2250
-     *  Return bank number property of thirdparty (label or rum)
2251
-     *
2252
-     *	@param	string	$mode	'label' or 'rum'
2253
-     *  @return	string			Bank number
2254
-     */
2255
-    function display_rib($mode='label')
2256
-    {
2257
-        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2898
+				$this->ref			     = $obj->name;
2899
+				$this->date_creation     = $this->db->jdate($obj->date_creation);
2900
+				$this->date_modification = $this->db->jdate($obj->date_modification);
2901
+			}
2258 2902
 
2259
-        $bac = new CompanyBankAccount($this->db);
2260
-        $bac->fetch(0,$this->id);
2903
+			$this->db->free($result);
2261 2904
 
2262
-        if ($mode == 'label')
2263
-        {
2264
-        	return $bac->getRibLabel(true);
2265
-        }
2266
-        elseif ($mode == 'rum')
2267
-        {
2268
-        	if (empty($bac->rum))
2269
-        	{
2270
-        		require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2271
-        		$prelevement = new BonPrelevement($this->db);
2272
-        		$bac->fetch_thirdparty();
2273
-        		$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2274
-        	}
2275
-        	return $bac->rum;
2276
-        }
2905
+		}
2906
+		else
2907
+		{
2908
+			dol_print_error($this->db);
2909
+		}
2910
+	}
2277 2911
 
2278
-        return 'BadParameterToFunctionDisplayRib';
2279
-    }
2280
-
2281
-    /**
2282
-     * Return Array of RIB
2283
-     *
2284
-     * @return     array|int        0 if KO, Array of CompanyBanckAccount if OK
2285
-     */
2286
-    function get_all_rib()
2287
-    {
2288
-        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2289
-        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id;
2290
-        $result = $this->db->query($sql);
2291
-        if (!$result) {
2292
-            $this->error++;
2293
-            $this->errors[] = $this->db->lasterror;
2294
-            return 0;
2295
-        } else {
2296
-            $num_rows = $this->db->num_rows($result);
2297
-            $rib_array = array();
2298
-            if ($num_rows) {
2299
-                while ($obj = $this->db->fetch_object($result)) {
2300
-                    $rib = new CompanyBankAccount($this->db);
2301
-                    $rib->fetch($obj->rowid);
2302
-                    $rib_array[] = $rib;
2303
-                }
2304
-            }
2305
-            return $rib_array;
2306
-        }
2307
-    }
2308
-
2309
-    /**
2310
-     *  Attribut un code client a partir du module de controle des codes.
2311
-     *  Return value is stored into this->code_client
2312
-     *
2313
-     *	@param	Societe		$objsoc		Object thirdparty
2314
-     *	@param	int			$type		Should be 0 to say customer
2315
-     *  @return void
2316
-     */
2317
-    function get_codeclient($objsoc=0,$type=0)
2318
-    {
2319
-        global $conf;
2320
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2321
-        {
2322
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2323
-
2324
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2325
-            foreach ($dirsociete as $dirroot)
2326
-            {
2327
-                $res=dol_include_once($dirroot.$module.'.php');
2328
-                if ($res) break;
2329
-            }
2330
-            $mod = new $module();
2331
-
2332
-            $this->code_client = $mod->getNextValue($objsoc,$type);
2333
-            $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2334
-
2335
-            dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2336
-        }
2337
-    }
2338
-
2339
-    /**
2340
-     *  Attribut un code fournisseur a partir du module de controle des codes.
2341
-     *  Return value is stored into this->code_fournisseur
2342
-     *
2343
-     *	@param	Societe		$objsoc		Object thirdparty
2344
-     *	@param	int			$type		Should be 1 to say supplier
2345
-     *  @return void
2346
-     */
2347
-    function get_codefournisseur($objsoc=0,$type=1)
2348
-    {
2349
-        global $conf;
2350
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2351
-        {
2352
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2912
+	/**
2913
+	 *  Return if third party is a company (Business) or an end user (Consumer)
2914
+	 *
2915
+	 *  @return    boolean     true=is a company, false=a and user
2916
+	 */
2917
+	function isACompany()
2918
+	{
2919
+		global $conf;
2353 2920
 
2354
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2355
-            foreach ($dirsociete as $dirroot)
2356
-            {
2357
-                $res=dol_include_once($dirroot.$module.'.php');
2358
-                if ($res) break;
2359
-            }
2360
-            $mod = new $module();
2921
+		// Define if third party is treated as company (or not) when nature is unknown
2922
+		$isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
2923
+		if (! empty($this->tva_intra)) $isacompany=1;
2924
+		else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
2925
+		else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1;
2361 2926
 
2362
-            $this->code_fournisseur = $mod->getNextValue($objsoc,$type);
2927
+		return $isacompany;
2928
+	}
2363 2929
 
2364
-            dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2365
-        }
2366
-    }
2367
-
2368
-    /**
2369
-     *    Verifie si un code client est modifiable en fonction des parametres
2370
-     *    du module de controle des codes.
2371
-     *
2372
-     *    @return     int		0=No, 1=Yes
2373
-     */
2374
-    function codeclient_modifiable()
2375
-    {
2376
-        global $conf;
2377
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2378
-        {
2379
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2380
-
2381
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2382
-            foreach ($dirsociete as $dirroot)
2383
-            {
2384
-                $res=dol_include_once($dirroot.$module.'.php');
2385
-                if ($res) break;
2386
-            }
2387
-
2388
-            $mod = new $module();
2389
-
2390
-            dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2391
-            if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2392
-            if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2393
-            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2394
-            return 0;
2395
-        }
2396
-        else
2397
-        {
2398
-            return 0;
2399
-        }
2400
-    }
2401
-
2402
-
2403
-    /**
2404
-     *    Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
2405
-     *
2406
-     *    @return     int		0=No, 1=Yes
2407
-     */
2408
-    function codefournisseur_modifiable()
2409
-    {
2410
-        global $conf;
2411
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2412
-        {
2413
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2414
-
2415
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2416
-            foreach ($dirsociete as $dirroot)
2417
-            {
2418
-                $res=dol_include_once($dirroot.$module.'.php');
2419
-                if ($res) break;
2420
-            }
2421
-
2422
-            $mod = new $module();
2423
-
2424
-            dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2425
-            if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2426
-            if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2427
-            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2428
-            return 0;
2429
-        }
2430
-        else
2431
-        {
2432
-            return 0;
2433
-        }
2434
-    }
2435
-
2436
-
2437
-    /**
2438
-     *  Check customer code
2439
-     *
2440
-     *  @return     int				0 if OK
2441
-     * 								-1 ErrorBadCustomerCodeSyntax
2442
-     * 								-2 ErrorCustomerCodeRequired
2443
-     * 								-3 ErrorCustomerCodeAlreadyUsed
2444
-     * 								-4 ErrorPrefixRequired
2445
-     */
2446
-    function check_codeclient()
2447
-    {
2448
-        global $conf;
2449
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2450
-        {
2451
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2452
-
2453
-        	$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2454
-            foreach ($dirsociete as $dirroot)
2455
-            {
2456
-                $res=dol_include_once($dirroot.$module.'.php');
2457
-                if ($res) break;
2458
-            }
2459
-
2460
-            $mod = new $module();
2461
-
2462
-           	dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2463
-           	$result = $mod->verif($this->db, $this->code_client, $this, 0);
2464
-            return $result;
2465
-        }
2466
-        else
2930
+	/**
2931
+	 *  Charge la liste des categories fournisseurs
2932
+	 *
2933
+	 *  @return    int      0 if success, <> 0 if error
2934
+	 */
2935
+	function LoadSupplierCateg()
2936
+	{
2937
+		$this->SupplierCategories = array();
2938
+		$sql = "SELECT rowid, label";
2939
+		$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
2940
+		$sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
2941
+
2942
+		$resql=$this->db->query($sql);
2943
+		if ($resql)
2467 2944
 		{
2468
-            return 0;
2469
-        }
2470
-    }
2471
-
2472
-    /**
2473
-     *    Check supplier code
2474
-     *
2475
-     *    @return     int		0 if OK
2476
-     * 							-1 ErrorBadCustomerCodeSyntax
2477
-     * 							-2 ErrorCustomerCodeRequired
2478
-     * 							-3 ErrorCustomerCodeAlreadyUsed
2479
-     * 							-4 ErrorPrefixRequired
2480
-     */
2481
-    function check_codefournisseur()
2482
-    {
2483
-        global $conf;
2484
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2485
-        {
2486
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2487
-
2488
-        	$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2489
-            foreach ($dirsociete as $dirroot)
2490
-            {
2491
-                $res=dol_include_once($dirroot.$module.'.php');
2492
-                if ($res) break;
2493
-            }
2494
-
2495
-            $mod = new $module();
2496
-
2497
-            dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2498
-            $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2499
-            return $result;
2500
-        }
2501
-        else
2945
+			while ($obj = $this->db->fetch_object($resql) )
2946
+			{
2947
+				$this->SupplierCategories[$obj->rowid] = $obj->label;
2948
+			}
2949
+			return 0;
2950
+		}
2951
+		else
2502 2952
 		{
2503
-            return 0;
2504
-        }
2505
-    }
2506
-
2507
-    /**
2508
-     *    	Renvoie un code compta, suivant le module de code compta.
2509
-     *      Peut etre identique a celui saisit ou genere automatiquement.
2510
-     *      A ce jour seule la generation automatique est implementee
2511
-     *
2512
-     *    	@param	string	$type		Type of thirdparty ('customer' or 'supplier')
2513
-     *		@return	string				Code compta si ok, 0 si aucun, <0 si ko
2514
-     */
2515
-    function get_codecompta($type)
2516
-    {
2517
-        global $conf;
2518
-
2519
-        if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2520
-        {
2521
-        	$file='';
2522
-            $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2523
-            foreach ($dirsociete as $dirroot)
2524
-            {
2525
-            	if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
2526
-            	{
2527
-            		$file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
2528
-            		break;
2529
-            	}
2530
-            }
2531
-
2532
-            if (! empty($file))
2533
-            {
2534
-            	dol_include_once($file);
2535
-
2536
-            	$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
2537
-            	$mod = new $classname;
2538
-
2539
-            	// Defini code compta dans $mod->code
2540
-            	$result = $mod->get_code($this->db, $this, $type);
2541
-
2542
-            	if ($type == 'customer') $this->code_compta = $mod->code;
2543
-            	else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2544
-
2545
-            	return $result;
2546
-            }
2547
-            else
2548
-            {
2549
-            	$this->error = 'ErrorAccountancyCodeNotDefined';
2550
-            	return -1;
2551
-            }
2552
-        }
2553
-        else
2554
-        {
2555
-            if ($type == 'customer') $this->code_compta = '';
2556
-            else if ($type == 'supplier') $this->code_compta_fournisseur = '';
2557
-
2558
-            return 0;
2559
-        }
2560
-    }
2561
-
2562
-    /**
2563
-     *    Define parent commany of current company
2564
-     *
2565
-     *    @param	int		$id     Id of thirdparty to set or '' to remove
2566
-     *    @return	int     		<0 if KO, >0 if OK
2567
-     */
2568
-    function set_parent($id)
2569
-    {
2570
-        if ($this->id)
2571
-        {
2572
-            $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2573
-            $sql.= " SET parent = ".($id > 0 ? $id : "null");
2574
-            $sql.= " WHERE rowid = " . $this->id;
2575
-			dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2576
-            $resql=$this->db->query($sql);
2577
-            if ($resql)
2578
-            {
2579
-            	$this->parent = $id;
2580
-                return 1;
2581
-            }
2582
-            else
2583
-			{
2584
-                return -1;
2585
-            }
2586
-        }
2587
-        else return -1;
2588
-    }
2589
-
2590
-	/**
2591
-     *  Returns if a profid sould be verified
2592
-     *
2593
-     *  @param	int		$idprof		1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
2594
-     *  @return boolean         	true , false
2595
-     */
2596
-    function id_prof_verifiable($idprof)
2597
-    {
2598
-	    global $conf;
2599
-
2600
-     	switch($idprof)
2601
-        {
2602
-        	case 1:
2603
-        		$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2604
-        		break;
2605
-        	case 2:
2606
-        		$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2607
-        		break;
2608
-        	case 3:
2609
-        		$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2610
-        		break;
2611
-        	case 4:
2612
-        		$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2613
-        		break;
2614
-        	case 5:
2615
-        		$ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2616
-        		break;
2617
-        	case 6:
2618
-        		$ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2619
-        		break;
2620
-        	default:
2621
-        		$ret=false;
2622
-        }
2953
+			return -1;
2954
+		}
2955
+	}
2623 2956
 
2624
-        return $ret;
2625
-    }
2626
-
2627
-	/**
2628
-     *    Verify if a profid exists into database for others thirds
2629
-     *
2630
-     *    @param	string	$idprof		'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
2631
-     *    @param	string	$value		Value of profid
2632
-     *    @param	int		$socid		Id of thirdparty to exclude (if update)
2633
-     *    @return   boolean				True if exists, False if not
2634
-     */
2635
-    function id_prof_exists($idprof, $value, $socid=0)
2636
-    {
2637
-    	$field = $idprof;
2638
-
2639
-     	switch($idprof)	// For backward compatibility
2640
-        {
2641
-        	case '1':
2642
-        	case 'idprof1':
2643
-        		$field="siren";
2644
-        		break;
2645
-        	case '2':
2646
-        	case 'idprof2':
2647
-        		$field="siret";
2648
-        		break;
2649
-        	case '3':
2650
-        	case 'idprof3':
2651
-        		$field="ape";
2652
-        		break;
2653
-        	case '4':
2654
-        	case 'idprof4':
2655
-        		$field="idprof4";
2656
-        		break;
2657
-        	case '5':
2658
-        		$field="idprof5";
2659
-        		break;
2660
-        	case '6':
2661
-        		$field="idprof6";
2662
-        		break;
2663
-     	}
2664
-
2665
-         //Verify duplicate entries
2666
-        $sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2667
-        if($socid) $sql .= " AND rowid <> ".$socid;
2668
-        $resql = $this->db->query($sql);
2669
-        if ($resql)
2670
-        {
2671
-            $obj = $this->db->fetch_object($resql);
2672
-            $count = $obj->idprof;
2673
-        }
2674
-        else
2675
-        {
2676
-            $count = 0;
2677
-            print $this->db->error();
2678
-        }
2679
-        $this->db->free($resql);
2957
+	/**
2958
+	 *  Insert link supplier - category
2959
+	 *
2960
+	 *	@param	int		$categorie_id		Id of category
2961
+	 *  @return int      					0 if success, <> 0 if error
2962
+	 */
2963
+	function AddFournisseurInCategory($categorie_id)
2964
+	{
2965
+		if ($categorie_id > 0 && $this->id > 0)
2966
+		{
2967
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
2968
+			$sql.= " VALUES (".$categorie_id.", ".$this->id.")";
2680 2969
 
2681
-		if ($count > 0) return true;
2682
-		else return false;
2683
-    }
2684
-
2685
-    /**
2686
-     *  Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
2687
-     *
2688
-     *  @param	int			$idprof         1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
2689
-     *  @param  Societe		$soc            Objet societe
2690
-     *  @return int             			<=0 if KO, >0 if OK
2691
-     *  TODO better to have this in a lib than into a business class
2692
-     */
2693
-    function id_prof_check($idprof,$soc)
2694
-    {
2695
-        global $conf;
2696
-
2697
-        $ok=1;
2698
-
2699
-        if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2700
-
2701
-        // Verifie SIREN si pays FR
2702
-        if ($idprof == 1 && $soc->country_code == 'FR')
2703
-        {
2704
-            $chaine=trim($this->idprof1);
2705
-            $chaine=preg_replace('/(\s)/','',$chaine);
2706
-
2707
-            if (dol_strlen($chaine) != 9) return -1;
2708
-
2709
-            $sum = 0;
2710
-
2711
-            for ($i = 0 ; $i < 10 ; $i = $i+2)
2712
-            {
2713
-                $sum = $sum + substr($this->idprof1, (8 - $i), 1);
2714
-            }
2715
-
2716
-            for ($i = 1 ; $i < 9 ; $i = $i+2)
2717
-            {
2718
-                $ps = 2 * substr($this->idprof1, (8 - $i), 1);
2719
-
2720
-                if ($ps > 9)
2721
-                {
2722
-                    $ps = substr($ps, 0,1) + substr($ps, 1, 1);
2723
-                }
2724
-                $sum = $sum + $ps;
2725
-            }
2726
-
2727
-            if (substr($sum, -1) != 0) return -1;
2728
-        }
2970
+			if ($resql=$this->db->query($sql)) return 0;
2971
+		}
2972
+		else
2973
+		{
2974
+			return 0;
2975
+		}
2976
+		return -1;
2977
+	}
2729 2978
 
2730
-        // Verifie SIRET si pays FR
2731
-        if ($idprof == 2 && $soc->country_code == 'FR')
2732
-        {
2733
-            $chaine=trim($this->idprof2);
2734
-            $chaine=preg_replace('/(\s)/','',$chaine);
2735 2979
 
2736
-            if (dol_strlen($chaine) != 14) return -1;
2737
-        }
2980
+	/**
2981
+	 *  Create a third party into database from a member object
2982
+	 *
2983
+	 *  @param	Adherent	$member		Object member
2984
+	 * 	@param	string	$socname	Name of third party to force
2985
+	 *  @return int					<0 if KO, id of created account if OK
2986
+	 */
2987
+	function create_from_member(Adherent $member,$socname='')
2988
+	{
2989
+		global $user,$langs;
2990
+
2991
+		$name = $socname?$socname:$member->societe;
2992
+		if (empty($name)) $name=$member->getFullName($langs);
2993
+
2994
+		// Positionne parametres
2995
+		$this->nom=$name;				// TODO deprecated
2996
+		$this->name=$name;
2997
+		$this->address=$member->address;
2998
+		$this->zip=$member->zip;
2999
+		$this->town=$member->town;
3000
+		$this->country_code=$member->country_code;
3001
+		$this->country_id=$member->country_id;
3002
+		$this->phone=$member->phone;       // Prof phone
3003
+		$this->email=$member->email;
3004
+		$this->skype=$member->skype;
3005
+
3006
+		$this->client = 1;				// A member is a customer by default
3007
+		$this->code_client = -1;
3008
+		$this->code_fournisseur = -1;
3009
+
3010
+		$this->db->begin();
3011
+
3012
+		// Cree et positionne $this->id
3013
+		$result=$this->create($user);
3014
+		if ($result >= 0)
3015
+		{
3016
+			$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3017
+			$sql.= " SET fk_soc=".$this->id;
3018
+			$sql.= " WHERE rowid=".$member->id;
2738 3019
 
2739
-        //Verify CIF/NIF/NIE if pays ES
2740
-        //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
2741
-        if ($idprof == 1 && $soc->country_code == 'ES')
2742
-        {
2743
-            $string=trim($this->idprof1);
2744
-            $string=preg_replace('/(\s)/','',$string);
2745
-            $string = strtoupper($string);
2746
-
2747
-            for ($i = 0; $i < 9; $i ++)
2748
-            $num[$i] = substr($string, $i, 1);
2749
-
2750
-            //Check format
2751
-            if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
2752
-            return 0;
2753
-
2754
-            //Check NIF
2755
-            if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
2756
-            if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
2757
-            return 1;
2758
-            else
2759
-            return -1;
2760
-
2761
-            //algorithm checking type code CIF
2762
-            $sum = $num[2] + $num[4] + $num[6];
2763
-            for ($i = 1; $i < 8; $i += 2)
2764
-            $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
2765
-            $n = 10 - substr($sum, strlen($sum) - 1, 1);
2766
-
2767
-            //Chek special NIF
2768
-            if (preg_match('/^[KLM]{1}/', $string))
2769
-            if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
2770
-            return 1;
2771
-            else
2772
-            return -1;
2773
-
2774
-            //Check CIF
2775
-            if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
2776
-            if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
2777
-            return 2;
2778
-            else
2779
-            return -2;
2780
-
2781
-            //Check NIE T
2782
-            if (preg_match('/^[T]{1}/', $string))
2783
-            if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
2784
-            return 3;
2785
-            else
2786
-            return -3;
2787
-
2788
-            //Check NIE XYZ
2789
-            if (preg_match('/^[XYZ]{1}/', $string))
2790
-            if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
2791
-            return 3;
2792
-            else
2793
-            return -3;
2794
-
2795
-            //Can not be verified
2796
-            return -4;
2797
-        }
3020
+			dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3021
+			$resql=$this->db->query($sql);
3022
+			if ($resql)
3023
+			{
3024
+				$this->db->commit();
3025
+				return $this->id;
3026
+			}
3027
+			else
3028
+			{
3029
+				$this->error=$this->db->error();
2798 3030
 
2799
-        return $ok;
2800
-    }
2801
-
2802
-    /**
2803
-     *   Return an url to check online a professional id or empty string
2804
-     *
2805
-     *   @param		int		$idprof         1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
2806
-     *   @param 	Societe	$thirdparty     Object thirdparty
2807
-     *   @return	string          		Url or empty string if no URL known
2808
-     *   TODO better in a lib than into business class
2809
-     */
2810
-    function id_prof_url($idprof,$thirdparty)
2811
-    {
2812
-        global $conf,$langs,$hookmanager;
2813
-
2814
-        $url='';
2815
-        $action = '';
2816
-
2817
-        $hookmanager->initHooks(array('idprofurl'));
2818
-        $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
2819
-        $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2820
-        if (empty($reshook))
2821
-        {
2822
-            if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
2823
-
2824
-            // TODO Move links to validate professional ID into a dictionary table "country" + "link"
2825
-            if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1;    // See also http://avis-situation-sirene.insee.fr/
2826
-            //if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/';     // Link no more valid
2827
-            if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
2828
-            if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
2829
-
2830
-            if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
2831
-        }
2832
-        else
2833
-        {
2834
-            return $hookmanager->resPrint;
2835
-        }
3031
+				$this->db->rollback();
3032
+				return -1;
3033
+			}
3034
+		}
3035
+		else
3036
+		{
3037
+			// $this->error deja positionne
3038
+			dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
2836 3039
 
2837
-        return '';
2838
-    }
2839
-
2840
-    /**
2841
-     *   Indique si la societe a des projets
2842
-     *
2843
-     *   @return     bool	   true si la societe a des projets, false sinon
2844
-     */
2845
-    function has_projects()
2846
-    {
2847
-        $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
2848
-        $resql = $this->db->query($sql);
2849
-        if ($resql)
2850
-        {
2851
-            $obj = $this->db->fetch_object($resql);
2852
-            $count = $obj->numproj;
2853
-        }
2854
-        else
2855
-        {
2856
-            $count = 0;
2857
-            print $this->db->error();
2858
-        }
2859
-        $this->db->free($resql);
2860
-        return ($count > 0);
2861
-    }
2862
-
2863
-
2864
-    /**
2865
-     *  Load information for tab info
2866
-     *
2867
-     *  @param  int		$id     Id of thirdparty to load
2868
-     *  @return	void
2869
-     */
2870
-    function info($id)
2871
-    {
2872
-        $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
2873
-        $sql.= " fk_user_creat, fk_user_modif";
2874
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
2875
-        $sql.= " WHERE s.rowid = ".$id;
2876
-
2877
-        $result=$this->db->query($sql);
2878
-        if ($result)
2879
-        {
2880
-            if ($this->db->num_rows($result))
2881
-            {
2882
-                $obj = $this->db->fetch_object($result);
2883
-
2884
-                $this->id = $obj->rowid;
2885
-
2886
-                if ($obj->fk_user_creat) {
2887
-                    $cuser = new User($this->db);
2888
-                    $cuser->fetch($obj->fk_user_creat);
2889
-                    $this->user_creation     = $cuser;
2890
-                }
2891
-
2892
-                if ($obj->fk_user_modif) {
2893
-                    $muser = new User($this->db);
2894
-                    $muser->fetch($obj->fk_user_modif);
2895
-                    $this->user_modification = $muser;
2896
-                }
2897
-
2898
-                $this->ref			     = $obj->name;
2899
-                $this->date_creation     = $this->db->jdate($obj->date_creation);
2900
-                $this->date_modification = $this->db->jdate($obj->date_modification);
2901
-            }
2902
-
2903
-            $this->db->free($result);
3040
+			$this->db->rollback();
3041
+			return $result;
3042
+		}
3043
+	}
2904 3044
 
2905
-        }
2906
-        else
2907
-		{
2908
-            dol_print_error($this->db);
2909
-        }
2910
-    }
2911
-
2912
-    /**
2913
-     *  Return if third party is a company (Business) or an end user (Consumer)
2914
-     *
2915
-     *  @return    boolean     true=is a company, false=a and user
2916
-     */
2917
-    function isACompany()
2918
-    {
2919
-        global $conf;
2920
-
2921
-        // Define if third party is treated as company (or not) when nature is unknown
2922
-        $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
2923
-        if (! empty($this->tva_intra)) $isacompany=1;
2924
-        else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
2925
-        else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1;
2926
-
2927
-        return $isacompany;
2928
-    }
2929
-
2930
-    /**
2931
-     *  Charge la liste des categories fournisseurs
2932
-     *
2933
-     *  @return    int      0 if success, <> 0 if error
2934
-     */
2935
-    function LoadSupplierCateg()
2936
-    {
2937
-        $this->SupplierCategories = array();
2938
-        $sql = "SELECT rowid, label";
2939
-        $sql.= " FROM ".MAIN_DB_PREFIX."categorie";
2940
-        $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
2941
-
2942
-        $resql=$this->db->query($sql);
2943
-        if ($resql)
2944
-        {
2945
-            while ($obj = $this->db->fetch_object($resql) )
2946
-            {
2947
-                $this->SupplierCategories[$obj->rowid] = $obj->label;
2948
-            }
2949
-            return 0;
2950
-        }
2951
-        else
2952
-        {
2953
-            return -1;
2954
-        }
2955
-    }
2956
-
2957
-    /**
2958
-     *  Insert link supplier - category
2959
-     *
2960
-     *	@param	int		$categorie_id		Id of category
2961
-     *  @return int      					0 if success, <> 0 if error
2962
-     */
2963
-    function AddFournisseurInCategory($categorie_id)
2964
-    {
2965
-        if ($categorie_id > 0 && $this->id > 0)
2966
-        {
2967
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
2968
-            $sql.= " VALUES (".$categorie_id.", ".$this->id.")";
2969
-
2970
-            if ($resql=$this->db->query($sql)) return 0;
2971
-        }
2972
-        else
2973
-        {
2974
-            return 0;
2975
-        }
2976
-        return -1;
2977
-    }
2978
-
2979
-
2980
-    /**
2981
-     *  Create a third party into database from a member object
2982
-     *
2983
-     *  @param	Adherent	$member		Object member
2984
-     * 	@param	string	$socname	Name of third party to force
2985
-     *  @return int					<0 if KO, id of created account if OK
2986
-     */
2987
-    function create_from_member(Adherent $member,$socname='')
2988
-    {
2989
-        global $user,$langs;
2990
-
2991
-        $name = $socname?$socname:$member->societe;
2992
-        if (empty($name)) $name=$member->getFullName($langs);
2993
-
2994
-        // Positionne parametres
2995
-        $this->nom=$name;				// TODO deprecated
2996
-        $this->name=$name;
2997
-        $this->address=$member->address;
2998
-        $this->zip=$member->zip;
2999
-        $this->town=$member->town;
3000
-        $this->country_code=$member->country_code;
3001
-        $this->country_id=$member->country_id;
3002
-        $this->phone=$member->phone;       // Prof phone
3003
-        $this->email=$member->email;
3004
-        $this->skype=$member->skype;
3005
-
3006
-        $this->client = 1;				// A member is a customer by default
3007
-        $this->code_client = -1;
3008
-        $this->code_fournisseur = -1;
3009
-
3010
-        $this->db->begin();
3011
-
3012
-        // Cree et positionne $this->id
3013
-        $result=$this->create($user);
3014
-        if ($result >= 0)
3015
-        {
3016
-            $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3017
-            $sql.= " SET fk_soc=".$this->id;
3018
-            $sql.= " WHERE rowid=".$member->id;
3019
-
3020
-            dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3021
-            $resql=$this->db->query($sql);
3022
-            if ($resql)
3023
-            {
3024
-                $this->db->commit();
3025
-                return $this->id;
3026
-            }
3027
-            else
3028
-            {
3029
-                $this->error=$this->db->error();
3030
-
3031
-                $this->db->rollback();
3032
-                return -1;
3033
-            }
3034
-        }
3035
-        else
3036
-        {
3037
-            // $this->error deja positionne
3038
-            dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
3045
+	/**
3046
+	 * 	Set properties with value into $conf
3047
+	 *
3048
+	 * 	@param	Conf	$conf		Conf object (possibility to use another entity)
3049
+	 * 	@return	void
3050
+	 */
3051
+	function setMysoc(Conf $conf)
3052
+	{
3053
+		global $langs;
3039 3054
 
3040
-            $this->db->rollback();
3041
-            return $result;
3042
-        }
3043
-    }
3044
-
3045
-    /**
3046
-     * 	Set properties with value into $conf
3047
-     *
3048
-     * 	@param	Conf	$conf		Conf object (possibility to use another entity)
3049
-     * 	@return	void
3050
-     */
3051
-    function setMysoc(Conf $conf)
3052
-    {
3053
-    	global $langs;
3054
-
3055
-    	$this->id=0;
3056
-    	$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3057
-    	$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3058
-    	$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3059
-    	$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3055
+		$this->id=0;
3056
+		$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3057
+		$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3058
+		$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3059
+		$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3060 3060
 		$this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
3061 3061
 
3062
-        /* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only.
3062
+		/* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only.
3063 3063
         If we need label, label must be loaded by output that need it from id (label depends on output language)
3064 3064
         require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
3065 3065
         if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
@@ -3068,165 +3068,165 @@  discard block
 block discarded – undo
3068 3068
         }
3069 3069
 		*/
3070 3070
 
3071
-    	$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3072
-
3073
-    	$this->nom=$this->name; 									// deprecated
3074
-
3075
-    	// We define country_id, country_code and country
3076
-    	$country_id=$country_code=$country_label='';
3077
-    	if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3078
-    	{
3079
-    		$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3080
-    		$country_id=$tmp[0];
3081
-    		if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3082
-    		{
3083
-    			$country_code=$tmp[1];
3084
-    			$country_label=$tmp[2];
3085
-    		}
3086
-    		else                    // For backward compatibility
3087
-    		{
3088
-    			dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3089
-    			include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3090
-    			$country_code=getCountry($country_id,2,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3091
-    			$country_label=getCountry($country_id,0,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3092
-    		}
3093
-    	}
3094
-    	$this->country_id=$country_id;
3095
-    	$this->country_code=$country_code;
3096
-    	$this->country=$country_label;
3097
-    	if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3098
-
3099
-    	$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3100
-    	$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3101
-    	$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3102
-    	// Id prof generiques
3103
-    	$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3104
-    	$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3105
-    	$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3106
-    	$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3107
-    	$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3108
-    	$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3109
-    	$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3110
-    	$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3111
-    	$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3112
-    	$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3113
-    	$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3114
-    	$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3115
-    	$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3116
-    	$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3117
-
3118
-    	// Define if company use vat or not
3119
-    	$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3120
-
3121
-    	// Define if company use local taxes
3122
-    	$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
3123
-    	$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
3124
-    }
3125
-
3126
-    /**
3127
-     *  Initialise an instance with random values.
3128
-     *  Used to build previews or test instances.
3129
-     *	id must be 0 if object instance is a specimen.
3130
-     *
3131
-     *  @return	void
3132
-     */
3133
-    function initAsSpecimen()
3134
-    {
3135
-        $now=dol_now();
3136
-
3137
-        // Initialize parameters
3138
-        $this->id=0;
3139
-        $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
3140
-        $this->nom = $this->name;   // For backward compatibility
3141
-        $this->ref_ext = 'Ref ext';
3142
-        $this->specimen=1;
3143
-        $this->address='21 jump street';
3144
-        $this->zip='99999';
3145
-        $this->town='MyTown';
3146
-        $this->state_id=1;
3147
-        $this->state_code='AA';
3148
-        $this->state='MyState';
3149
-        $this->country_id=1;
3150
-        $this->country_code='FR';
3151
-        $this->email='[email protected]';
3152
-        $this->skype='tom.hanson';
3153
-        $this->url='http://www.specimen.com';
3154
-
3155
-        $this->phone='0909090901';
3156
-        $this->fax='0909090909';
3157
-
3158
-        $this->code_client='CC-'.dol_print_date($now,'dayhourlog');
3159
-        $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
3160
-        $this->capital=10000;
3161
-        $this->client=1;
3162
-        $this->prospect=1;
3163
-        $this->fournisseur=1;
3164
-        $this->tva_assuj=1;
3165
-        $this->tva_intra='EU1234567';
3166
-        $this->note_public='This is a comment (public)';
3167
-        $this->note_private='This is a comment (private)';
3168
-
3169
-        $this->idprof1='idprof1';
3170
-        $this->idprof2='idprof2';
3171
-        $this->idprof3='idprof3';
3172
-        $this->idprof4='idprof4';
3173
-        $this->idprof5='idprof5';
3174
-        $this->idprof6='idprof6';
3175
-    }
3176
-
3177
-    /**
3178
-     *  Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
3179
-     *
3180
-     *	@param		int		$localTaxNum	To get info for only localtax1 or localtax2
3181
-     *  @return		boolean					true or false
3182
-     */
3183
-    function useLocalTax($localTaxNum=0)
3184
-    {
3185
-    	$sql  = "SELECT t.localtax1, t.localtax2";
3186
-    	$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3187
-    	$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3188
-    	$sql .= " AND t.active = 1";
3189
-    	if (empty($localTaxNum))   $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3190
-    	elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3191
-    	elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3192
-
3193
-    	dol_syslog("useLocalTax", LOG_DEBUG);
3194
-    	$resql=$this->db->query($sql);
3195
-    	if ($resql)
3196
-    	{
3071
+		$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3072
+
3073
+		$this->nom=$this->name; 									// deprecated
3074
+
3075
+		// We define country_id, country_code and country
3076
+		$country_id=$country_code=$country_label='';
3077
+		if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3078
+		{
3079
+			$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3080
+			$country_id=$tmp[0];
3081
+			if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3082
+			{
3083
+				$country_code=$tmp[1];
3084
+				$country_label=$tmp[2];
3085
+			}
3086
+			else                    // For backward compatibility
3087
+			{
3088
+				dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3089
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3090
+				$country_code=getCountry($country_id,2,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3091
+				$country_label=getCountry($country_id,0,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3092
+			}
3093
+		}
3094
+		$this->country_id=$country_id;
3095
+		$this->country_code=$country_code;
3096
+		$this->country=$country_label;
3097
+		if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3098
+
3099
+		$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3100
+		$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3101
+		$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3102
+		// Id prof generiques
3103
+		$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3104
+		$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3105
+		$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3106
+		$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3107
+		$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3108
+		$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3109
+		$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3110
+		$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3111
+		$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3112
+		$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3113
+		$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3114
+		$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3115
+		$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3116
+		$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3117
+
3118
+		// Define if company use vat or not
3119
+		$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3120
+
3121
+		// Define if company use local taxes
3122
+		$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
3123
+		$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
3124
+	}
3125
+
3126
+	/**
3127
+	 *  Initialise an instance with random values.
3128
+	 *  Used to build previews or test instances.
3129
+	 *	id must be 0 if object instance is a specimen.
3130
+	 *
3131
+	 *  @return	void
3132
+	 */
3133
+	function initAsSpecimen()
3134
+	{
3135
+		$now=dol_now();
3136
+
3137
+		// Initialize parameters
3138
+		$this->id=0;
3139
+		$this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
3140
+		$this->nom = $this->name;   // For backward compatibility
3141
+		$this->ref_ext = 'Ref ext';
3142
+		$this->specimen=1;
3143
+		$this->address='21 jump street';
3144
+		$this->zip='99999';
3145
+		$this->town='MyTown';
3146
+		$this->state_id=1;
3147
+		$this->state_code='AA';
3148
+		$this->state='MyState';
3149
+		$this->country_id=1;
3150
+		$this->country_code='FR';
3151
+		$this->email='[email protected]';
3152
+		$this->skype='tom.hanson';
3153
+		$this->url='http://www.specimen.com';
3154
+
3155
+		$this->phone='0909090901';
3156
+		$this->fax='0909090909';
3157
+
3158
+		$this->code_client='CC-'.dol_print_date($now,'dayhourlog');
3159
+		$this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
3160
+		$this->capital=10000;
3161
+		$this->client=1;
3162
+		$this->prospect=1;
3163
+		$this->fournisseur=1;
3164
+		$this->tva_assuj=1;
3165
+		$this->tva_intra='EU1234567';
3166
+		$this->note_public='This is a comment (public)';
3167
+		$this->note_private='This is a comment (private)';
3168
+
3169
+		$this->idprof1='idprof1';
3170
+		$this->idprof2='idprof2';
3171
+		$this->idprof3='idprof3';
3172
+		$this->idprof4='idprof4';
3173
+		$this->idprof5='idprof5';
3174
+		$this->idprof6='idprof6';
3175
+	}
3176
+
3177
+	/**
3178
+	 *  Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
3179
+	 *
3180
+	 *	@param		int		$localTaxNum	To get info for only localtax1 or localtax2
3181
+	 *  @return		boolean					true or false
3182
+	 */
3183
+	function useLocalTax($localTaxNum=0)
3184
+	{
3185
+		$sql  = "SELECT t.localtax1, t.localtax2";
3186
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3187
+		$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3188
+		$sql .= " AND t.active = 1";
3189
+		if (empty($localTaxNum))   $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3190
+		elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3191
+		elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3192
+
3193
+		dol_syslog("useLocalTax", LOG_DEBUG);
3194
+		$resql=$this->db->query($sql);
3195
+		if ($resql)
3196
+		{
3197 3197
    			return ($this->db->num_rows($resql) > 0);
3198
-    	}
3199
-    	else return false;
3200
-    }
3201
-
3202
-    /**
3203
-     *  Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
3204
-     *
3205
-     *  @return		boolean					true or false
3206
-     */
3207
-    function useNPR()
3208
-    {
3209
-        $sql  = "SELECT t.rowid";
3210
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3211
-        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3212
-        $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3213
-
3214
-        dol_syslog("useNPR", LOG_DEBUG);
3215
-        $resql=$this->db->query($sql);
3216
-        if ($resql)
3217
-        {
3218
-            return ($this->db->num_rows($resql) > 0);
3219
-        }
3220
-        else return false;
3221
-    }
3222
-
3223
-    /**
3224
-     *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
3225
-     *
3226
-     *  @return		boolean			true or false
3227
-     */
3228
-    function useRevenueStamp()
3229
-    {
3198
+		}
3199
+		else return false;
3200
+	}
3201
+
3202
+	/**
3203
+	 *  Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
3204
+	 *
3205
+	 *  @return		boolean					true or false
3206
+	 */
3207
+	function useNPR()
3208
+	{
3209
+		$sql  = "SELECT t.rowid";
3210
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3211
+		$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3212
+		$sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3213
+
3214
+		dol_syslog("useNPR", LOG_DEBUG);
3215
+		$resql=$this->db->query($sql);
3216
+		if ($resql)
3217
+		{
3218
+			return ($this->db->num_rows($resql) > 0);
3219
+		}
3220
+		else return false;
3221
+	}
3222
+
3223
+	/**
3224
+	 *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
3225
+	 *
3226
+	 *  @return		boolean			true or false
3227
+	 */
3228
+	function useRevenueStamp()
3229
+	{
3230 3230
 		$sql  = "SELECT COUNT(*) as nb";
3231 3231
 		$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
3232 3232
 		$sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
@@ -3281,11 +3281,11 @@  discard block
 block discarded – undo
3281 3281
 	 *
3282 3282
 	 *  @param  User	$user		Utilisateur qui definie la remise
3283 3283
 	 *	@return	int					<0 if KO, >0 if OK
3284
-     * @deprecated Use update function instead
3284
+	 * @deprecated Use update function instead
3285 3285
 	 */
3286 3286
 	function set_prospect_level(User $user)
3287 3287
 	{
3288
-        return $this->update($this->id, $user);
3288
+		return $this->update($this->id, $user);
3289 3289
 	}
3290 3290
 
3291 3291
 	/**
@@ -3358,11 +3358,11 @@  discard block
 block discarded – undo
3358 3358
 	 *
3359 3359
 	 *  @param  User	$user		User making change
3360 3360
 	 *	@return	int					<0 if KO, >0 if OK
3361
-     * @deprecated Use update function instead
3361
+	 * @deprecated Use update function instead
3362 3362
 	 */
3363 3363
 	function set_OutstandingBill(User $user)
3364 3364
 	{
3365
-        return $this->update($this->id, $user);
3365
+		return $this->update($this->id, $user);
3366 3366
 	}
3367 3367
 
3368 3368
 	/**
@@ -3526,39 +3526,39 @@  discard block
 block discarded – undo
3526 3526
 	 */
3527 3527
 	function get_OutstandingBill()
3528 3528
 	{
3529
-	    /* Accurate value of remain to pay is to sum remaintopay for each invoice
3529
+		/* Accurate value of remain to pay is to sum remaintopay for each invoice
3530 3530
 	     $paiement = $invoice->getSommePaiement();
3531 3531
 	     $creditnotes=$invoice->getSumCreditNotesUsed();
3532 3532
 	     $deposits=$invoice->getSumDepositsUsed();
3533 3533
 	     $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3534 3534
 	     $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3535 3535
 	     */
3536
-	    $sql  = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3537
-	    $sql .= " WHERE fk_soc = ". $this->id;
3538
-	    $sql .= " AND paye = 0";
3539
-	    $sql .= " AND fk_statut <> 0";	// Not a draft
3540
-	    //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3541
-	    $sql .= " AND fk_statut <> 3";		// Not abandonned
3542
-	    $sql .= " AND fk_statut <> 2";		// Not clasified as paid
3543
-
3544
-	    dol_syslog("get_OutstandingBill", LOG_DEBUG);
3545
-	    $resql=$this->db->query($sql);
3546
-	    if ($resql)
3547
-	    {
3548
-	        $outstandingAmount = 0;
3549
-	        require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3550
-	        $tmpobject=new Facture($this->db);
3551
-	        while($obj=$this->db->fetch_object($resql)) {
3552
-	            $tmpobject->id=$obj->rowid;
3553
-	            $paiement = $tmpobject->getSommePaiement();
3554
-	            $creditnotes = $tmpobject->getSumCreditNotesUsed();
3555
-	            $deposits = $tmpobject->getSumDepositsUsed();
3556
-	            $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3557
-	        }
3558
-	        return $outstandingAmount;
3559
-	    }
3560
-	    else
3561
-	        return 0;
3536
+		$sql  = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3537
+		$sql .= " WHERE fk_soc = ". $this->id;
3538
+		$sql .= " AND paye = 0";
3539
+		$sql .= " AND fk_statut <> 0";	// Not a draft
3540
+		//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3541
+		$sql .= " AND fk_statut <> 3";		// Not abandonned
3542
+		$sql .= " AND fk_statut <> 2";		// Not clasified as paid
3543
+
3544
+		dol_syslog("get_OutstandingBill", LOG_DEBUG);
3545
+		$resql=$this->db->query($sql);
3546
+		if ($resql)
3547
+		{
3548
+			$outstandingAmount = 0;
3549
+			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3550
+			$tmpobject=new Facture($this->db);
3551
+			while($obj=$this->db->fetch_object($resql)) {
3552
+				$tmpobject->id=$obj->rowid;
3553
+				$paiement = $tmpobject->getSommePaiement();
3554
+				$creditnotes = $tmpobject->getSumCreditNotesUsed();
3555
+				$deposits = $tmpobject->getSumDepositsUsed();
3556
+				$outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3557
+			}
3558
+			return $outstandingAmount;
3559
+		}
3560
+		else
3561
+			return 0;
3562 3562
 	}
3563 3563
 
3564 3564
 	/**
@@ -3607,33 +3607,33 @@  discard block
 block discarded – undo
3607 3607
 
3608 3608
 		if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
3609 3609
 		{
3610
-		    $modelpath = "core/modules/bank/doc/";
3610
+			$modelpath = "core/modules/bank/doc/";
3611 3611
 
3612
-		    include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3613
-		    $companybankaccount = new CompanyBankAccount($this->db);
3614
-		    $result = $companybankaccount->fetch($moreparams['use_companybankid']);
3615
-		    if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3616
-		    $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3612
+			include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3613
+			$companybankaccount = new CompanyBankAccount($this->db);
3614
+			$result = $companybankaccount->fetch($moreparams['use_companybankid']);
3615
+			if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3616
+			$result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3617 3617
 		}
3618 3618
 		else
3619 3619
 		{
3620
-    		// Positionne le modele sur le nom du modele a utiliser
3621
-    		if (! dol_strlen($modele))
3622
-    		{
3623
-    			if (! empty($conf->global->COMPANY_ADDON_PDF))
3624
-    			{
3625
-    				$modele = $conf->global->COMPANY_ADDON_PDF;
3626
-    			}
3627
-    			else
3628
-    			{
3629
-    				print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3630
-                    return 0;
3631
-    			}
3632
-    		}
3620
+			// Positionne le modele sur le nom du modele a utiliser
3621
+			if (! dol_strlen($modele))
3622
+			{
3623
+				if (! empty($conf->global->COMPANY_ADDON_PDF))
3624
+				{
3625
+					$modele = $conf->global->COMPANY_ADDON_PDF;
3626
+				}
3627
+				else
3628
+				{
3629
+					print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3630
+					return 0;
3631
+				}
3632
+			}
3633 3633
 
3634
-    		$modelpath = "core/modules/societe/doc/";
3634
+			$modelpath = "core/modules/societe/doc/";
3635 3635
 
3636
-    		$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3636
+			$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3637 3637
 		}
3638 3638
 
3639 3639
 		return $result;
@@ -3654,7 +3654,7 @@  discard block
 block discarded – undo
3654 3654
 	{
3655 3655
 		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3656 3656
 
3657
-	    // Decode type
3657
+		// Decode type
3658 3658
 		if ($type == 'customer') {
3659 3659
 			$type_id = Categorie::TYPE_CUSTOMER;
3660 3660
 			$type_text = 'customer';
Please login to merge, or discard this patch.
Spacing   +721 added lines, -721 removed lines patch added patch discarded remove patch
@@ -40,11 +40,11 @@  discard block
 block discarded – undo
40 40
  */
41 41
 class Societe extends CommonObject
42 42
 {
43
-    public $element='societe';
43
+    public $element = 'societe';
44 44
     public $table_element = 'societe';
45
-	public $fk_element='fk_soc';
46
-    protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord');    // To test if we can delete object
47
-	protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
45
+	public $fk_element = 'fk_soc';
46
+    protected $childtables = array("supplier_proposal"=>'SupplierProposal', "propal"=>'Proposal', "commande"=>'Order', "facture"=>'Invoice', "facture_rec"=>'RecurringInvoiceTemplate', "contrat"=>'Contract', "fichinter"=>'Fichinter', "facture_fourn"=>'SupplierInvoice', "commande_fournisseur"=>'SupplierOrder', "projet"=>'Project', "expedition"=>'Shipment', "prelevement_lignes"=>'DirectDebitRecord'); // To test if we can delete object
47
+	protected $childtablesoncascade = array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
48 48
 
49 49
 
50 50
 	/**
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 	// Incoterms
363 363
 	var $fk_incoterms;
364 364
 	var $location_incoterms;
365
-	var $libelle_incoterms;  //Used into tooltip
365
+	var $libelle_incoterms; //Used into tooltip
366 366
 
367 367
 	// Multicurrency
368 368
 	var $fk_multicurrency;
@@ -386,9 +386,9 @@  discard block
 block discarded – undo
386 386
         $this->client = 0;
387 387
         $this->prospect = 0;
388 388
         $this->fournisseur = 0;
389
-        $this->typent_id  = 0;
390
-        $this->effectif_id  = 0;
391
-        $this->forme_juridique_code  = 0;
389
+        $this->typent_id = 0;
390
+        $this->effectif_id = 0;
391
+        $this->forme_juridique_code = 0;
392 392
         $this->tva_assuj = 1;
393 393
         $this->status = 1;
394 394
     }
@@ -403,17 +403,17 @@  discard block
 block discarded – undo
403 403
      */
404 404
     function create($user)
405 405
     {
406
-        global $langs,$conf,$mysoc;
406
+        global $langs, $conf, $mysoc;
407 407
 
408
-		$error=0;
408
+		$error = 0;
409 409
 
410 410
         // Clean parameters
411
-        if (empty($this->status)) $this->status=0;
412
-        $this->name=$this->name?trim($this->name):trim($this->nom);
413
-        if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
414
-        $this->nom=$this->name; // For backward compatibility
415
-        if (empty($this->client))      $this->client=0;
416
-        if (empty($this->fournisseur)) $this->fournisseur=0;
411
+        if (empty($this->status)) $this->status = 0;
412
+        $this->name = $this->name ?trim($this->name) : trim($this->nom);
413
+        if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name = ucwords($this->name);
414
+        $this->nom = $this->name; // For backward compatibility
415
+        if (empty($this->client))      $this->client = 0;
416
+        if (empty($this->fournisseur)) $this->fournisseur = 0;
417 417
         $this->import_key = trim($this->import_key);
418 418
 
419 419
 		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
@@ -425,13 +425,13 @@  discard block
 block discarded – undo
425 425
 
426 426
         dol_syslog(get_class($this)."::create ".$this->name);
427 427
 
428
-        $now=dol_now();
428
+        $now = dol_now();
429 429
 
430 430
         $this->db->begin();
431 431
 
432 432
         // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
433
-        if ($this->code_client == -1)      $this->get_codeclient($this,0);
434
-        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
433
+        if ($this->code_client == -1)      $this->get_codeclient($this, 0);
434
+        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this, 1);
435 435
 
436 436
         // Check more parameters (including mandatory setup
437 437
         // If error, this->errors[] is filled
@@ -440,26 +440,26 @@  discard block
 block discarded – undo
440 440
         if ($result >= 0)
441 441
         {
442 442
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
443
-            $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'";
444
-            $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
445
-            $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
446
-            $sql.= ", ".$this->status;
447
-            $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
448
-            $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
449
-            $sql.= ", 0";
450
-			$sql.= ", ".(int) $this->fk_incoterms;
451
-			$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
452
-            $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
453
-            $sql.= ", ".(int) $this->fk_multicurrency;
454
-            $sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
443
+            $sql .= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'";
444
+            $sql .= ", ".(!empty($user->id) ? "'".$user->id."'" : "null");
445
+            $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
446
+            $sql .= ", ".$this->status;
447
+            $sql .= ", ".(!empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'" : "null");
448
+            $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
449
+            $sql .= ", 0";
450
+			$sql .= ", ".(int) $this->fk_incoterms;
451
+			$sql .= ", '".$this->db->escape($this->location_incoterms)."'";
452
+            $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
453
+            $sql .= ", ".(int) $this->fk_multicurrency;
454
+            $sql .= ", '".$this->db->escape($this->multicurrency_code)."')";
455 455
 
456 456
             dol_syslog(get_class($this)."::create", LOG_DEBUG);
457
-            $result=$this->db->query($sql);
457
+            $result = $this->db->query($sql);
458 458
             if ($result)
459 459
             {
460 460
                 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
461 461
 
462
-                $ret = $this->update($this->id,$user,0,1,1,'add');
462
+                $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
463 463
 
464 464
                 // Ajout du commercial affecte
465 465
                 if ($this->commercial_id != '' && $this->commercial_id != -1)
@@ -475,13 +475,13 @@  discard block
 block discarded – undo
475 475
                 if ($ret >= 0)
476 476
                 {
477 477
                     // Call trigger
478
-                    $result=$this->call_trigger('COMPANY_CREATE',$user);
478
+                    $result = $this->call_trigger('COMPANY_CREATE', $user);
479 479
                     if ($result < 0) $error++;
480 480
                     // End call triggers
481 481
                 }
482 482
                 else $error++;
483 483
 
484
-                if (! $error)
484
+                if (!$error)
485 485
                 {
486 486
                     dol_syslog(get_class($this)."::Create success id=".$this->id);
487 487
                     $this->db->commit();
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
                 }
490 490
                 else
491 491
                 {
492
-                    dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
492
+                    dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',', $this->errors), LOG_ERR);
493 493
                     $this->db->rollback();
494 494
                     return -4;
495 495
                 }
@@ -498,13 +498,13 @@  discard block
 block discarded – undo
498 498
             {
499 499
                 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
500 500
                 {
501
-                    $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
502
-                    $result=-1;
501
+                    $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
502
+                    $result = -1;
503 503
                 }
504 504
                 else
505 505
                 {
506
-                    $this->error=$this->db->lasterror();
507
-                    $result=-2;
506
+                    $this->error = $this->db->lasterror();
507
+                    $result = -2;
508 508
                 }
509 509
                 $this->db->rollback();
510 510
                 return $result;
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
         else
515 515
         {
516 516
             $this->db->rollback();
517
-            dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
517
+            dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
518 518
             return -3;
519 519
         }
520 520
     }
@@ -529,12 +529,12 @@  discard block
 block discarded – undo
529 529
     function create_individual(User $user)
530 530
     {
531 531
         require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
532
-        $contact=new Contact($this->db);
532
+        $contact = new Contact($this->db);
533 533
 
534 534
         $contact->name              = $this->name_bis;
535 535
         $contact->firstname         = $this->firstname;
536 536
         $contact->civility_id       = $this->civility_id;
537
-        $contact->socid             = $this->id;	// fk_soc
537
+        $contact->socid             = $this->id; // fk_soc
538 538
         $contact->statut            = 1;
539 539
         $contact->priv              = 0;
540 540
         $contact->country_id        = $this->country_id;
@@ -550,7 +550,7 @@  discard block
 block discarded – undo
550 550
         {
551 551
             $this->error = $contact->error;
552 552
             $this->errors = $contact->errors;
553
-            dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
553
+            dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
554 554
         }
555 555
 
556 556
         return $result;
@@ -567,13 +567,13 @@  discard block
 block discarded – undo
567 567
     	global $conf, $langs, $mysoc;
568 568
 
569 569
     	$error = 0;
570
-        $this->errors=array();
570
+        $this->errors = array();
571 571
 
572 572
         $result = 0;
573
-        $this->name	= trim($this->name);
574
-        $this->nom=$this->name; // For backward compatibility
573
+        $this->name = trim($this->name);
574
+        $this->nom = $this->name; // For backward compatibility
575 575
 
576
-        if (! $this->name)
576
+        if (!$this->name)
577 577
         {
578 578
             $this->errors[] = 'ErrorBadThirdPartyName';
579 579
             $result = -2;
@@ -630,12 +630,12 @@  discard block
 block discarded – undo
630 630
         }
631 631
 
632 632
         // Check for duplicate or mandatory fields defined into setup
633
-        $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
634
-        foreach($array_to_check as $key)
633
+        $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL');
634
+        foreach ($array_to_check as $key)
635 635
         {
636
-        	$keymin=strtolower($key);
637
-        	$i=(int) preg_replace('/[^0-9]/','',$key);
638
-        	$vallabel=$this->$keymin;
636
+        	$keymin = strtolower($key);
637
+        	$i = (int) preg_replace('/[^0-9]/', '', $key);
638
+        	$vallabel = $this->$keymin;
639 639
 
640 640
         	if ($i > 0)
641 641
         	{
@@ -654,8 +654,8 @@  discard block
 block discarded – undo
654 654
         			// Check for mandatory prof id (but only if country is other than ours)
655 655
         			if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
656 656
         			{
657
-        				$idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
658
-        				if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
657
+        				$idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
658
+        				if (!$vallabel && !empty($conf->global->$idprof_mandatory))
659 659
         				{
660 660
         					$langs->load("errors");
661 661
         					$error++;
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
         			}
681 681
 
682 682
         			// Check for mandatory
683
-        			if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
683
+        			if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email))
684 684
         			{
685 685
         				$langs->load("errors");
686 686
         				$error++;
@@ -707,48 +707,48 @@  discard block
 block discarded – undo
707 707
      *		@param	int		$nosyncmember				Do not synchronize info of linked member
708 708
      *      @return int  			           			<0 if KO, >=0 if OK
709 709
      */
710
-    function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
710
+    function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
711 711
     {
712
-        global $langs,$conf,$hookmanager;
712
+        global $langs, $conf, $hookmanager;
713 713
         require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
714 714
 
715
-		$error=0;
715
+		$error = 0;
716 716
 
717 717
         dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
718 718
 
719
-        $now=dol_now();
719
+        $now = dol_now();
720 720
 
721 721
         // Clean parameters
722
-        $this->id			= $id;
723
-        $this->name			= $this->name?trim($this->name):trim($this->nom);
724
-        $this->nom			= $this->name;	// For backward compatibility
722
+        $this->id = $id;
723
+        $this->name = $this->name ?trim($this->name) : trim($this->nom);
724
+        $this->nom = $this->name; // For backward compatibility
725 725
 	    $this->name_alias = trim($this->name_alias);
726 726
         $this->ref_ext		= trim($this->ref_ext);
727
-        $this->address		= $this->address?trim($this->address):trim($this->address);
728
-        $this->zip			= $this->zip?trim($this->zip):trim($this->zip);
729
-        $this->town			= $this->town?trim($this->town):trim($this->town);
730
-        $this->state_id		= trim($this->state_id);
731
-        $this->country_id	= ($this->country_id > 0)?$this->country_id:0;
727
+        $this->address		= $this->address ?trim($this->address) : trim($this->address);
728
+        $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
729
+        $this->town			= $this->town ?trim($this->town) : trim($this->town);
730
+        $this->state_id = trim($this->state_id);
731
+        $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
732 732
         $this->phone		= trim($this->phone);
733
-        $this->phone		= preg_replace("/\s/","",$this->phone);
734
-        $this->phone		= preg_replace("/\./","",$this->phone);
733
+        $this->phone		= preg_replace("/\s/", "", $this->phone);
734
+        $this->phone		= preg_replace("/\./", "", $this->phone);
735 735
         $this->fax			= trim($this->fax);
736
-        $this->fax			= preg_replace("/\s/","",$this->fax);
737
-        $this->fax			= preg_replace("/\./","",$this->fax);
736
+        $this->fax			= preg_replace("/\s/", "", $this->fax);
737
+        $this->fax			= preg_replace("/\./", "", $this->fax);
738 738
         $this->email		= trim($this->email);
739 739
         $this->skype		= trim($this->skype);
740
-        $this->url			= $this->url?clean_url($this->url,0):'';
740
+        $this->url			= $this->url ?clean_url($this->url, 0) : '';
741 741
         $this->idprof1		= trim($this->idprof1);
742 742
         $this->idprof2		= trim($this->idprof2);
743 743
         $this->idprof3		= trim($this->idprof3);
744 744
         $this->idprof4		= trim($this->idprof4);
745
-        $this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
746
-        $this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
747
-        $this->prefix_comm	= trim($this->prefix_comm);
745
+        $this->idprof5		= (!empty($this->idprof5) ?trim($this->idprof5) : '');
746
+        $this->idprof6		= (!empty($this->idprof6) ?trim($this->idprof6) : '');
747
+        $this->prefix_comm = trim($this->prefix_comm);
748 748
         $this->outstanding_limit = price2num($this->outstanding_limit);
749 749
 
750 750
         $this->tva_assuj	= trim($this->tva_assuj);
751
-        $this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
751
+        $this->tva_intra	= dol_sanitizeFileName($this->tva_intra, '');
752 752
         if (empty($this->status)) $this->status = 0;
753 753
 
754 754
 		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
@@ -759,64 +759,64 @@  discard block
 block discarded – undo
759 759
 		}
760 760
 
761 761
         // Local taxes
762
-        $this->localtax1_assuj=trim($this->localtax1_assuj);
763
-        $this->localtax2_assuj=trim($this->localtax2_assuj);
762
+        $this->localtax1_assuj = trim($this->localtax1_assuj);
763
+        $this->localtax2_assuj = trim($this->localtax2_assuj);
764 764
 
765
-        $this->localtax1_value=trim($this->localtax1_value);
766
-        $this->localtax2_value=trim($this->localtax2_value);
765
+        $this->localtax1_value = trim($this->localtax1_value);
766
+        $this->localtax2_value = trim($this->localtax2_value);
767 767
 
768
-        if ($this->capital != '') $this->capital=price2num(trim($this->capital));
769
-        if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
768
+        if ($this->capital != '') $this->capital = price2num(trim($this->capital));
769
+        if (!is_numeric($this->capital)) $this->capital = ''; // '' = undef
770 770
 
771
-        $this->effectif_id=trim($this->effectif_id);
772
-        $this->forme_juridique_code=trim($this->forme_juridique_code);
771
+        $this->effectif_id = trim($this->effectif_id);
772
+        $this->forme_juridique_code = trim($this->forme_juridique_code);
773 773
 
774 774
         //Gencod
775
-        $this->barcode=trim($this->barcode);
775
+        $this->barcode = trim($this->barcode);
776 776
 
777 777
         // For automatic creation
778
-        if ($this->code_client == -1) $this->get_codeclient($this,0);
779
-        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
778
+        if ($this->code_client == -1) $this->get_codeclient($this, 0);
779
+        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this, 1);
780 780
 
781
-        $this->code_compta=trim($this->code_compta);
782
-        $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
781
+        $this->code_compta = trim($this->code_compta);
782
+        $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
783 783
 
784 784
         // Check parameters. More tests are done later in the ->verify()
785
-        if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
785
+        if (!is_numeric($this->client) && !is_numeric($this->fournisseur))
786 786
         {
787 787
             $langs->load("errors");
788 788
             $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
789 789
             return -1;
790 790
         }
791 791
 
792
-        $customer=false;
793
-        if (! empty($allowmodcodeclient) && ! empty($this->client))
792
+        $customer = false;
793
+        if (!empty($allowmodcodeclient) && !empty($this->client))
794 794
         {
795 795
         	// Attention get_codecompta peut modifier le code suivant le module utilise
796 796
         	if (empty($this->code_compta))
797 797
         	{
798
-        		$ret=$this->get_codecompta('customer');
798
+        		$ret = $this->get_codecompta('customer');
799 799
         		if ($ret < 0) return -1;
800 800
         	}
801 801
 
802
-        	$customer=true;
802
+        	$customer = true;
803 803
         }
804 804
 
805
-        $supplier=false;
806
-        if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
805
+        $supplier = false;
806
+        if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur))
807 807
         {
808 808
         	// Attention get_codecompta peut modifier le code suivant le module utilise
809 809
         	if (empty($this->code_compta_fournisseur))
810 810
         	{
811
-        		$ret=$this->get_codecompta('supplier');
811
+        		$ret = $this->get_codecompta('supplier');
812 812
         		if ($ret < 0) return -1;
813 813
         	}
814 814
 
815
-        	$supplier=true;
815
+        	$supplier = true;
816 816
         }
817 817
 
818 818
         //Web services
819
-        $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
819
+        $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
820 820
         $this->webservices_key = trim($this->webservices_key);
821 821
 
822 822
         //Incoterms
@@ -828,176 +828,176 @@  discard block
 block discarded – undo
828 828
         // Check name is required and codes are ok or unique.
829 829
         // If error, this->errors[] is filled
830 830
         $result = 0;
831
-        if ($action != 'add') $result = $this->verify();	// We don't check when update called during a create because verify was already done
831
+        if ($action != 'add') $result = $this->verify(); // We don't check when update called during a create because verify was already done
832 832
 
833 833
         if ($result >= 0)
834 834
         {
835 835
             dol_syslog(get_class($this)."::update verify ok or not done");
836 836
 
837 837
             $sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
838
-            $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
839
-            $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
840
-            $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
841
-            $sql .= ",address = '" . $this->db->escape($this->address) ."'";
842
-
843
-            $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
844
-            $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
845
-
846
-            $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
847
-            $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
848
-
849
-            $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
850
-            $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
851
-            $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
852
-            $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
853
-            $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
854
-
855
-            $sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
856
-            $sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
857
-            $sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
858
-            $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
859
-            $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
860
-            $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
861
-
862
-            $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
863
-            $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
864
-            $sql .= ",status = " .$this->status;
838
+            $sql .= "nom = '".$this->db->escape($this->name)."'"; // Required
839
+            $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
840
+            $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
841
+            $sql .= ",address = '".$this->db->escape($this->address)."'";
842
+
843
+            $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
844
+            $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
845
+
846
+            $sql .= ",fk_departement = '".(!empty($this->state_id) ? $this->state_id : '0')."'";
847
+            $sql .= ",fk_pays = '".(!empty($this->country_id) ? $this->country_id : '0')."'";
848
+
849
+            $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
850
+            $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
851
+            $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
852
+            $sql .= ",skype = ".(!empty($this->skype) ? "'".$this->db->escape($this->skype)."'" : "null");
853
+            $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
854
+
855
+            $sql .= ",siren   = '".$this->db->escape($this->idprof1)."'";
856
+            $sql .= ",siret   = '".$this->db->escape($this->idprof2)."'";
857
+            $sql .= ",ape     = '".$this->db->escape($this->idprof3)."'";
858
+            $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
859
+            $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
860
+            $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
861
+
862
+            $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
863
+            $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
864
+            $sql .= ",status = ".$this->status;
865 865
 
866 866
             // Local taxes
867
-            $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
868
-            $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
869
-            if($this->localtax1_assuj==1)
867
+            $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
868
+            $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
869
+            if ($this->localtax1_assuj == 1)
870 870
             {
871
-            	if($this->localtax1_value!='')
871
+            	if ($this->localtax1_value != '')
872 872
             	{
873
-            		$sql .=",localtax1_value =".$this->localtax1_value;
873
+            		$sql .= ",localtax1_value =".$this->localtax1_value;
874 874
             	}
875
-            	else $sql .=",localtax1_value =0.000";
875
+            	else $sql .= ",localtax1_value =0.000";
876 876
 
877 877
             }
878
-            else $sql .=",localtax1_value =0.000";
878
+            else $sql .= ",localtax1_value =0.000";
879 879
 
880
-            if($this->localtax2_assuj==1)
880
+            if ($this->localtax2_assuj == 1)
881 881
             {
882
-            	if($this->localtax2_value!='')
882
+            	if ($this->localtax2_value != '')
883 883
             	{
884
-            		$sql .=",localtax2_value =".$this->localtax2_value;
884
+            		$sql .= ",localtax2_value =".$this->localtax2_value;
885 885
             	}
886
-            	else $sql .=",localtax2_value =0.000";
886
+            	else $sql .= ",localtax2_value =0.000";
887 887
 
888 888
             }
889
-            else $sql .=",localtax2_value =0.000";
889
+            else $sql .= ",localtax2_value =0.000";
890 890
 
891 891
             $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
892 892
 
893
-            $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
893
+            $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
894 894
 
895
-            $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
895
+            $sql .= ",fk_effectif = ".(!empty($this->effectif_id) ? "'".$this->db->escape($this->effectif_id)."'" : "null");
896 896
             if (isset($this->stcomm_id))
897 897
             {
898 898
                 $sql .= ",fk_stcomm=".($this->stcomm_id > 0 ? $this->stcomm_id : "0");
899 899
             }
900
-            $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
901
-
902
-            $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
903
-
904
-            $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
905
-            $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
906
-            $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
907
-            $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
908
-            $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
909
-
910
-            $sql .= ",client = " . (! empty($this->client)?$this->client:0);
911
-            $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
912
-            $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
913
-            $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
914
-            $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
915
-            $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
900
+            $sql .= ",fk_typent = ".(!empty($this->typent_id) ? "'".$this->db->escape($this->typent_id)."'" : "0");
901
+
902
+            $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
903
+
904
+            $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
905
+            $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
906
+            $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
907
+            $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
908
+            $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
909
+
910
+            $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
911
+            $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
912
+            $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
913
+            $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
914
+            $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
915
+            $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
916 916
             $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
917 917
 
918
-            $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
919
-            $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
918
+            $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
919
+            $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
920 920
 
921 921
 			//Incoterms
922
-			$sql.= ", fk_incoterms = ".$this->fk_incoterms;
923
-			$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
922
+			$sql .= ", fk_incoterms = ".$this->fk_incoterms;
923
+			$sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
924 924
 
925 925
             if ($customer)
926 926
             {
927
-                $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
928
-                $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
927
+                $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
928
+                $sql .= ", code_compta = ".(!empty($this->code_compta) ? "'".$this->db->escape($this->code_compta)."'" : "null");
929 929
             }
930 930
 
931 931
             if ($supplier)
932 932
             {
933
-                $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
934
-                $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
933
+                $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
934
+                $sql .= ", code_compta_fournisseur = ".(!empty($this->code_compta_fournisseur) ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
935 935
             }
936
-            $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
936
+            $sql .= ", fk_user_modif = ".(!empty($user->id) ? "'".$user->id."'" : "null");
937 937
 			$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
938 938
 			$sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'";
939
-            $sql .= " WHERE rowid = '" . $id ."'";
939
+            $sql .= " WHERE rowid = '".$id."'";
940 940
 
941
-            $resql=$this->db->query($sql);
941
+            $resql = $this->db->query($sql);
942 942
             if ($resql)
943 943
             {
944
-            	unset($this->country_code);		// We clean this because it may have been changed after an update of country_id
944
+            	unset($this->country_code); // We clean this because it may have been changed after an update of country_id
945 945
             	unset($this->country);
946 946
             	unset($this->state_code);
947 947
             	unset($this->state);
948 948
 
949 949
             	$nbrowsaffected = $this->db->affected_rows($resql);
950 950
 
951
-            	if (! $error && $nbrowsaffected)
951
+            	if (!$error && $nbrowsaffected)
952 952
             	{
953 953
             		// Update information on linked member if it is an update
954
-	            	if (! $nosyncmember && ! empty($conf->adherent->enabled))
954
+	            	if (!$nosyncmember && !empty($conf->adherent->enabled))
955 955
 	            	{
956 956
 		            	require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
957 957
 
958 958
 		            	dol_syslog(get_class($this)."::update update linked member");
959 959
 
960
-		            	$lmember=new Adherent($this->db);
961
-		            	$result=$lmember->fetch(0, 0, $this->id);
960
+		            	$lmember = new Adherent($this->db);
961
+		            	$result = $lmember->fetch(0, 0, $this->id);
962 962
 
963 963
 		            	if ($result > 0)
964 964
 		            	{
965
-		            		$lmember->societe=$this->name;
965
+		            		$lmember->societe = $this->name;
966 966
 		            		//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
967 967
 		            		//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
968
-		            		$lmember->address=$this->address;
969
-		            		$lmember->email=$this->email;
970
-                    		$lmember->skype=$this->skype;
971
-		            		$lmember->phone=$this->phone;
968
+		            		$lmember->address = $this->address;
969
+		            		$lmember->email = $this->email;
970
+                    		$lmember->skype = $this->skype;
971
+		            		$lmember->phone = $this->phone;
972 972
 
973
-		            		$result=$lmember->update($user,0,1,1,1);	// Use nosync to 1 to avoid cyclic updates
973
+		            		$result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
974 974
 		            		if ($result < 0)
975 975
 		            		{
976
-		            			$this->error=$lmember->error;
977
-		            			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
976
+		            			$this->error = $lmember->error;
977
+		            			dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
978 978
 		            			$error++;
979 979
 		            		}
980 980
 		            	}
981 981
 		            	else if ($result < 0)
982 982
 		            	{
983
-		            		$this->error=$lmember->error;
983
+		            		$this->error = $lmember->error;
984 984
 		            		$error++;
985 985
 		            	}
986 986
 	            	}
987 987
             	}
988 988
 
989
-            	$action='update';
989
+            	$action = 'update';
990 990
 
991 991
                 // Actions on extra fields (by external module or standard code)
992 992
                 // TODO le hook fait double emploi avec le trigger !!
993 993
                 $hookmanager->initHooks(array('thirdpartydao'));
994
-                $parameters=array('socid'=>$this->id);
995
-                $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
994
+                $parameters = array('socid'=>$this->id);
995
+                $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
996 996
                 if (empty($reshook))
997 997
                 {
998 998
                 	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
999 999
                 	{
1000
-                		$result=$this->insertExtraFields();
1000
+                		$result = $this->insertExtraFields();
1001 1001
                 		if ($result < 0)
1002 1002
                 		{
1003 1003
                 			$error++;
@@ -1006,15 +1006,15 @@  discard block
 block discarded – undo
1006 1006
                 }
1007 1007
                 else if ($reshook < 0) $error++;
1008 1008
 
1009
-                if (! $error && $call_trigger)
1009
+                if (!$error && $call_trigger)
1010 1010
                 {
1011 1011
                     // Call trigger
1012
-                    $result=$this->call_trigger('COMPANY_MODIFY',$user);
1012
+                    $result = $this->call_trigger('COMPANY_MODIFY', $user);
1013 1013
                     if ($result < 0) $error++;
1014 1014
                     // End call triggers
1015 1015
                 }
1016 1016
 
1017
-                if (! $error)
1017
+                if (!$error)
1018 1018
                 {
1019 1019
                     dol_syslog(get_class($this)."::Update success");
1020 1020
                     $this->db->commit();
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
         else
1047 1047
        {
1048 1048
             $this->db->rollback();
1049
-            dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
1049
+            dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
1050 1050
             return -3;
1051 1051
         }
1052 1052
     }
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      *    @param    string	$email   		Email (Warning, this can return several records)
1068 1068
      *    @return   int						>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
1069 1069
      */
1070
-    function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='')
1070
+    function fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '')
1071 1071
     {
1072 1072
         global $langs;
1073 1073
         global $conf;
@@ -1119,13 +1119,13 @@  discard block
 block discarded – undo
1119 1119
         if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1120 1120
         if ($email)   $sql .= " AND email = '".$this->db->escape($email)."'";
1121 1121
 
1122
-        $resql=$this->db->query($sql);
1122
+        $resql = $this->db->query($sql);
1123 1123
         if ($resql)
1124 1124
         {
1125
-            $num=$this->db->num_rows($resql);
1125
+            $num = $this->db->num_rows($resql);
1126 1126
             if ($num > 1)
1127 1127
             {
1128
-                $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1128
+                $this->error = 'Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1129 1129
                 dol_syslog($this->error, LOG_ERR);
1130 1130
                 $result = -2;
1131 1131
             }
@@ -1135,11 +1135,11 @@  discard block
 block discarded – undo
1135 1135
 
1136 1136
                 $this->id           = $obj->rowid;
1137 1137
                 $this->entity       = $obj->entity;
1138
-                $this->canvas		= $obj->canvas;
1138
+                $this->canvas = $obj->canvas;
1139 1139
 
1140 1140
                 $this->ref          = $obj->rowid;
1141
-                $this->name 		= $obj->name;
1142
-                $this->nom          = $obj->name;		// deprecated
1141
+                $this->name = $obj->name;
1142
+                $this->nom          = $obj->name; // deprecated
1143 1143
 	            $this->name_alias = $obj->name_alias;
1144 1144
                 $this->ref_ext      = $obj->ref_ext;
1145 1145
                 $this->ref_int      = $obj->ref_int;
@@ -1149,22 +1149,22 @@  discard block
 block discarded – undo
1149 1149
                 $this->user_creation     = $obj->fk_user_creat;
1150 1150
                 $this->user_modification = $obj->fk_user_modif;
1151 1151
 
1152
-                $this->address 		= $obj->address;
1152
+                $this->address = $obj->address;
1153 1153
                 $this->zip 			= $obj->zip;
1154 1154
                 $this->town 		= $obj->town;
1155 1155
 
1156 1156
                 $this->country_id   = $obj->country_id;
1157
-                $this->country_code = $obj->country_id?$obj->country_code:'';
1158
-                $this->country 		= $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1157
+                $this->country_code = $obj->country_id ? $obj->country_code : '';
1158
+                $this->country = $obj->country_id ? ($langs->trans('Country'.$obj->country_code) != 'Country'.$obj->country_code ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
1159 1159
 
1160 1160
                 $this->state_id     = $obj->fk_departement;
1161 1161
                 $this->state_code   = $obj->state_code;
1162
-                $this->state        = ($obj->state!='-'?$obj->state:'');
1162
+                $this->state        = ($obj->state != '-' ? $obj->state : '');
1163 1163
 
1164
-                $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1165
-                $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1166
-                $this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
1167
-                $this->statut_commercial = $libelle;    // libelle statut commercial
1164
+                $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
1165
+                $libelle = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
1166
+                $this->stcomm_id = $obj->fk_stcomm; // id statut commercial
1167
+                $this->statut_commercial = $libelle; // libelle statut commercial
1168 1168
 
1169 1169
                 $this->email = $obj->email;
1170 1170
                 $this->skype = $obj->skype;
@@ -1172,7 +1172,7 @@  discard block
 block discarded – undo
1172 1172
                 $this->phone = $obj->phone;
1173 1173
                 $this->fax = $obj->fax;
1174 1174
 
1175
-                $this->parent    = $obj->parent;
1175
+                $this->parent = $obj->parent;
1176 1176
 
1177 1177
                 $this->idprof1		= $obj->idprof1;
1178 1178
                 $this->idprof2		= $obj->idprof2;
@@ -1181,7 +1181,7 @@  discard block
 block discarded – undo
1181 1181
                 $this->idprof5		= $obj->idprof5;
1182 1182
                 $this->idprof6		= $obj->idprof6;
1183 1183
 
1184
-                $this->capital   = $obj->capital;
1184
+                $this->capital = $obj->capital;
1185 1185
 
1186 1186
                 $this->code_client = $obj->code_client;
1187 1187
                 $this->code_fournisseur = $obj->code_fournisseur;
@@ -1206,22 +1206,22 @@  discard block
 block discarded – undo
1206 1206
                 $this->typent_code    = $obj->typent_code;
1207 1207
 
1208 1208
                 $this->effectif_id    = $obj->effectif_id;
1209
-                $this->effectif       = $obj->effectif_id?$obj->effectif:'';
1209
+                $this->effectif       = $obj->effectif_id ? $obj->effectif : '';
1210 1210
 
1211
-                $this->forme_juridique_code= $obj->forme_juridique_code;
1212
-                $this->forme_juridique     = $obj->forme_juridique_code?$obj->forme_juridique:'';
1211
+                $this->forme_juridique_code = $obj->forme_juridique_code;
1212
+                $this->forme_juridique     = $obj->forme_juridique_code ? $obj->forme_juridique : '';
1213 1213
 
1214 1214
                 $this->fk_prospectlevel = $obj->fk_prospectlevel;
1215 1215
 
1216 1216
                 $this->prefix_comm = $obj->prefix_comm;
1217 1217
 
1218
-                $this->remise_percent		= $obj->remise_client;
1218
+                $this->remise_percent = $obj->remise_client;
1219 1219
                 $this->mode_reglement_id 	= $obj->mode_reglement;
1220 1220
                 $this->cond_reglement_id 	= $obj->cond_reglement;
1221 1221
                 $this->mode_reglement_supplier_id 	= $obj->mode_reglement_supplier;
1222 1222
                 $this->cond_reglement_supplier_id 	= $obj->cond_reglement_supplier;
1223
-                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1224
-				$this->fk_account			= $obj->fk_account;
1223
+                $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1224
+				$this->fk_account = $obj->fk_account;
1225 1225
 
1226 1226
                 $this->client      = $obj->client;
1227 1227
                 $this->fournisseur = $obj->fournisseur;
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
                 $this->webservices_url = $obj->webservices_url;
1237 1237
                 $this->webservices_key = $obj->webservices_key;
1238 1238
 
1239
-                $this->outstanding_limit		= $obj->outstanding_limit;
1239
+                $this->outstanding_limit = $obj->outstanding_limit;
1240 1240
 
1241 1241
                 // multiprix
1242 1242
                 $this->price_level = $obj->price_level;
@@ -1266,12 +1266,12 @@  discard block
 block discarded – undo
1266 1266
         }
1267 1267
         else
1268 1268
 		{
1269
-            $this->error=$this->db->lasterror();
1269
+            $this->error = $this->db->lasterror();
1270 1270
             $result = -3;
1271 1271
         }
1272 1272
 
1273 1273
         // Use first price level if level not defined for third party
1274
-        if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1274
+        if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level = 1;
1275 1275
 
1276 1276
         return $result;
1277 1277
     }
@@ -1288,7 +1288,7 @@  discard block
 block discarded – undo
1288 1288
      * 	@param		string		$clause		Clause for filters
1289 1289
      * 	@return		array|int				<0 if KO, array of thirdparties object if OK
1290 1290
      */
1291
-    function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
1291
+    function searchByName($name, $type = '0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
1292 1292
     {
1293 1293
     	$thirdparties = array();
1294 1294
 
@@ -1297,23 +1297,23 @@  discard block
 block discarded – undo
1297 1297
     	// Check parameter
1298 1298
     	if (empty($name))
1299 1299
     	{
1300
-    		$this->errors[]='ErrorBadValueForParameter';
1300
+    		$this->errors[] = 'ErrorBadValueForParameter';
1301 1301
     		return -1;
1302 1302
     	}
1303 1303
 
1304 1304
     	// Generation requete recherche
1305 1305
     	$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
1306
-    	$sql.= " WHERE entity IN (".getEntity('category').")";
1307
-    	if (! empty($type))
1306
+    	$sql .= " WHERE entity IN (".getEntity('category').")";
1307
+    	if (!empty($type))
1308 1308
     	{
1309 1309
     		if ($type == 1 || $type == 2)
1310
-    			$sql.= " AND client = ".$type;
1310
+    			$sql .= " AND client = ".$type;
1311 1311
     		elseif ($type == 3)
1312
-    			$sql.= " AND fournisseur = 1";
1312
+    			$sql .= " AND fournisseur = 1";
1313 1313
     	}
1314
-    	if (! empty($name))
1314
+    	if (!empty($name))
1315 1315
     	{
1316
-    		if (! $exact)
1316
+    		if (!$exact)
1317 1317
     		{
1318 1318
     			if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
1319 1319
     			{
@@ -1324,28 +1324,28 @@  discard block
 block discarded – undo
1324 1324
     				$name = '%'.$name.'%';
1325 1325
     			}
1326 1326
     		}
1327
-    		$sql.= " AND ";
1328
-    		if (is_array($filters) && ! empty($filters))
1329
-    			$sql.= "(";
1327
+    		$sql .= " AND ";
1328
+    		if (is_array($filters) && !empty($filters))
1329
+    			$sql .= "(";
1330 1330
     		if ($similar)
1331 1331
     		{
1332 1332
     			// For test similitude (string inside name into database, or name into database inside string)
1333 1333
     			// Do not use this. Not compatible with other database.
1334
-    			$sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
1334
+    			$sql .= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
1335 1335
     		}
1336 1336
     		else
1337 1337
     		{
1338
-    			if (! $case)
1339
-    				$sql.= "nom LIKE '".$this->db->escape($name)."'";
1338
+    			if (!$case)
1339
+    				$sql .= "nom LIKE '".$this->db->escape($name)."'";
1340 1340
     			else
1341
-    				$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
1341
+    				$sql .= "nom LIKE BINARY '".$this->db->escape($name)."'";
1342 1342
     		}
1343 1343
     	}
1344
-    	if (is_array($filters) && ! empty($filters))
1344
+    	if (is_array($filters) && !empty($filters))
1345 1345
     	{
1346
-    		foreach($filters as $field => $value)
1346
+    		foreach ($filters as $field => $value)
1347 1347
     		{
1348
-    			if (! $exact)
1348
+    			if (!$exact)
1349 1349
     			{
1350 1350
     				if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
1351 1351
     				{
@@ -1356,16 +1356,16 @@  discard block
 block discarded – undo
1356 1356
     					$value = '%'.$value.'%';
1357 1357
     				}
1358 1358
     			}
1359
-    			if (! $case)
1360
-    				$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1359
+    			if (!$case)
1360
+    				$sql .= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1361 1361
     			else
1362
-    				$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1362
+    				$sql .= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1363 1363
     		}
1364
-    		if (! empty($name))
1365
-    			$sql.= ")";
1364
+    		if (!empty($name))
1365
+    			$sql .= ")";
1366 1366
     	}
1367 1367
 
1368
-    	$res  = $this->db->query($sql);
1368
+    	$res = $this->db->query($sql);
1369 1369
     	if ($res)
1370 1370
     	{
1371 1371
     		while ($rec = $this->db->fetch_array($res))
@@ -1379,7 +1379,7 @@  discard block
 block discarded – undo
1379 1379
     	}
1380 1380
     	else
1381 1381
     	{
1382
-    		$this->error=$this->db->lasterror();
1382
+    		$this->error = $this->db->lasterror();
1383 1383
     		return -1;
1384 1384
     	}
1385 1385
     }
@@ -1392,15 +1392,15 @@  discard block
 block discarded – undo
1392 1392
      *    @param    int		$call_trigger   0=No, 1=yes
1393 1393
      *    @return	int						<0 if KO, 0 if nothing done, >0 if OK
1394 1394
      */
1395
-    function delete($id, User $fuser=null, $call_trigger=1)
1395
+    function delete($id, User $fuser = null, $call_trigger = 1)
1396 1396
     {
1397 1397
         global $langs, $conf, $user;
1398 1398
 
1399
-        if (empty($fuser)) $fuser=$user;
1399
+        if (empty($fuser)) $fuser = $user;
1400 1400
 
1401 1401
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1402 1402
 
1403
-        $entity=isset($this->entity)?$this->entity:$conf->entity;
1403
+        $entity = isset($this->entity) ? $this->entity : $conf->entity;
1404 1404
 
1405 1405
         dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1406 1406
         $error = 0;
@@ -1412,15 +1412,15 @@  discard block
 block discarded – undo
1412 1412
             $this->db->begin();
1413 1413
 
1414 1414
             // User is mandatory for trigger call
1415
-            if (! $error && $call_trigger)
1415
+            if (!$error && $call_trigger)
1416 1416
             {
1417 1417
                 // Call trigger
1418
-                $result=$this->call_trigger('COMPANY_DELETE',$fuser);
1418
+                $result = $this->call_trigger('COMPANY_DELETE', $fuser);
1419 1419
                 if ($result < 0) $error++;
1420 1420
                 // End call triggers
1421 1421
             }
1422 1422
 
1423
-			if (! $error)
1423
+			if (!$error)
1424 1424
 			{
1425 1425
 	            require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1426 1426
 	            $static_cat = new Categorie($this->db);
@@ -1429,11 +1429,11 @@  discard block
 block discarded – undo
1429 1429
 	            // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1430 1430
 	            if ($this->client || $this->prospect)
1431 1431
 	            {
1432
-	                $toute_categs['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
1432
+	                $toute_categs['societe'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
1433 1433
 	            }
1434 1434
 	            if ($this->fournisseur)
1435 1435
 	            {
1436
-	                $toute_categs['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
1436
+	                $toute_categs['fournisseur'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
1437 1437
 	            }
1438 1438
 
1439 1439
 	            // Remove each "Categorie"
@@ -1448,11 +1448,11 @@  discard block
 block discarded – undo
1448 1448
 
1449 1449
 			foreach ($this->childtablesoncascade as $tabletodelete)
1450 1450
 			{
1451
-				if (! $error)
1451
+				if (!$error)
1452 1452
 				{
1453 1453
 					$sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1454
-					$sql.= " WHERE fk_soc = " . $id;
1455
-					if (! $this->db->query($sql))
1454
+					$sql .= " WHERE fk_soc = ".$id;
1455
+					if (!$this->db->query($sql))
1456 1456
 					{
1457 1457
 						$error++;
1458 1458
 						$this->errors[] = $this->db->lasterror();
@@ -1461,9 +1461,9 @@  discard block
 block discarded – undo
1461 1461
 			}
1462 1462
 
1463 1463
             // Removed extrafields
1464
-            if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1464
+            if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1465 1465
             {
1466
-            	$result=$this->deleteExtraFields();
1466
+            	$result = $this->deleteExtraFields();
1467 1467
             	if ($result < 0)
1468 1468
             	{
1469 1469
             		$error++;
@@ -1472,25 +1472,25 @@  discard block
 block discarded – undo
1472 1472
             }
1473 1473
 
1474 1474
             // Remove third party
1475
-            if (! $error)
1475
+            if (!$error)
1476 1476
             {
1477 1477
                 $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1478
-                $sql.= " WHERE rowid = " . $id;
1479
-                if (! $this->db->query($sql))
1478
+                $sql .= " WHERE rowid = ".$id;
1479
+                if (!$this->db->query($sql))
1480 1480
                 {
1481 1481
                     $error++;
1482 1482
                     $this->errors[] = $this->db->lasterror();
1483 1483
                 }
1484 1484
             }
1485 1485
 
1486
-            if (! $error)
1486
+            if (!$error)
1487 1487
             {
1488 1488
                 $this->db->commit();
1489 1489
 
1490 1490
                 // Delete directory
1491
-                if (! empty($conf->societe->multidir_output[$entity]))
1491
+                if (!empty($conf->societe->multidir_output[$entity]))
1492 1492
                 {
1493
-                	$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1493
+                	$docdir = $conf->societe->multidir_output[$entity]."/".$id;
1494 1494
                 	if (dol_is_dir($docdir))
1495 1495
                 	{
1496 1496
                     	dol_delete_dir_recursive($docdir);
@@ -1519,13 +1519,13 @@  discard block
 block discarded – undo
1519 1519
     {
1520 1520
         if ($this->id)
1521 1521
         {
1522
-            $newclient=1;
1523
-            if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1522
+            $newclient = 1;
1523
+            if ($this->client == 2 || $this->client == 3) $newclient = 3; //If prospect, we keep prospect tag
1524 1524
             $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1525
-            $sql.= " SET client = ".$newclient;
1526
-            $sql.= " WHERE rowid = " . $this->id;
1525
+            $sql .= " SET client = ".$newclient;
1526
+            $sql .= " WHERE rowid = ".$this->id;
1527 1527
 
1528
-            $resql=$this->db->query($sql);
1528
+            $resql = $this->db->query($sql);
1529 1529
             if ($resql)
1530 1530
             {
1531 1531
                 $this->client = $newclient;
@@ -1549,10 +1549,10 @@  discard block
 block discarded – undo
1549 1549
         global $conf, $langs;
1550 1550
 
1551 1551
         // Nettoyage parametres
1552
-        $note=trim($note);
1553
-        if (! $note)
1552
+        $note = trim($note);
1553
+        if (!$note)
1554 1554
         {
1555
-            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1555
+            $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("NoteReason"));
1556 1556
             return -2;
1557 1557
         }
1558 1558
 
@@ -1562,33 +1562,33 @@  discard block
 block discarded – undo
1562 1562
         {
1563 1563
             $this->db->begin();
1564 1564
 
1565
-            $now=dol_now();
1565
+            $now = dol_now();
1566 1566
 
1567 1567
             // Positionne remise courante
1568 1568
             $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1569
-            $sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1570
-            $sql.= " WHERE rowid = " . $this->id;
1571
-            $resql=$this->db->query($sql);
1572
-            if (! $resql)
1569
+            $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
1570
+            $sql .= " WHERE rowid = ".$this->id;
1571
+            $resql = $this->db->query($sql);
1572
+            if (!$resql)
1573 1573
             {
1574 1574
                 $this->db->rollback();
1575
-                $this->error=$this->db->error();
1575
+                $this->error = $this->db->error();
1576 1576
                 return -1;
1577 1577
             }
1578 1578
 
1579 1579
             // Ecrit trace dans historique des remises
1580 1580
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1581
-            $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1582
-            $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1583
-            $sql.= " '".$this->db->escape($note)."',";
1584
-            $sql.= " ".$user->id;
1585
-            $sql.= ")";
1586
-
1587
-            $resql=$this->db->query($sql);
1588
-            if (! $resql)
1581
+            $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1582
+            $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1583
+            $sql .= " '".$this->db->escape($note)."',";
1584
+            $sql .= " ".$user->id;
1585
+            $sql .= ")";
1586
+
1587
+            $resql = $this->db->query($sql);
1588
+            if (!$resql)
1589 1589
             {
1590 1590
                 $this->db->rollback();
1591
-                $this->error=$this->db->lasterror();
1591
+                $this->error = $this->db->lasterror();
1592 1592
                 return -1;
1593 1593
             }
1594 1594
 
@@ -1606,7 +1606,7 @@  discard block
 block discarded – undo
1606 1606
      *      @param  float	$tva_tx     VAT rate
1607 1607
      *		@return	int					<0 if KO, id of discount record if OK
1608 1608
      */
1609
-    function set_remise_except($remise, User $user, $desc, $tva_tx=0)
1609
+    function set_remise_except($remise, User $user, $desc, $tva_tx = 0)
1610 1610
     {
1611 1611
         global $langs;
1612 1612
 
@@ -1615,14 +1615,14 @@  discard block
 block discarded – undo
1615 1615
         $desc = trim($desc);
1616 1616
 
1617 1617
         // Check parameters
1618
-        if (! $remise > 0)
1618
+        if (!$remise > 0)
1619 1619
         {
1620
-            $this->error=$langs->trans("ErrorWrongValueForParameter","1");
1620
+            $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
1621 1621
             return -1;
1622 1622
         }
1623
-        if (! $desc)
1623
+        if (!$desc)
1624 1624
         {
1625
-            $this->error=$langs->trans("ErrorWrongValueForParameter","3");
1625
+            $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
1626 1626
             return -2;
1627 1627
         }
1628 1628
 
@@ -1631,20 +1631,20 @@  discard block
 block discarded – undo
1631 1631
             require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1632 1632
 
1633 1633
             $discount = new DiscountAbsolute($this->db);
1634
-            $discount->fk_soc=$this->id;
1635
-            $discount->amount_ht=price2num($remise,'MT');
1636
-            $discount->amount_tva=price2num($remise*$tva_tx/100,'MT');
1637
-            $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
1638
-            $discount->tva_tx=price2num($tva_tx,'MT');
1639
-            $discount->description=$desc;
1640
-            $result=$discount->create($user);
1634
+            $discount->fk_soc = $this->id;
1635
+            $discount->amount_ht = price2num($remise, 'MT');
1636
+            $discount->amount_tva = price2num($remise * $tva_tx / 100, 'MT');
1637
+            $discount->amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
1638
+            $discount->tva_tx = price2num($tva_tx, 'MT');
1639
+            $discount->description = $desc;
1640
+            $result = $discount->create($user);
1641 1641
             if ($result > 0)
1642 1642
             {
1643 1643
                 return $result;
1644 1644
             }
1645 1645
             else
1646 1646
             {
1647
-                $this->error=$discount->error;
1647
+                $this->error = $discount->error;
1648 1648
                 return -3;
1649 1649
             }
1650 1650
         }
@@ -1659,19 +1659,19 @@  discard block
 block discarded – undo
1659 1659
      * 	@param	integer	$maxvalue	Filter on max value for discount
1660 1660
      *	@return	int					<0 if KO, Credit note amount otherwise
1661 1661
      */
1662
-    function getAvailableDiscounts($user='',$filter='',$maxvalue=0)
1662
+    function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0)
1663 1663
     {
1664 1664
         require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1665 1665
 
1666
-        $discountstatic=new DiscountAbsolute($this->db);
1667
-        $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue);
1666
+        $discountstatic = new DiscountAbsolute($this->db);
1667
+        $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue);
1668 1668
         if ($result >= 0)
1669 1669
         {
1670 1670
             return $result;
1671 1671
         }
1672 1672
         else
1673 1673
         {
1674
-            $this->error=$discountstatic->error;
1674
+            $this->error = $discountstatic->error;
1675 1675
             return -1;
1676 1676
         }
1677 1677
     }
@@ -1686,38 +1686,38 @@  discard block
 block discarded – undo
1686 1686
     {
1687 1687
         global $conf;
1688 1688
 
1689
-        $reparray=array();
1689
+        $reparray = array();
1690 1690
 
1691 1691
         $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1692
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1693
-        if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1692
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1693
+        if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1694 1694
         {
1695
-        	$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1696
-        	$sql.= " WHERE ((ug.fk_user = sc.fk_user";
1697
-        	$sql.= " AND ug.entity = ".$conf->entity.")";
1698
-        	$sql.= " OR u.admin = 1)";
1695
+        	$sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1696
+        	$sql .= " WHERE ((ug.fk_user = sc.fk_user";
1697
+        	$sql .= " AND ug.entity = ".$conf->entity.")";
1698
+        	$sql .= " OR u.admin = 1)";
1699 1699
         }
1700 1700
         else
1701
-        	$sql.= " WHERE entity in (0, ".$conf->entity.")";
1701
+        	$sql .= " WHERE entity in (0, ".$conf->entity.")";
1702 1702
 
1703
-        $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1703
+        $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1704 1704
 
1705 1705
         $resql = $this->db->query($sql);
1706 1706
         if ($resql)
1707 1707
         {
1708 1708
             $num = $this->db->num_rows($resql);
1709
-            $i=0;
1709
+            $i = 0;
1710 1710
             while ($i < $num)
1711 1711
             {
1712 1712
                 $obj = $this->db->fetch_object($resql);
1713
-                $reparray[$i]['id']=$obj->rowid;
1714
-                $reparray[$i]['lastname']=$obj->lastname;
1715
-                $reparray[$i]['firstname']=$obj->firstname;
1716
-                $reparray[$i]['email']=$obj->email;
1717
-                $reparray[$i]['statut']=$obj->statut;
1718
-                $reparray[$i]['entity']=$obj->entity;
1719
-                $reparray[$i]['login']=$obj->login;
1720
-                $reparray[$i]['photo']=$obj->photo;
1713
+                $reparray[$i]['id'] = $obj->rowid;
1714
+                $reparray[$i]['lastname'] = $obj->lastname;
1715
+                $reparray[$i]['firstname'] = $obj->firstname;
1716
+                $reparray[$i]['email'] = $obj->email;
1717
+                $reparray[$i]['statut'] = $obj->statut;
1718
+                $reparray[$i]['entity'] = $obj->entity;
1719
+                $reparray[$i]['login'] = $obj->login;
1720
+                $reparray[$i]['photo'] = $obj->photo;
1721 1721
                 $i++;
1722 1722
             }
1723 1723
             return $reparray;
@@ -1739,13 +1739,13 @@  discard block
 block discarded – undo
1739 1739
     {
1740 1740
         if ($this->id)
1741 1741
         {
1742
-        	$now=dol_now();
1742
+        	$now = dol_now();
1743 1743
 
1744 1744
             $sql  = "UPDATE ".MAIN_DB_PREFIX."societe";
1745 1745
             $sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1746
-            $sql .= " WHERE rowid = " . $this->id;
1746
+            $sql .= " WHERE rowid = ".$this->id;
1747 1747
 
1748
-            if (! $this->db->query($sql))
1748
+            if (!$this->db->query($sql))
1749 1749
             {
1750 1750
                 dol_print_error($this->db);
1751 1751
                 return -1;
@@ -1755,7 +1755,7 @@  discard block
 block discarded – undo
1755 1755
             $sql .= " (datec, fk_soc, price_level, fk_user_author)";
1756 1756
             $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1757 1757
 
1758
-            if (! $this->db->query($sql))
1758
+            if (!$this->db->query($sql))
1759 1759
             {
1760 1760
                 dol_print_error($this->db);
1761 1761
                 return -1;
@@ -1777,15 +1777,15 @@  discard block
 block discarded – undo
1777 1777
         if ($this->id > 0 && $commid > 0)
1778 1778
         {
1779 1779
             $sql = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux";
1780
-            $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1780
+            $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1781 1781
 
1782 1782
             $this->db->query($sql);
1783 1783
 
1784 1784
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1785
-            $sql.= " ( fk_soc, fk_user )";
1786
-            $sql.= " VALUES (".$this->id.",".$commid.")";
1785
+            $sql .= " ( fk_soc, fk_user )";
1786
+            $sql .= " VALUES (".$this->id.",".$commid.")";
1787 1787
 
1788
-            if (! $this->db->query($sql) )
1788
+            if (!$this->db->query($sql))
1789 1789
             {
1790 1790
                 dol_syslog(get_class($this)."::add_commercial Erreur");
1791 1791
             }
@@ -1806,7 +1806,7 @@  discard block
 block discarded – undo
1806 1806
             $sql  = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux ";
1807 1807
             $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1808 1808
 
1809
-            if (! $this->db->query($sql) )
1809
+            if (!$this->db->query($sql))
1810 1810
             {
1811 1811
                 dol_syslog(get_class($this)."::del_commercial Erreur");
1812 1812
             }
@@ -1824,156 +1824,156 @@  discard block
 block discarded – undo
1824 1824
      *      @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1825 1825
      *		@return	string					          String with URL
1826 1826
      */
1827
-    function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
1827
+    function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1)
1828 1828
     {
1829 1829
         global $conf, $langs, $hookmanager;
1830 1830
 
1831
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1831
+        if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
1832 1832
 
1833
-        $name=$this->name?$this->name:$this->nom;
1833
+        $name = $this->name ? $this->name : $this->nom;
1834 1834
 
1835
-    	if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
1835
+    	if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
1836 1836
     	{
1837
-    		if (($this->client) && (! empty ( $this->code_client ))
1837
+    		if (($this->client) && (!empty ($this->code_client))
1838 1838
     			&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1839 1839
     			|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
1840 1840
     			)
1841 1841
     		)
1842
-    		$code = $this->code_client . ' - ';
1842
+    		$code = $this->code_client.' - ';
1843 1843
 
1844
-    		if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
1844
+    		if (($this->fournisseur) && (!empty ($this->code_fournisseur))
1845 1845
     			&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1846 1846
     			|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
1847 1847
     			)
1848 1848
     		)
1849
-    		$code .= $this->code_fournisseur . ' - ';
1849
+    		$code .= $this->code_fournisseur.' - ';
1850 1850
 
1851 1851
     		if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
1852
-    			$name =$code.' '.$name;
1852
+    			$name = $code.' '.$name;
1853 1853
     		else
1854
-    			$name =$code;
1854
+    			$name = $code;
1855 1855
     	}
1856 1856
 
1857 1857
     	if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
1858 1858
 
1859
-        $result=''; $label='';
1860
-        $linkstart=''; $linkend='';
1859
+        $result = ''; $label = '';
1860
+        $linkstart = ''; $linkend = '';
1861 1861
 
1862
-        if (! empty($this->logo) && class_exists('Form'))
1862
+        if (!empty($this->logo) && class_exists('Form'))
1863 1863
         {
1864
-            $label.= '<div class="photointooltip">';
1865
-            $label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini');
1866
-            $label.= '</div><div style="clear: both;"></div>';
1864
+            $label .= '<div class="photointooltip">';
1865
+            $label .= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini');
1866
+            $label .= '</div><div style="clear: both;"></div>';
1867 1867
         }
1868 1868
 
1869
-        $label.= '<div class="centpercent">';
1869
+        $label .= '<div class="centpercent">';
1870 1870
 
1871 1871
         if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
1872 1872
         {
1873
-           $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
1873
+           $label .= '<u>'.$langs->trans("ShowCustomer").'</u>';
1874 1874
            $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1875 1875
         }
1876 1876
         else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1877 1877
         {
1878
-            $label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
1878
+            $label .= '<u>'.$langs->trans("ShowProspect").'</u>';
1879 1879
             $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1880 1880
         }
1881 1881
         else if ($option == 'supplier')
1882 1882
         {
1883
-            $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
1883
+            $label .= '<u>'.$langs->trans("ShowSupplier").'</u>';
1884 1884
             $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
1885 1885
         }
1886 1886
         else if ($option == 'agenda')
1887 1887
         {
1888
-            $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
1888
+            $label .= '<u>'.$langs->trans("ShowAgenda").'</u>';
1889 1889
             $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
1890 1890
         }
1891 1891
         else if ($option == 'project')
1892 1892
         {
1893
-            $label.= '<u>' . $langs->trans("ShowProject") . '</u>';
1893
+            $label .= '<u>'.$langs->trans("ShowProject").'</u>';
1894 1894
             $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
1895 1895
         }
1896 1896
         else if ($option == 'margin')
1897 1897
         {
1898
-            $label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
1898
+            $label .= '<u>'.$langs->trans("ShowMargin").'</u>';
1899 1899
             $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
1900 1900
         }
1901 1901
         else if ($option == 'contact')
1902 1902
         {
1903
-        	$label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
1903
+        	$label .= '<u>'.$langs->trans("ShowContacts").'</u>';
1904 1904
         	$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
1905 1905
         }
1906 1906
 
1907 1907
         // By default
1908 1908
         if (empty($linkstart))
1909 1909
         {
1910
-            $label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
1910
+            $label .= '<u>'.$langs->trans("ShowCompany").'</u>';
1911 1911
             $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
1912 1912
         }
1913 1913
 
1914
-        if (! empty($this->name))
1914
+        if (!empty($this->name))
1915 1915
         {
1916
-            $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
1917
-            if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
1918
-            $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
1916
+            $label .= '<br><b>'.$langs->trans('Name').':</b> '.$this->name;
1917
+            if (!empty($this->name_alias)) $label .= ' ('.$this->name_alias.')';
1918
+            $label .= '<br><b>'.$langs->trans('Email').':</b> '.$this->email;
1919 1919
         }
1920
-        if (! empty($this->country_code))
1921
-            $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
1922
-        if (! empty($this->tva_intra))
1923
-            $label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra;
1924
-            if (! empty($this->code_client) && $this->client)
1925
-            $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
1926
-        if (! empty($this->code_fournisseur) && $this->fournisseur)
1927
-            $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
1928
-        if (! empty($conf->accounting->enabled) && $this->client)
1929
-            $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
1930
-        if (! empty($conf->accounting->enabled) && $this->fournisseur)
1931
-            $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
1920
+        if (!empty($this->country_code))
1921
+            $label .= '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
1922
+        if (!empty($this->tva_intra))
1923
+            $label .= '<br><b>'.$langs->trans('VATNumber').':</b> '.$this->tva_intra;
1924
+            if (!empty($this->code_client) && $this->client)
1925
+            $label .= '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
1926
+        if (!empty($this->code_fournisseur) && $this->fournisseur)
1927
+            $label .= '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
1928
+        if (!empty($conf->accounting->enabled) && $this->client)
1929
+            $label .= '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.$this->code_compta_client;
1930
+        if (!empty($conf->accounting->enabled) && $this->fournisseur)
1931
+            $label .= '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
1932 1932
 
1933
-        $label.= '</div>';
1933
+        $label .= '</div>';
1934 1934
 
1935 1935
         // Add type of canvas
1936
-        $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
1936
+        $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
1937 1937
         // Add param to save lastsearch_values or not
1938
-        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1939
-        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1940
-        if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
1941
-        $linkstart.='"';
1938
+        $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1939
+        if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1940
+        if ($add_save_lastsearch_values) $linkstart .= '&save_lastsearch_values=1';
1941
+        $linkstart .= '"';
1942 1942
 
1943
-        $linkclose='';
1943
+        $linkclose = '';
1944 1944
         if (empty($notooltip))
1945 1945
         {
1946
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1946
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1947 1947
             {
1948
-                $label=$langs->trans("ShowCompany");
1949
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1948
+                $label = $langs->trans("ShowCompany");
1949
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1950 1950
             }
1951
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1952
-            $linkclose.=' class="classfortooltip"';
1951
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1952
+            $linkclose .= ' class="classfortooltip"';
1953 1953
 
1954
-         	if (! is_object($hookmanager))
1954
+         	if (!is_object($hookmanager))
1955 1955
     		{
1956 1956
     			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1957
-    			$hookmanager=new HookManager($this->db);
1957
+    			$hookmanager = new HookManager($this->db);
1958 1958
     		}
1959 1959
     		$hookmanager->initHooks(array('societedao'));
1960
-    		$parameters=array('id'=>$this->id);
1961
-    		$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1960
+    		$parameters = array('id'=>$this->id);
1961
+    		$reshook = $hookmanager->executeHooks('getnomurltooltip', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1962 1962
     		if ($reshook > 0) $linkclose = $hookmanager->resPrint;
1963 1963
         }
1964
-        $linkstart.=$linkclose.'>';
1965
-        $linkend='</a>';
1964
+        $linkstart .= $linkclose.'>';
1965
+        $linkend = '</a>';
1966 1966
 
1967 1967
         global $user;
1968
-        if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
1968
+        if (!$user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
1969 1969
         {
1970
-            $linkstart='';
1971
-            $linkend='';
1970
+            $linkstart = '';
1971
+            $linkend = '';
1972 1972
         }
1973 1973
 
1974
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend);
1975
-        if ($withpicto && $withpicto != 2) $result.=' ';
1976
-        if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
1974
+        if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), 'company', ($notooltip ? '' : 'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip ? 0 : 1).$linkend);
1975
+        if ($withpicto && $withpicto != 2) $result .= ' ';
1976
+        if ($withpicto != 2) $result .= $linkstart.($maxlen ?dol_trunc($name, $maxlen) : $name).$linkend;
1977 1977
 
1978 1978
         return $result;
1979 1979
     }
@@ -1984,9 +1984,9 @@  discard block
 block discarded – undo
1984 1984
      *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
1985 1985
      *    @return   string        		Libelle
1986 1986
      */
1987
-    function getLibStatut($mode=0)
1987
+    function getLibStatut($mode = 0)
1988 1988
     {
1989
-        return $this->LibStatut($this->status,$mode);
1989
+        return $this->LibStatut($this->status, $mode);
1990 1990
     }
1991 1991
 
1992 1992
     /**
@@ -1996,40 +1996,40 @@  discard block
 block discarded – undo
1996 1996
      *  @param	int		$mode           0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1997 1997
      *  @return	string          		Libelle du statut
1998 1998
      */
1999
-    function LibStatut($statut,$mode=0)
1999
+    function LibStatut($statut, $mode = 0)
2000 2000
     {
2001 2001
         global $langs;
2002 2002
         $langs->load('companies');
2003 2003
 
2004 2004
         if ($mode == 0)
2005 2005
         {
2006
-            if ($statut==0) return $langs->trans("ActivityCeased");
2007
-            if ($statut==1) return $langs->trans("InActivity");
2006
+            if ($statut == 0) return $langs->trans("ActivityCeased");
2007
+            if ($statut == 1) return $langs->trans("InActivity");
2008 2008
         }
2009 2009
         if ($mode == 1)
2010 2010
         {
2011
-            if ($statut==0) return $langs->trans("ActivityCeased");
2012
-            if ($statut==1) return $langs->trans("InActivity");
2011
+            if ($statut == 0) return $langs->trans("ActivityCeased");
2012
+            if ($statut == 1) return $langs->trans("InActivity");
2013 2013
         }
2014 2014
         if ($mode == 2)
2015 2015
         {
2016
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2017
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2016
+            if ($statut == 0) return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2017
+            if ($statut == 1) return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2018 2018
         }
2019 2019
         if ($mode == 3)
2020 2020
         {
2021
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2022
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2021
+            if ($statut == 0) return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
2022
+            if ($statut == 1) return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
2023 2023
         }
2024 2024
         if ($mode == 4)
2025 2025
         {
2026
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2027
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2026
+            if ($statut == 0) return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2027
+            if ($statut == 1) return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2028 2028
         }
2029 2029
         if ($mode == 5)
2030 2030
         {
2031
-            if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2032
-            if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2031
+            if ($statut == 0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
2032
+            if ($statut == 1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
2033 2033
         }
2034 2034
     }
2035 2035
 
@@ -2039,15 +2039,15 @@  discard block
 block discarded – undo
2039 2039
      *	  @param	  int		$addthirdparty		1=Add also a record for thirdparty email
2040 2040
      *    @return     array       					Array of contacts emails
2041 2041
      */
2042
-    function thirdparty_and_contact_email_array($addthirdparty=0)
2042
+    function thirdparty_and_contact_email_array($addthirdparty = 0)
2043 2043
     {
2044 2044
         global $langs;
2045 2045
 
2046
-        $contact_emails = $this->contact_property_array('email',1);
2046
+        $contact_emails = $this->contact_property_array('email', 1);
2047 2047
         if ($this->email && $addthirdparty)
2048 2048
         {
2049
-            if (empty($this->name)) $this->name=$this->nom;
2050
-            $contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->email."&gt;";
2049
+            if (empty($this->name)) $this->name = $this->nom;
2050
+            $contact_emails['thirdparty'] = $langs->trans("ThirdParty").': '.dol_trunc($this->name, 16)." &lt;".$this->email."&gt;";
2051 2051
         }
2052 2052
         //var_dump($contact_emails)
2053 2053
         return $contact_emails;
@@ -2064,11 +2064,11 @@  discard block
 block discarded – undo
2064 2064
 
2065 2065
         $contact_phone = $this->contact_property_array('mobile');
2066 2066
 
2067
-        if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2067
+        if (!empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2068 2068
         {
2069
-            if (empty($this->name)) $this->name=$this->nom;
2069
+            if (empty($this->name)) $this->name = $this->nom;
2070 2070
             // TODO: Tester si tel non deja present dans tableau contact
2071
-            $contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->phone."&gt;";
2071
+            $contact_phone['thirdparty'] = $langs->trans("ThirdParty").': '.dol_trunc($this->name, 16)." &lt;".$this->phone."&gt;";
2072 2072
         }
2073 2073
         return $contact_phone;
2074 2074
     }
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
 	 * 	@param	int		$hidedisabled		1=Hide contact if disabled
2081 2081
      *  @return array       				Array of contacts emails or mobile array(id=>'Name <email>')
2082 2082
      */
2083
-    function contact_property_array($mode='email', $hidedisabled=0)
2083
+    function contact_property_array($mode = 'email', $hidedisabled = 0)
2084 2084
     {
2085 2085
     	global $langs;
2086 2086
 
@@ -2088,44 +2088,44 @@  discard block
 block discarded – undo
2088 2088
 
2089 2089
 
2090 2090
         $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2091
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2092
-        $sql.= " WHERE fk_soc = ".$this->id;
2091
+        $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2092
+        $sql .= " WHERE fk_soc = ".$this->id;
2093 2093
 
2094
-        $resql=$this->db->query($sql);
2094
+        $resql = $this->db->query($sql);
2095 2095
         if ($resql)
2096 2096
         {
2097 2097
             $nump = $this->db->num_rows($resql);
2098 2098
             if ($nump)
2099 2099
             {
2100
-            	$sepa="("; $sepb=")";
2100
+            	$sepa = "("; $sepb = ")";
2101 2101
             	if ($mode == 'email')
2102 2102
             	{
2103
-            		$sepa="&lt;"; $sepb="&gt;";
2103
+            		$sepa = "&lt;"; $sepb = "&gt;";
2104 2104
             	}
2105 2105
                 $i = 0;
2106 2106
                 while ($i < $nump)
2107 2107
                 {
2108 2108
                     $obj = $this->db->fetch_object($resql);
2109
-                    if ($mode == 'email') $property=$obj->email;
2110
-                    else if ($mode == 'mobile') $property=$obj->phone_mobile;
2111
-                    else $property=$obj->$mode;
2109
+                    if ($mode == 'email') $property = $obj->email;
2110
+                    else if ($mode == 'mobile') $property = $obj->phone_mobile;
2111
+                    else $property = $obj->$mode;
2112 2112
 
2113 2113
 					// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2114 2114
                     if ($obj->statut == 1 || empty($hidedisabled))
2115 2115
                     {
2116 2116
                     	if (empty($property))
2117 2117
                     	{
2118
-                    		if ($mode == 'email') $property=$langs->trans("NoEMail");
2119
-                    		else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone");
2118
+                    		if ($mode == 'email') $property = $langs->trans("NoEMail");
2119
+                    		else if ($mode == 'mobile') $property = $langs->trans("NoMobilePhone");
2120 2120
                     	}
2121 2121
 
2122 2122
 	                    if (!empty($obj->poste))
2123 2123
     	                {
2124
-							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2124
+							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2125 2125
 						}
2126 2126
 						else
2127 2127
 						{
2128
-							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2128
+							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
2129 2129
 						}
2130 2130
                     }
2131 2131
                     $i++;
@@ -2150,7 +2150,7 @@  discard block
 block discarded – undo
2150 2150
         $contacts = array();
2151 2151
 
2152 2152
         $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2153
-        $resql=$this->db->query($sql);
2153
+        $resql = $this->db->query($sql);
2154 2154
         if ($resql)
2155 2155
         {
2156 2156
             $nump = $this->db->num_rows($resql);
@@ -2160,7 +2160,7 @@  discard block
 block discarded – undo
2160 2160
                 while ($i < $nump)
2161 2161
                 {
2162 2162
                     $obj = $this->db->fetch_object($resql);
2163
-                    $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
2163
+                    $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
2164 2164
                     $i++;
2165 2165
                 }
2166 2166
             }
@@ -2179,11 +2179,11 @@  discard block
 block discarded – undo
2179 2179
      */
2180 2180
     function contact_array_objects()
2181 2181
     {
2182
-        require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2182
+        require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2183 2183
         $contacts = array();
2184 2184
 
2185 2185
         $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2186
-        $resql=$this->db->query($sql);
2186
+        $resql = $this->db->query($sql);
2187 2187
         if ($resql)
2188 2188
         {
2189 2189
             $nump = $this->db->num_rows($resql);
@@ -2214,17 +2214,17 @@  discard block
 block discarded – undo
2214 2214
      *  @param  string	$mode       'email' or 'mobile'
2215 2215
      *  @return string  			Email of contact with format: "Full name <email>"
2216 2216
      */
2217
-    function contact_get_property($rowid,$mode)
2217
+    function contact_get_property($rowid, $mode)
2218 2218
     {
2219
-        $contact_property='';
2219
+        $contact_property = '';
2220 2220
 
2221 2221
         if (empty($rowid)) return '';
2222 2222
 
2223 2223
         $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2224
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2225
-        $sql.= " WHERE rowid = '".$rowid."'";
2224
+        $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
2225
+        $sql .= " WHERE rowid = '".$rowid."'";
2226 2226
 
2227
-        $resql=$this->db->query($sql);
2227
+        $resql = $this->db->query($sql);
2228 2228
         if ($resql)
2229 2229
         {
2230 2230
             $nump = $this->db->num_rows($resql);
@@ -2252,12 +2252,12 @@  discard block
 block discarded – undo
2252 2252
      *	@param	string	$mode	'label' or 'rum'
2253 2253
      *  @return	string			Bank number
2254 2254
      */
2255
-    function display_rib($mode='label')
2255
+    function display_rib($mode = 'label')
2256 2256
     {
2257
-        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2257
+        require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
2258 2258
 
2259 2259
         $bac = new CompanyBankAccount($this->db);
2260
-        $bac->fetch(0,$this->id);
2260
+        $bac->fetch(0, $this->id);
2261 2261
 
2262 2262
         if ($mode == 'label')
2263 2263
         {
@@ -2267,7 +2267,7 @@  discard block
 block discarded – undo
2267 2267
         {
2268 2268
         	if (empty($bac->rum))
2269 2269
         	{
2270
-        		require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2270
+        		require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
2271 2271
         		$prelevement = new BonPrelevement($this->db);
2272 2272
         		$bac->fetch_thirdparty();
2273 2273
         		$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
@@ -2285,7 +2285,7 @@  discard block
 block discarded – undo
2285 2285
      */
2286 2286
     function get_all_rib()
2287 2287
     {
2288
-        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2288
+        require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
2289 2289
         $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id;
2290 2290
         $result = $this->db->query($sql);
2291 2291
         if (!$result) {
@@ -2314,22 +2314,22 @@  discard block
 block discarded – undo
2314 2314
      *	@param	int			$type		Should be 0 to say customer
2315 2315
      *  @return void
2316 2316
      */
2317
-    function get_codeclient($objsoc=0,$type=0)
2317
+    function get_codeclient($objsoc = 0, $type = 0)
2318 2318
     {
2319 2319
         global $conf;
2320
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2320
+        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2321 2321
         {
2322
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2322
+        	$module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2323 2323
 
2324
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2324
+            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2325 2325
             foreach ($dirsociete as $dirroot)
2326 2326
             {
2327
-                $res=dol_include_once($dirroot.$module.'.php');
2327
+                $res = dol_include_once($dirroot.$module.'.php');
2328 2328
                 if ($res) break;
2329 2329
             }
2330 2330
             $mod = new $module();
2331 2331
 
2332
-            $this->code_client = $mod->getNextValue($objsoc,$type);
2332
+            $this->code_client = $mod->getNextValue($objsoc, $type);
2333 2333
             $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2334 2334
 
2335 2335
             dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
@@ -2344,22 +2344,22 @@  discard block
 block discarded – undo
2344 2344
      *	@param	int			$type		Should be 1 to say supplier
2345 2345
      *  @return void
2346 2346
      */
2347
-    function get_codefournisseur($objsoc=0,$type=1)
2347
+    function get_codefournisseur($objsoc = 0, $type = 1)
2348 2348
     {
2349 2349
         global $conf;
2350
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2350
+        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2351 2351
         {
2352
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2352
+			$module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2353 2353
 
2354
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2354
+            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2355 2355
             foreach ($dirsociete as $dirroot)
2356 2356
             {
2357
-                $res=dol_include_once($dirroot.$module.'.php');
2357
+                $res = dol_include_once($dirroot.$module.'.php');
2358 2358
                 if ($res) break;
2359 2359
             }
2360 2360
             $mod = new $module();
2361 2361
 
2362
-            $this->code_fournisseur = $mod->getNextValue($objsoc,$type);
2362
+            $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
2363 2363
 
2364 2364
             dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2365 2365
         }
@@ -2374,23 +2374,23 @@  discard block
 block discarded – undo
2374 2374
     function codeclient_modifiable()
2375 2375
     {
2376 2376
         global $conf;
2377
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2377
+        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2378 2378
         {
2379
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2379
+        	$module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2380 2380
 
2381
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2381
+            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2382 2382
             foreach ($dirsociete as $dirroot)
2383 2383
             {
2384
-                $res=dol_include_once($dirroot.$module.'.php');
2384
+                $res = dol_include_once($dirroot.$module.'.php');
2385 2385
                 if ($res) break;
2386 2386
             }
2387 2387
 
2388 2388
             $mod = new $module();
2389 2389
 
2390 2390
             dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2391
-            if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2391
+            if ($mod->code_modifiable_null && !$this->code_client) return 1;
2392 2392
             if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2393
-            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2393
+            if ($mod->code_modifiable) return 1; // A mettre en dernier
2394 2394
             return 0;
2395 2395
         }
2396 2396
         else
@@ -2408,23 +2408,23 @@  discard block
 block discarded – undo
2408 2408
     function codefournisseur_modifiable()
2409 2409
     {
2410 2410
         global $conf;
2411
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2411
+        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2412 2412
         {
2413
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2413
+        	$module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2414 2414
 
2415
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2415
+            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2416 2416
             foreach ($dirsociete as $dirroot)
2417 2417
             {
2418
-                $res=dol_include_once($dirroot.$module.'.php');
2418
+                $res = dol_include_once($dirroot.$module.'.php');
2419 2419
                 if ($res) break;
2420 2420
             }
2421 2421
 
2422 2422
             $mod = new $module();
2423 2423
 
2424 2424
             dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2425
-            if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2425
+            if ($mod->code_modifiable_null && !$this->code_fournisseur) return 1;
2426 2426
             if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2427
-            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2427
+            if ($mod->code_modifiable) return 1; // A mettre en dernier
2428 2428
             return 0;
2429 2429
         }
2430 2430
         else
@@ -2446,14 +2446,14 @@  discard block
 block discarded – undo
2446 2446
     function check_codeclient()
2447 2447
     {
2448 2448
         global $conf;
2449
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2449
+        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2450 2450
         {
2451
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2451
+        	$module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2452 2452
 
2453
-        	$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2453
+        	$dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2454 2454
             foreach ($dirsociete as $dirroot)
2455 2455
             {
2456
-                $res=dol_include_once($dirroot.$module.'.php');
2456
+                $res = dol_include_once($dirroot.$module.'.php');
2457 2457
                 if ($res) break;
2458 2458
             }
2459 2459
 
@@ -2481,14 +2481,14 @@  discard block
 block discarded – undo
2481 2481
     function check_codefournisseur()
2482 2482
     {
2483 2483
         global $conf;
2484
-        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2484
+        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2485 2485
         {
2486
-        	$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2486
+        	$module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2487 2487
 
2488
-        	$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2488
+        	$dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2489 2489
             foreach ($dirsociete as $dirroot)
2490 2490
             {
2491
-                $res=dol_include_once($dirroot.$module.'.php');
2491
+                $res = dol_include_once($dirroot.$module.'.php');
2492 2492
                 if ($res) break;
2493 2493
             }
2494 2494
 
@@ -2516,20 +2516,20 @@  discard block
 block discarded – undo
2516 2516
     {
2517 2517
         global $conf;
2518 2518
 
2519
-        if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2519
+        if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2520 2520
         {
2521
-        	$file='';
2522
-            $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2521
+        	$file = '';
2522
+            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2523 2523
             foreach ($dirsociete as $dirroot)
2524 2524
             {
2525 2525
             	if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
2526 2526
             	{
2527
-            		$file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
2527
+            		$file = $dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
2528 2528
             		break;
2529 2529
             	}
2530 2530
             }
2531 2531
 
2532
-            if (! empty($file))
2532
+            if (!empty($file))
2533 2533
             {
2534 2534
             	dol_include_once($file);
2535 2535
 
@@ -2570,10 +2570,10 @@  discard block
 block discarded – undo
2570 2570
         if ($this->id)
2571 2571
         {
2572 2572
             $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2573
-            $sql.= " SET parent = ".($id > 0 ? $id : "null");
2574
-            $sql.= " WHERE rowid = " . $this->id;
2573
+            $sql .= " SET parent = ".($id > 0 ? $id : "null");
2574
+            $sql .= " WHERE rowid = ".$this->id;
2575 2575
 			dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2576
-            $resql=$this->db->query($sql);
2576
+            $resql = $this->db->query($sql);
2577 2577
             if ($resql)
2578 2578
             {
2579 2579
             	$this->parent = $id;
@@ -2597,28 +2597,28 @@  discard block
 block discarded – undo
2597 2597
     {
2598 2598
 	    global $conf;
2599 2599
 
2600
-     	switch($idprof)
2600
+     	switch ($idprof)
2601 2601
         {
2602 2602
         	case 1:
2603
-        		$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2603
+        		$ret = (!$conf->global->SOCIETE_IDPROF1_UNIQUE ?false:true);
2604 2604
         		break;
2605 2605
         	case 2:
2606
-        		$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2606
+        		$ret = (!$conf->global->SOCIETE_IDPROF2_UNIQUE ?false:true);
2607 2607
         		break;
2608 2608
         	case 3:
2609
-        		$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2609
+        		$ret = (!$conf->global->SOCIETE_IDPROF3_UNIQUE ?false:true);
2610 2610
         		break;
2611 2611
         	case 4:
2612
-        		$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2612
+        		$ret = (!$conf->global->SOCIETE_IDPROF4_UNIQUE ?false:true);
2613 2613
         		break;
2614 2614
         	case 5:
2615
-        		$ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2615
+        		$ret = (!$conf->global->SOCIETE_IDPROF5_UNIQUE ?false:true);
2616 2616
         		break;
2617 2617
         	case 6:
2618
-        		$ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2618
+        		$ret = (!$conf->global->SOCIETE_IDPROF6_UNIQUE ?false:true);
2619 2619
         		break;
2620 2620
         	default:
2621
-        		$ret=false;
2621
+        		$ret = false;
2622 2622
         }
2623 2623
 
2624 2624
         return $ret;
@@ -2632,39 +2632,39 @@  discard block
 block discarded – undo
2632 2632
      *    @param	int		$socid		Id of thirdparty to exclude (if update)
2633 2633
      *    @return   boolean				True if exists, False if not
2634 2634
      */
2635
-    function id_prof_exists($idprof, $value, $socid=0)
2635
+    function id_prof_exists($idprof, $value, $socid = 0)
2636 2636
     {
2637 2637
     	$field = $idprof;
2638 2638
 
2639
-     	switch($idprof)	// For backward compatibility
2639
+     	switch ($idprof)	// For backward compatibility
2640 2640
         {
2641 2641
         	case '1':
2642 2642
         	case 'idprof1':
2643
-        		$field="siren";
2643
+        		$field = "siren";
2644 2644
         		break;
2645 2645
         	case '2':
2646 2646
         	case 'idprof2':
2647
-        		$field="siret";
2647
+        		$field = "siret";
2648 2648
         		break;
2649 2649
         	case '3':
2650 2650
         	case 'idprof3':
2651
-        		$field="ape";
2651
+        		$field = "ape";
2652 2652
         		break;
2653 2653
         	case '4':
2654 2654
         	case 'idprof4':
2655
-        		$field="idprof4";
2655
+        		$field = "idprof4";
2656 2656
         		break;
2657 2657
         	case '5':
2658
-        		$field="idprof5";
2658
+        		$field = "idprof5";
2659 2659
         		break;
2660 2660
         	case '6':
2661
-        		$field="idprof6";
2661
+        		$field = "idprof6";
2662 2662
         		break;
2663 2663
      	}
2664 2664
 
2665 2665
          //Verify duplicate entries
2666
-        $sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2667
-        if($socid) $sql .= " AND rowid <> ".$socid;
2666
+        $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2667
+        if ($socid) $sql .= " AND rowid <> ".$socid;
2668 2668
         $resql = $this->db->query($sql);
2669 2669
         if ($resql)
2670 2670
         {
@@ -2690,36 +2690,36 @@  discard block
 block discarded – undo
2690 2690
      *  @return int             			<=0 if KO, >0 if OK
2691 2691
      *  TODO better to have this in a lib than into a business class
2692 2692
      */
2693
-    function id_prof_check($idprof,$soc)
2693
+    function id_prof_check($idprof, $soc)
2694 2694
     {
2695 2695
         global $conf;
2696 2696
 
2697
-        $ok=1;
2697
+        $ok = 1;
2698 2698
 
2699
-        if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2699
+        if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2700 2700
 
2701 2701
         // Verifie SIREN si pays FR
2702 2702
         if ($idprof == 1 && $soc->country_code == 'FR')
2703 2703
         {
2704
-            $chaine=trim($this->idprof1);
2705
-            $chaine=preg_replace('/(\s)/','',$chaine);
2704
+            $chaine = trim($this->idprof1);
2705
+            $chaine = preg_replace('/(\s)/', '', $chaine);
2706 2706
 
2707 2707
             if (dol_strlen($chaine) != 9) return -1;
2708 2708
 
2709 2709
             $sum = 0;
2710 2710
 
2711
-            for ($i = 0 ; $i < 10 ; $i = $i+2)
2711
+            for ($i = 0; $i < 10; $i = $i + 2)
2712 2712
             {
2713 2713
                 $sum = $sum + substr($this->idprof1, (8 - $i), 1);
2714 2714
             }
2715 2715
 
2716
-            for ($i = 1 ; $i < 9 ; $i = $i+2)
2716
+            for ($i = 1; $i < 9; $i = $i + 2)
2717 2717
             {
2718 2718
                 $ps = 2 * substr($this->idprof1, (8 - $i), 1);
2719 2719
 
2720 2720
                 if ($ps > 9)
2721 2721
                 {
2722
-                    $ps = substr($ps, 0,1) + substr($ps, 1, 1);
2722
+                    $ps = substr($ps, 0, 1) + substr($ps, 1, 1);
2723 2723
                 }
2724 2724
                 $sum = $sum + $ps;
2725 2725
             }
@@ -2730,8 +2730,8 @@  discard block
 block discarded – undo
2730 2730
         // Verifie SIRET si pays FR
2731 2731
         if ($idprof == 2 && $soc->country_code == 'FR')
2732 2732
         {
2733
-            $chaine=trim($this->idprof2);
2734
-            $chaine=preg_replace('/(\s)/','',$chaine);
2733
+            $chaine = trim($this->idprof2);
2734
+            $chaine = preg_replace('/(\s)/', '', $chaine);
2735 2735
 
2736 2736
             if (dol_strlen($chaine) != 14) return -1;
2737 2737
         }
@@ -2740,11 +2740,11 @@  discard block
 block discarded – undo
2740 2740
         //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
2741 2741
         if ($idprof == 1 && $soc->country_code == 'ES')
2742 2742
         {
2743
-            $string=trim($this->idprof1);
2744
-            $string=preg_replace('/(\s)/','',$string);
2743
+            $string = trim($this->idprof1);
2744
+            $string = preg_replace('/(\s)/', '', $string);
2745 2745
             $string = strtoupper($string);
2746 2746
 
2747
-            for ($i = 0; $i < 9; $i ++)
2747
+            for ($i = 0; $i < 9; $i++)
2748 2748
             $num[$i] = substr($string, $i, 1);
2749 2749
 
2750 2750
             //Check format
@@ -2761,7 +2761,7 @@  discard block
 block discarded – undo
2761 2761
             //algorithm checking type code CIF
2762 2762
             $sum = $num[2] + $num[4] + $num[6];
2763 2763
             for ($i = 1; $i < 8; $i += 2)
2764
-            $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
2764
+            $sum += substr((2 * $num[$i]), 0, 1) + substr((2 * $num[$i]), 1, 1);
2765 2765
             $n = 10 - substr($sum, strlen($sum) - 1, 1);
2766 2766
 
2767 2767
             //Chek special NIF
@@ -2787,7 +2787,7 @@  discard block
 block discarded – undo
2787 2787
 
2788 2788
             //Check NIE XYZ
2789 2789
             if (preg_match('/^[XYZ]{1}/', $string))
2790
-            if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
2790
+            if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1))
2791 2791
             return 3;
2792 2792
             else
2793 2793
             return -3;
@@ -2807,25 +2807,25 @@  discard block
 block discarded – undo
2807 2807
      *   @return	string          		Url or empty string if no URL known
2808 2808
      *   TODO better in a lib than into business class
2809 2809
      */
2810
-    function id_prof_url($idprof,$thirdparty)
2810
+    function id_prof_url($idprof, $thirdparty)
2811 2811
     {
2812
-        global $conf,$langs,$hookmanager;
2812
+        global $conf, $langs, $hookmanager;
2813 2813
 
2814
-        $url='';
2814
+        $url = '';
2815 2815
         $action = '';
2816 2816
 
2817 2817
         $hookmanager->initHooks(array('idprofurl'));
2818
-        $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
2819
-        $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2818
+        $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
2819
+        $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2820 2820
         if (empty($reshook))
2821 2821
         {
2822
-            if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
2822
+            if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
2823 2823
 
2824 2824
             // TODO Move links to validate professional ID into a dictionary table "country" + "link"
2825
-            if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1;    // See also http://avis-situation-sirene.insee.fr/
2825
+            if ($idprof == 1 && $thirdparty->country_code == 'FR') $url = 'http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1; // See also http://avis-situation-sirene.insee.fr/
2826 2826
             //if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/';     // Link no more valid
2827
-            if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
2828
-            if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
2827
+            if ($idprof == 1 && $thirdparty->country_code == 'ES') $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
2828
+            if ($idprof == 1 && $thirdparty->country_code == 'IN') $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
2829 2829
 
2830 2830
             if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
2831 2831
         }
@@ -2844,7 +2844,7 @@  discard block
 block discarded – undo
2844 2844
      */
2845 2845
     function has_projects()
2846 2846
     {
2847
-        $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
2847
+        $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = '.$this->id;
2848 2848
         $resql = $this->db->query($sql);
2849 2849
         if ($resql)
2850 2850
         {
@@ -2870,11 +2870,11 @@  discard block
 block discarded – undo
2870 2870
     function info($id)
2871 2871
     {
2872 2872
         $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
2873
-        $sql.= " fk_user_creat, fk_user_modif";
2874
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
2875
-        $sql.= " WHERE s.rowid = ".$id;
2873
+        $sql .= " fk_user_creat, fk_user_modif";
2874
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
2875
+        $sql .= " WHERE s.rowid = ".$id;
2876 2876
 
2877
-        $result=$this->db->query($sql);
2877
+        $result = $this->db->query($sql);
2878 2878
         if ($result)
2879 2879
         {
2880 2880
             if ($this->db->num_rows($result))
@@ -2886,7 +2886,7 @@  discard block
 block discarded – undo
2886 2886
                 if ($obj->fk_user_creat) {
2887 2887
                     $cuser = new User($this->db);
2888 2888
                     $cuser->fetch($obj->fk_user_creat);
2889
-                    $this->user_creation     = $cuser;
2889
+                    $this->user_creation = $cuser;
2890 2890
                 }
2891 2891
 
2892 2892
                 if ($obj->fk_user_modif) {
@@ -2895,7 +2895,7 @@  discard block
 block discarded – undo
2895 2895
                     $this->user_modification = $muser;
2896 2896
                 }
2897 2897
 
2898
-                $this->ref			     = $obj->name;
2898
+                $this->ref = $obj->name;
2899 2899
                 $this->date_creation     = $this->db->jdate($obj->date_creation);
2900 2900
                 $this->date_modification = $this->db->jdate($obj->date_modification);
2901 2901
             }
@@ -2919,10 +2919,10 @@  discard block
 block discarded – undo
2919 2919
         global $conf;
2920 2920
 
2921 2921
         // Define if third party is treated as company (or not) when nature is unknown
2922
-        $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
2923
-        if (! empty($this->tva_intra)) $isacompany=1;
2924
-        else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
2925
-        else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1;
2922
+        $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
2923
+        if (!empty($this->tva_intra)) $isacompany = 1;
2924
+        else if (!empty($this->typent_code) && in_array($this->typent_code, array('TE_PRIVATE'))) $isacompany = 0;
2925
+        else if (!empty($this->typent_code) && in_array($this->typent_code, array('TE_SMALL', 'TE_MEDIUM', 'TE_LARGE', 'TE_GROUP'))) $isacompany = 1;
2926 2926
 
2927 2927
         return $isacompany;
2928 2928
     }
@@ -2936,13 +2936,13 @@  discard block
 block discarded – undo
2936 2936
     {
2937 2937
         $this->SupplierCategories = array();
2938 2938
         $sql = "SELECT rowid, label";
2939
-        $sql.= " FROM ".MAIN_DB_PREFIX."categorie";
2940
-        $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
2939
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
2940
+        $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
2941 2941
 
2942
-        $resql=$this->db->query($sql);
2942
+        $resql = $this->db->query($sql);
2943 2943
         if ($resql)
2944 2944
         {
2945
-            while ($obj = $this->db->fetch_object($resql) )
2945
+            while ($obj = $this->db->fetch_object($resql))
2946 2946
             {
2947 2947
                 $this->SupplierCategories[$obj->rowid] = $obj->label;
2948 2948
             }
@@ -2965,9 +2965,9 @@  discard block
 block discarded – undo
2965 2965
         if ($categorie_id > 0 && $this->id > 0)
2966 2966
         {
2967 2967
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
2968
-            $sql.= " VALUES (".$categorie_id.", ".$this->id.")";
2968
+            $sql .= " VALUES (".$categorie_id.", ".$this->id.")";
2969 2969
 
2970
-            if ($resql=$this->db->query($sql)) return 0;
2970
+            if ($resql = $this->db->query($sql)) return 0;
2971 2971
         }
2972 2972
         else
2973 2973
         {
@@ -2984,41 +2984,41 @@  discard block
 block discarded – undo
2984 2984
      * 	@param	string	$socname	Name of third party to force
2985 2985
      *  @return int					<0 if KO, id of created account if OK
2986 2986
      */
2987
-    function create_from_member(Adherent $member,$socname='')
2987
+    function create_from_member(Adherent $member, $socname = '')
2988 2988
     {
2989
-        global $user,$langs;
2989
+        global $user, $langs;
2990 2990
 
2991
-        $name = $socname?$socname:$member->societe;
2992
-        if (empty($name)) $name=$member->getFullName($langs);
2991
+        $name = $socname ? $socname : $member->societe;
2992
+        if (empty($name)) $name = $member->getFullName($langs);
2993 2993
 
2994 2994
         // Positionne parametres
2995
-        $this->nom=$name;				// TODO deprecated
2996
-        $this->name=$name;
2997
-        $this->address=$member->address;
2998
-        $this->zip=$member->zip;
2999
-        $this->town=$member->town;
3000
-        $this->country_code=$member->country_code;
3001
-        $this->country_id=$member->country_id;
3002
-        $this->phone=$member->phone;       // Prof phone
3003
-        $this->email=$member->email;
3004
-        $this->skype=$member->skype;
3005
-
3006
-        $this->client = 1;				// A member is a customer by default
2995
+        $this->nom = $name; // TODO deprecated
2996
+        $this->name = $name;
2997
+        $this->address = $member->address;
2998
+        $this->zip = $member->zip;
2999
+        $this->town = $member->town;
3000
+        $this->country_code = $member->country_code;
3001
+        $this->country_id = $member->country_id;
3002
+        $this->phone = $member->phone; // Prof phone
3003
+        $this->email = $member->email;
3004
+        $this->skype = $member->skype;
3005
+
3006
+        $this->client = 1; // A member is a customer by default
3007 3007
         $this->code_client = -1;
3008 3008
         $this->code_fournisseur = -1;
3009 3009
 
3010 3010
         $this->db->begin();
3011 3011
 
3012 3012
         // Cree et positionne $this->id
3013
-        $result=$this->create($user);
3013
+        $result = $this->create($user);
3014 3014
         if ($result >= 0)
3015 3015
         {
3016 3016
             $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3017
-            $sql.= " SET fk_soc=".$this->id;
3018
-            $sql.= " WHERE rowid=".$member->id;
3017
+            $sql .= " SET fk_soc=".$this->id;
3018
+            $sql .= " WHERE rowid=".$member->id;
3019 3019
 
3020 3020
             dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3021
-            $resql=$this->db->query($sql);
3021
+            $resql = $this->db->query($sql);
3022 3022
             if ($resql)
3023 3023
             {
3024 3024
                 $this->db->commit();
@@ -3026,7 +3026,7 @@  discard block
 block discarded – undo
3026 3026
             }
3027 3027
             else
3028 3028
             {
3029
-                $this->error=$this->db->error();
3029
+                $this->error = $this->db->error();
3030 3030
 
3031 3031
                 $this->db->rollback();
3032 3032
                 return -1;
@@ -3035,7 +3035,7 @@  discard block
 block discarded – undo
3035 3035
         else
3036 3036
         {
3037 3037
             // $this->error deja positionne
3038
-            dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
3038
+            dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
3039 3039
 
3040 3040
             $this->db->rollback();
3041 3041
             return $result;
@@ -3052,12 +3052,12 @@  discard block
 block discarded – undo
3052 3052
     {
3053 3053
     	global $langs;
3054 3054
 
3055
-    	$this->id=0;
3056
-    	$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3057
-    	$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3058
-    	$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3059
-    	$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3060
-		$this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
3055
+    	$this->id = 0;
3056
+    	$this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
3057
+    	$this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3058
+    	$this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
3059
+    	$this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
3060
+		$this->state_id = empty($conf->global->MAIN_INFO_SOCIETE_STATE) ? '' : $conf->global->MAIN_INFO_SOCIETE_STATE;
3061 3061
 
3062 3062
         /* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only.
3063 3063
         If we need label, label must be loaded by output that need it from id (label depends on output language)
@@ -3068,59 +3068,59 @@  discard block
 block discarded – undo
3068 3068
         }
3069 3069
 		*/
3070 3070
 
3071
-    	$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3071
+    	$this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
3072 3072
 
3073
-    	$this->nom=$this->name; 									// deprecated
3073
+    	$this->nom = $this->name; // deprecated
3074 3074
 
3075 3075
     	// We define country_id, country_code and country
3076
-    	$country_id=$country_code=$country_label='';
3077
-    	if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3076
+    	$country_id = $country_code = $country_label = '';
3077
+    	if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3078 3078
     	{
3079
-    		$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3080
-    		$country_id=$tmp[0];
3081
-    		if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3079
+    		$tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3080
+    		$country_id = $tmp[0];
3081
+    		if (!empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3082 3082
     		{
3083
-    			$country_code=$tmp[1];
3084
-    			$country_label=$tmp[2];
3083
+    			$country_code = $tmp[1];
3084
+    			$country_label = $tmp[2];
3085 3085
     		}
3086 3086
     		else                    // For backward compatibility
3087 3087
     		{
3088 3088
     			dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3089 3089
     			include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3090
-    			$country_code=getCountry($country_id,2,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3091
-    			$country_label=getCountry($country_id,0,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3090
+    			$country_code = getCountry($country_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
3091
+    			$country_label = getCountry($country_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
3092 3092
     		}
3093 3093
     	}
3094
-    	$this->country_id=$country_id;
3095
-    	$this->country_code=$country_code;
3096
-    	$this->country=$country_label;
3097
-    	if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3098
-
3099
-    	$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3100
-    	$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3101
-    	$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3094
+    	$this->country_id = $country_id;
3095
+    	$this->country_code = $country_code;
3096
+    	$this->country = $country_label;
3097
+    	if (is_object($langs)) $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
3098
+
3099
+    	$this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
3100
+    	$this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
3101
+    	$this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
3102 3102
     	// Id prof generiques
3103
-    	$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3104
-    	$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3105
-    	$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3106
-    	$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3107
-    	$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3108
-    	$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3109
-    	$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3110
-    	$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3111
-    	$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3112
-    	$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3113
-    	$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3114
-    	$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3115
-    	$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3116
-    	$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3103
+    	$this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
3104
+    	$this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
3105
+    	$this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
3106
+    	$this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
3107
+    	$this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
3108
+    	$this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
3109
+    	$this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
3110
+    	$this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3111
+    	$this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
3112
+    	$this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3113
+    	$this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
3114
+    	$this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
3115
+    	$this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3116
+    	$this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3117 3117
 
3118 3118
     	// Define if company use vat or not
3119
-    	$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3119
+    	$this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
3120 3120
 
3121 3121
     	// Define if company use local taxes
3122
-    	$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
3123
-    	$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
3122
+    	$this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == 'localtax1on')) ? 1 : 0);
3123
+    	$this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == 'localtax2on')) ? 1 : 0);
3124 3124
     }
3125 3125
 
3126 3126
     /**
@@ -3132,46 +3132,46 @@  discard block
 block discarded – undo
3132 3132
      */
3133 3133
     function initAsSpecimen()
3134 3134
     {
3135
-        $now=dol_now();
3135
+        $now = dol_now();
3136 3136
 
3137 3137
         // Initialize parameters
3138
-        $this->id=0;
3139
-        $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
3140
-        $this->nom = $this->name;   // For backward compatibility
3138
+        $this->id = 0;
3139
+        $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
3140
+        $this->nom = $this->name; // For backward compatibility
3141 3141
         $this->ref_ext = 'Ref ext';
3142
-        $this->specimen=1;
3143
-        $this->address='21 jump street';
3144
-        $this->zip='99999';
3145
-        $this->town='MyTown';
3146
-        $this->state_id=1;
3147
-        $this->state_code='AA';
3148
-        $this->state='MyState';
3149
-        $this->country_id=1;
3150
-        $this->country_code='FR';
3151
-        $this->email='[email protected]';
3152
-        $this->skype='tom.hanson';
3153
-        $this->url='http://www.specimen.com';
3154
-
3155
-        $this->phone='0909090901';
3156
-        $this->fax='0909090909';
3157
-
3158
-        $this->code_client='CC-'.dol_print_date($now,'dayhourlog');
3159
-        $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
3160
-        $this->capital=10000;
3161
-        $this->client=1;
3162
-        $this->prospect=1;
3163
-        $this->fournisseur=1;
3164
-        $this->tva_assuj=1;
3165
-        $this->tva_intra='EU1234567';
3166
-        $this->note_public='This is a comment (public)';
3167
-        $this->note_private='This is a comment (private)';
3168
-
3169
-        $this->idprof1='idprof1';
3170
-        $this->idprof2='idprof2';
3171
-        $this->idprof3='idprof3';
3172
-        $this->idprof4='idprof4';
3173
-        $this->idprof5='idprof5';
3174
-        $this->idprof6='idprof6';
3142
+        $this->specimen = 1;
3143
+        $this->address = '21 jump street';
3144
+        $this->zip = '99999';
3145
+        $this->town = 'MyTown';
3146
+        $this->state_id = 1;
3147
+        $this->state_code = 'AA';
3148
+        $this->state = 'MyState';
3149
+        $this->country_id = 1;
3150
+        $this->country_code = 'FR';
3151
+        $this->email = '[email protected]';
3152
+        $this->skype = 'tom.hanson';
3153
+        $this->url = 'http://www.specimen.com';
3154
+
3155
+        $this->phone = '0909090901';
3156
+        $this->fax = '0909090909';
3157
+
3158
+        $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
3159
+        $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
3160
+        $this->capital = 10000;
3161
+        $this->client = 1;
3162
+        $this->prospect = 1;
3163
+        $this->fournisseur = 1;
3164
+        $this->tva_assuj = 1;
3165
+        $this->tva_intra = 'EU1234567';
3166
+        $this->note_public = 'This is a comment (public)';
3167
+        $this->note_private = 'This is a comment (private)';
3168
+
3169
+        $this->idprof1 = 'idprof1';
3170
+        $this->idprof2 = 'idprof2';
3171
+        $this->idprof3 = 'idprof3';
3172
+        $this->idprof4 = 'idprof4';
3173
+        $this->idprof5 = 'idprof5';
3174
+        $this->idprof6 = 'idprof6';
3175 3175
     }
3176 3176
 
3177 3177
     /**
@@ -3180,7 +3180,7 @@  discard block
 block discarded – undo
3180 3180
      *	@param		int		$localTaxNum	To get info for only localtax1 or localtax2
3181 3181
      *  @return		boolean					true or false
3182 3182
      */
3183
-    function useLocalTax($localTaxNum=0)
3183
+    function useLocalTax($localTaxNum = 0)
3184 3184
     {
3185 3185
     	$sql  = "SELECT t.localtax1, t.localtax2";
3186 3186
     	$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
@@ -3191,7 +3191,7 @@  discard block
 block discarded – undo
3191 3191
     	elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3192 3192
 
3193 3193
     	dol_syslog("useLocalTax", LOG_DEBUG);
3194
-    	$resql=$this->db->query($sql);
3194
+    	$resql = $this->db->query($sql);
3195 3195
     	if ($resql)
3196 3196
     	{
3197 3197
    			return ($this->db->num_rows($resql) > 0);
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
         $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3213 3213
 
3214 3214
         dol_syslog("useNPR", LOG_DEBUG);
3215
-        $resql=$this->db->query($sql);
3215
+        $resql = $this->db->query($sql);
3216 3216
         if ($resql)
3217 3217
         {
3218 3218
             return ($this->db->num_rows($resql) > 0);
@@ -3233,15 +3233,15 @@  discard block
 block discarded – undo
3233 3233
 		$sql .= " AND r.active = 1";
3234 3234
 
3235 3235
 		dol_syslog("useRevenueStamp", LOG_DEBUG);
3236
-		$resql=$this->db->query($sql);
3236
+		$resql = $this->db->query($sql);
3237 3237
 		if ($resql)
3238 3238
 		{
3239
-			$obj=$this->db->fetch_object($resql);
3240
-   			return (($obj->nb > 0)?true:false);
3239
+			$obj = $this->db->fetch_object($resql);
3240
+   			return (($obj->nb > 0) ?true:false);
3241 3241
 		}
3242 3242
 		else
3243 3243
 		{
3244
-			$this->error=$this->db->lasterror();
3244
+			$this->error = $this->db->lasterror();
3245 3245
 			return false;
3246 3246
 		}
3247 3247
 	}
@@ -3266,11 +3266,11 @@  discard block
 block discarded – undo
3266 3266
 	{
3267 3267
 		global $langs;
3268 3268
 
3269
-		$lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
3269
+		$lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
3270 3270
 		// If lib not found in language file, we get label from cache/databse
3271 3271
 		if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
3272 3272
 		{
3273
-			$lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
3273
+			$lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
3274 3274
 		}
3275 3275
 		return $lib;
3276 3276
 	}
@@ -3295,7 +3295,7 @@  discard block
 block discarded – undo
3295 3295
 	 *  @param	string	$label		Label to use for status for added status
3296 3296
 	 *  @return string        		Libelle
3297 3297
 	 */
3298
-	function getLibProspCommStatut($mode=0, $label='')
3298
+	function getLibProspCommStatut($mode = 0, $label = '')
3299 3299
 	{
3300 3300
 		return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
3301 3301
 	}
@@ -3308,18 +3308,18 @@  discard block
 block discarded – undo
3308 3308
 	 *  @param	string		$label			Label to use for status for added status
3309 3309
 	 *  @return string       	 			Libelle du statut
3310 3310
 	 */
3311
-	function LibProspCommStatut($statut, $mode=0, $label='')
3311
+	function LibProspCommStatut($statut, $mode = 0, $label = '')
3312 3312
 	{
3313 3313
 		global $langs;
3314 3314
 		$langs->load('customers');
3315 3315
 
3316 3316
 		if ($mode == 2)
3317 3317
 		{
3318
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3319
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3320
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3321
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3322
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3318
+			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"), -1).' '.$langs->trans("StatusProspect-1");
3319
+			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3320
+			elseif ($statut == '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3321
+			elseif ($statut == '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3322
+			elseif ($statut == '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3323 3323
 			else
3324 3324
 			{
3325 3325
 				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
@@ -3327,11 +3327,11 @@  discard block
 block discarded – undo
3327 3327
 		}
3328 3328
 		if ($mode == 3)
3329 3329
 		{
3330
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1);
3331
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3332
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1);
3333
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2);
3334
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3);
3330
+			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"), -1);
3331
+			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3332
+			elseif ($statut == '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1);
3333
+			elseif ($statut == '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2);
3334
+			elseif ($statut == '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3);
3335 3335
 			else
3336 3336
 			{
3337 3337
 				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
@@ -3339,11 +3339,11 @@  discard block
 block discarded – undo
3339 3339
 		}
3340 3340
 		if ($mode == 4)
3341 3341
 		{
3342
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3343
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3344
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3345
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3346
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3342
+			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"), -1).' '.$langs->trans("StatusProspect-1");
3343
+			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3344
+			elseif ($statut == '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3345
+			elseif ($statut == '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3346
+			elseif ($statut == '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3347 3347
 			else
3348 3348
 			{
3349 3349
 				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
@@ -3371,13 +3371,13 @@  discard block
 block discarded – undo
3371 3371
 	 *  @param     string      $mode    'customer' or 'supplier'
3372 3372
 	 *  @return    array				array('opened'=>Amount, 'total'=>Total amount)
3373 3373
 	 */
3374
-	function getOutstandingProposals($mode='customer')
3374
+	function getOutstandingProposals($mode = 'customer')
3375 3375
 	{
3376
-		$table='propal';
3376
+		$table = 'propal';
3377 3377
 		if ($mode == 'supplier') $table = 'supplier_proposal';
3378 3378
 
3379 3379
 		$sql  = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3380
-		$sql .= " WHERE fk_soc = ". $this->id;
3380
+		$sql .= " WHERE fk_soc = ".$this->id;
3381 3381
 		if ($mode == 'supplier') {
3382 3382
 			$sql .= " AND entity IN (".getEntity('supplier_proposal').")";
3383 3383
 		} else {
@@ -3385,18 +3385,18 @@  discard block
 block discarded – undo
3385 3385
 		}
3386 3386
 
3387 3387
 		dol_syslog("getOutstandingProposals", LOG_DEBUG);
3388
-		$resql=$this->db->query($sql);
3388
+		$resql = $this->db->query($sql);
3389 3389
 		if ($resql)
3390 3390
 		{
3391 3391
 			$outstandingOpened = 0;
3392 3392
 			$outstandingTotal = 0;
3393 3393
 			$outstandingTotalIncTax = 0;
3394
-			while($obj=$this->db->fetch_object($resql)) {
3395
-				$outstandingTotal+= $obj->total_ht;
3396
-				$outstandingTotalIncTax+= $obj->total_ttc;
3394
+			while ($obj = $this->db->fetch_object($resql)) {
3395
+				$outstandingTotal += $obj->total_ht;
3396
+				$outstandingTotalIncTax += $obj->total_ttc;
3397 3397
 				if ($obj->fk_statut != 0)    // Not a draft
3398 3398
 				{
3399
-					$outstandingOpened+=$obj->total_ttc;
3399
+					$outstandingOpened += $obj->total_ttc;
3400 3400
 				}
3401 3401
 			}
3402 3402
 			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
@@ -3411,13 +3411,13 @@  discard block
 block discarded – undo
3411 3411
 	 *  @param     string      $mode    'customer' or 'supplier'
3412 3412
 	 *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3413 3413
 	 */
3414
-	function getOutstandingOrders($mode='customer')
3414
+	function getOutstandingOrders($mode = 'customer')
3415 3415
 	{
3416
-		$table='commande';
3416
+		$table = 'commande';
3417 3417
 		if ($mode == 'supplier') $table = 'commande_fournisseur';
3418 3418
 
3419 3419
 		$sql  = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3420
-		$sql .= " WHERE fk_soc = ". $this->id;
3420
+		$sql .= " WHERE fk_soc = ".$this->id;
3421 3421
 		if ($mode == 'supplier') {
3422 3422
 			$sql .= " AND entity IN (".getEntity('supplier_order').")";
3423 3423
 		} else {
@@ -3425,18 +3425,18 @@  discard block
 block discarded – undo
3425 3425
 		}
3426 3426
 
3427 3427
 		dol_syslog("getOutstandingOrders", LOG_DEBUG);
3428
-		$resql=$this->db->query($sql);
3428
+		$resql = $this->db->query($sql);
3429 3429
 		if ($resql)
3430 3430
 		{
3431 3431
 			$outstandingOpened = 0;
3432 3432
 			$outstandingTotal = 0;
3433 3433
 			$outstandingTotalIncTax = 0;
3434
-			while($obj=$this->db->fetch_object($resql)) {
3435
-				$outstandingTotal+= $obj->total_ht;
3436
-				$outstandingTotalIncTax+= $obj->total_ttc;
3434
+			while ($obj = $this->db->fetch_object($resql)) {
3435
+				$outstandingTotal += $obj->total_ht;
3436
+				$outstandingTotalIncTax += $obj->total_ttc;
3437 3437
 				if ($obj->fk_statut != 0)    // Not a draft
3438 3438
 				{
3439
-					$outstandingOpened+=$obj->total_ttc;
3439
+					$outstandingOpened += $obj->total_ttc;
3440 3440
 				}
3441 3441
 			}
3442 3442
 			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
@@ -3451,9 +3451,9 @@  discard block
 block discarded – undo
3451 3451
 	 *  @param     string      $mode    'customer' or 'supplier'
3452 3452
 	 *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3453 3453
 	 */
3454
-	function getOutstandingBills($mode='customer')
3454
+	function getOutstandingBills($mode = 'customer')
3455 3455
 	{
3456
-		$table='facture';
3456
+		$table = 'facture';
3457 3457
 		if ($mode == 'supplier') $table = 'facture_fourn';
3458 3458
 
3459 3459
 		/* Accurate value of remain to pay is to sum remaintopay for each invoice
@@ -3463,9 +3463,9 @@  discard block
 block discarded – undo
3463 3463
 		 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3464 3464
 		 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3465 3465
 		 */
3466
-		if ($mode == 'supplier') $sql  = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3467
-		else $sql  = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3468
-		$sql .= " WHERE fk_soc = ". $this->id;
3466
+		if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3467
+		else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3468
+		$sql .= " WHERE fk_soc = ".$this->id;
3469 3469
 		if ($mode == 'supplier') {
3470 3470
 			$sql .= " AND entity IN (".getEntity('facture_fourn').")";
3471 3471
 		} else {
@@ -3473,7 +3473,7 @@  discard block
 block discarded – undo
3473 3473
 		}
3474 3474
 
3475 3475
 		dol_syslog("getOutstandingBills", LOG_DEBUG);
3476
-		$resql=$this->db->query($sql);
3476
+		$resql = $this->db->query($sql);
3477 3477
 		if ($resql)
3478 3478
 		{
3479 3479
 			$outstandingOpened = 0;
@@ -3482,21 +3482,21 @@  discard block
 block discarded – undo
3482 3482
 			if ($mode == 'supplier')
3483 3483
 			{
3484 3484
 				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
3485
-				$tmpobject=new FactureFournisseur($this->db);
3485
+				$tmpobject = new FactureFournisseur($this->db);
3486 3486
 			}
3487 3487
 			else
3488 3488
 			{
3489 3489
 				require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3490
-				$tmpobject=new Facture($this->db);
3490
+				$tmpobject = new Facture($this->db);
3491 3491
 			}
3492
-			while($obj=$this->db->fetch_object($resql)) {
3493
-				$tmpobject->id=$obj->rowid;
3492
+			while ($obj = $this->db->fetch_object($resql)) {
3493
+				$tmpobject->id = $obj->rowid;
3494 3494
 				if ($obj->fk_statut != 0                                           // Not a draft
3495
-					&& ! ($obj->fk_statut == 3 && $obj->close_code == 'replaced')  // Not a replaced invoice
3495
+					&& !($obj->fk_statut == 3 && $obj->close_code == 'replaced')  // Not a replaced invoice
3496 3496
 					)
3497 3497
 				{
3498
-					$outstandingTotal+= $obj->total_ht;
3499
-					$outstandingTotalIncTax+= $obj->total_ttc;
3498
+					$outstandingTotal += $obj->total_ht;
3499
+					$outstandingTotalIncTax += $obj->total_ttc;
3500 3500
 				}
3501 3501
 				if ($obj->paye == 0
3502 3502
 					&& $obj->fk_statut != 0    // Not a draft
@@ -3507,7 +3507,7 @@  discard block
 block discarded – undo
3507 3507
 					$paiement = $tmpobject->getSommePaiement();
3508 3508
 					$creditnotes = $tmpobject->getSumCreditNotesUsed();
3509 3509
 					$deposits = $tmpobject->getSumDepositsUsed();
3510
-					$outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
3510
+					$outstandingOpened += $obj->total_ttc - $paiement - $creditnotes - $deposits;
3511 3511
 				}
3512 3512
 			}
3513 3513
 			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
@@ -3534,26 +3534,26 @@  discard block
 block discarded – undo
3534 3534
 	     $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3535 3535
 	     */
3536 3536
 	    $sql  = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3537
-	    $sql .= " WHERE fk_soc = ". $this->id;
3537
+	    $sql .= " WHERE fk_soc = ".$this->id;
3538 3538
 	    $sql .= " AND paye = 0";
3539
-	    $sql .= " AND fk_statut <> 0";	// Not a draft
3539
+	    $sql .= " AND fk_statut <> 0"; // Not a draft
3540 3540
 	    //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3541
-	    $sql .= " AND fk_statut <> 3";		// Not abandonned
3542
-	    $sql .= " AND fk_statut <> 2";		// Not clasified as paid
3541
+	    $sql .= " AND fk_statut <> 3"; // Not abandonned
3542
+	    $sql .= " AND fk_statut <> 2"; // Not clasified as paid
3543 3543
 
3544 3544
 	    dol_syslog("get_OutstandingBill", LOG_DEBUG);
3545
-	    $resql=$this->db->query($sql);
3545
+	    $resql = $this->db->query($sql);
3546 3546
 	    if ($resql)
3547 3547
 	    {
3548 3548
 	        $outstandingAmount = 0;
3549 3549
 	        require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3550
-	        $tmpobject=new Facture($this->db);
3551
-	        while($obj=$this->db->fetch_object($resql)) {
3552
-	            $tmpobject->id=$obj->rowid;
3550
+	        $tmpobject = new Facture($this->db);
3551
+	        while ($obj = $this->db->fetch_object($resql)) {
3552
+	            $tmpobject->id = $obj->rowid;
3553 3553
 	            $paiement = $tmpobject->getSommePaiement();
3554 3554
 	            $creditnotes = $tmpobject->getSumCreditNotesUsed();
3555 3555
 	            $deposits = $tmpobject->getSumDepositsUsed();
3556
-	            $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3556
+	            $outstandingAmount += $obj->total_ttc - $paiement - $creditnotes - $deposits;
3557 3557
 	        }
3558 3558
 	        return $outstandingAmount;
3559 3559
 	    }
@@ -3582,10 +3582,10 @@  discard block
 block discarded – undo
3582 3582
 		global $langs;
3583 3583
 		$langs->load('companies');
3584 3584
 
3585
-		if ($statut==0) return $langs->trans("NorProspectNorCustomer");
3586
-		if ($statut==1) return $langs->trans("Customer");
3587
-		if ($statut==2) return $langs->trans("Prospect");
3588
-		if ($statut==3) return $langs->trans("ProspectCustomer");
3585
+		if ($statut == 0) return $langs->trans("NorProspectNorCustomer");
3586
+		if ($statut == 1) return $langs->trans("Customer");
3587
+		if ($statut == 2) return $langs->trans("Prospect");
3588
+		if ($statut == 3) return $langs->trans("ProspectCustomer");
3589 3589
 
3590 3590
 	}
3591 3591
 
@@ -3601,26 +3601,26 @@  discard block
 block discarded – undo
3601 3601
 	 *  @param  null|array  $moreparams     Array to provide more information
3602 3602
 	 *	@return int        					<0 if KO, >0 if OK
3603 3603
 	 */
3604
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
3604
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3605 3605
 	{
3606
-		global $conf,$user,$langs;
3606
+		global $conf, $user, $langs;
3607 3607
 
3608
-		if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
3608
+		if (!empty($moreparams) && !empty($moreparams['use_companybankid']))
3609 3609
 		{
3610 3610
 		    $modelpath = "core/modules/bank/doc/";
3611 3611
 
3612 3612
 		    include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3613 3613
 		    $companybankaccount = new CompanyBankAccount($this->db);
3614 3614
 		    $result = $companybankaccount->fetch($moreparams['use_companybankid']);
3615
-		    if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3616
-		    $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3615
+		    if (!$result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3616
+		    $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3617 3617
 		}
3618 3618
 		else
3619 3619
 		{
3620 3620
     		// Positionne le modele sur le nom du modele a utiliser
3621
-    		if (! dol_strlen($modele))
3621
+    		if (!dol_strlen($modele))
3622 3622
     		{
3623
-    			if (! empty($conf->global->COMPANY_ADDON_PDF))
3623
+    			if (!empty($conf->global->COMPANY_ADDON_PDF))
3624 3624
     			{
3625 3625
     				$modele = $conf->global->COMPANY_ADDON_PDF;
3626 3626
     			}
@@ -3633,7 +3633,7 @@  discard block
 block discarded – undo
3633 3633
 
3634 3634
     		$modelpath = "core/modules/societe/doc/";
3635 3635
 
3636
-    		$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3636
+    		$result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3637 3637
 		}
3638 3638
 
3639 3639
 		return $result;
@@ -3652,7 +3652,7 @@  discard block
 block discarded – undo
3652 3652
 	 */
3653 3653
 	public function setCategories($categories, $type)
3654 3654
 	{
3655
-		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3655
+		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3656 3656
 
3657 3657
 	    // Decode type
3658 3658
 		if ($type == 'customer') {
@@ -3662,7 +3662,7 @@  discard block
 block discarded – undo
3662 3662
 			$type_id = Categorie::TYPE_SUPPLIER;
3663 3663
 			$type_text = 'supplier';
3664 3664
 		} else {
3665
-			dol_syslog(__METHOD__ . ': Type ' . $type .  'is an unknown company category type. Done nothing.', LOG_ERR);
3665
+			dol_syslog(__METHOD__.': Type '.$type.'is an unknown company category type. Done nothing.', LOG_ERR);
3666 3666
 			return;
3667 3667
 		}
3668 3668
 
Please login to merge, or discard this patch.
Braces   +558 added lines, -328 removed lines patch added patch discarded remove patch
@@ -408,15 +408,25 @@  discard block
 block discarded – undo
408 408
 		$error=0;
409 409
 
410 410
         // Clean parameters
411
-        if (empty($this->status)) $this->status=0;
411
+        if (empty($this->status)) {
412
+        	$this->status=0;
413
+        }
412 414
         $this->name=$this->name?trim($this->name):trim($this->nom);
413
-        if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
415
+        if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) {
416
+        	$this->name=ucwords($this->name);
417
+        }
414 418
         $this->nom=$this->name; // For backward compatibility
415
-        if (empty($this->client))      $this->client=0;
416
-        if (empty($this->fournisseur)) $this->fournisseur=0;
419
+        if (empty($this->client)) {
420
+        	$this->client=0;
421
+        }
422
+        if (empty($this->fournisseur)) {
423
+        	$this->fournisseur=0;
424
+        }
417 425
         $this->import_key = trim($this->import_key);
418 426
 
419
-		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
427
+		if (!empty($this->multicurrency_code)) {
428
+			$this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
429
+		}
420 430
 		if (empty($this->fk_multicurrency))
421 431
 		{
422 432
 			$this->multicurrency_code = '';
@@ -430,8 +440,12 @@  discard block
 block discarded – undo
430 440
         $this->db->begin();
431 441
 
432 442
         // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
433
-        if ($this->code_client == -1)      $this->get_codeclient($this,0);
434
-        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
443
+        if ($this->code_client == -1) {
444
+        	$this->get_codeclient($this,0);
445
+        }
446
+        if ($this->code_fournisseur == -1) {
447
+        	$this->get_codefournisseur($this,1);
448
+        }
435 449
 
436 450
         // Check more parameters (including mandatory setup
437 451
         // If error, this->errors[] is filled
@@ -476,32 +490,32 @@  discard block
 block discarded – undo
476 490
                 {
477 491
                     // Call trigger
478 492
                     $result=$this->call_trigger('COMPANY_CREATE',$user);
479
-                    if ($result < 0) $error++;
493
+                    if ($result < 0) {
494
+                    	$error++;
495
+                    }
480 496
                     // End call triggers
497
+                } else {
498
+                	$error++;
481 499
                 }
482
-                else $error++;
483 500
 
484 501
                 if (! $error)
485 502
                 {
486 503
                     dol_syslog(get_class($this)."::Create success id=".$this->id);
487 504
                     $this->db->commit();
488 505
                     return $this->id;
489
-                }
490
-                else
506
+                } else
491 507
                 {
492 508
                     dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
493 509
                     $this->db->rollback();
494 510
                     return -4;
495 511
                 }
496
-            }
497
-            else
512
+            } else
498 513
             {
499 514
                 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
500 515
                 {
501 516
                     $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
502 517
                     $result=-1;
503
-                }
504
-                else
518
+                } else
505 519
                 {
506 520
                     $this->error=$this->db->lasterror();
507 521
                     $result=-2;
@@ -510,8 +524,7 @@  discard block
 block discarded – undo
510 524
                 return $result;
511 525
             }
512 526
 
513
-        }
514
-        else
527
+        } else
515 528
         {
516 529
             $this->db->rollback();
517 530
             dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
@@ -663,8 +676,7 @@  discard block
 block discarded – undo
663 676
         				}
664 677
         			}
665 678
         		}
666
-        	}
667
-        	else
679
+        	} else
668 680
         	{
669 681
         		//var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
670 682
         		if ($key == 'EMAIL')
@@ -690,7 +702,9 @@  discard block
 block discarded – undo
690 702
         	}
691 703
         }
692 704
 
693
-        if ($error) $result = -4;
705
+        if ($error) {
706
+        	$result = -4;
707
+        }
694 708
 
695 709
         return $result;
696 710
     }
@@ -749,9 +763,13 @@  discard block
 block discarded – undo
749 763
 
750 764
         $this->tva_assuj	= trim($this->tva_assuj);
751 765
         $this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
752
-        if (empty($this->status)) $this->status = 0;
766
+        if (empty($this->status)) {
767
+        	$this->status = 0;
768
+        }
753 769
 
754
-		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
770
+		if (!empty($this->multicurrency_code)) {
771
+			$this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
772
+		}
755 773
 		if (empty($this->fk_multicurrency))
756 774
 		{
757 775
 			$this->multicurrency_code = '';
@@ -765,8 +783,13 @@  discard block
 block discarded – undo
765 783
         $this->localtax1_value=trim($this->localtax1_value);
766 784
         $this->localtax2_value=trim($this->localtax2_value);
767 785
 
768
-        if ($this->capital != '') $this->capital=price2num(trim($this->capital));
769
-        if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
786
+        if ($this->capital != '') {
787
+        	$this->capital=price2num(trim($this->capital));
788
+        }
789
+        if (! is_numeric($this->capital)) {
790
+        	$this->capital = '';
791
+        }
792
+        // '' = undef
770 793
 
771 794
         $this->effectif_id=trim($this->effectif_id);
772 795
         $this->forme_juridique_code=trim($this->forme_juridique_code);
@@ -775,8 +798,12 @@  discard block
 block discarded – undo
775 798
         $this->barcode=trim($this->barcode);
776 799
 
777 800
         // For automatic creation
778
-        if ($this->code_client == -1) $this->get_codeclient($this,0);
779
-        if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
801
+        if ($this->code_client == -1) {
802
+        	$this->get_codeclient($this,0);
803
+        }
804
+        if ($this->code_fournisseur == -1) {
805
+        	$this->get_codefournisseur($this,1);
806
+        }
780 807
 
781 808
         $this->code_compta=trim($this->code_compta);
782 809
         $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
@@ -796,7 +823,9 @@  discard block
 block discarded – undo
796 823
         	if (empty($this->code_compta))
797 824
         	{
798 825
         		$ret=$this->get_codecompta('customer');
799
-        		if ($ret < 0) return -1;
826
+        		if ($ret < 0) {
827
+        			return -1;
828
+        		}
800 829
         	}
801 830
 
802 831
         	$customer=true;
@@ -809,7 +838,9 @@  discard block
 block discarded – undo
809 838
         	if (empty($this->code_compta_fournisseur))
810 839
         	{
811 840
         		$ret=$this->get_codecompta('supplier');
812
-        		if ($ret < 0) return -1;
841
+        		if ($ret < 0) {
842
+        			return -1;
843
+        		}
813 844
         	}
814 845
 
815 846
         	$supplier=true;
@@ -828,7 +859,10 @@  discard block
 block discarded – undo
828 859
         // Check name is required and codes are ok or unique.
829 860
         // If error, this->errors[] is filled
830 861
         $result = 0;
831
-        if ($action != 'add') $result = $this->verify();	// We don't check when update called during a create because verify was already done
862
+        if ($action != 'add') {
863
+        	$result = $this->verify();
864
+        }
865
+        // We don't check when update called during a create because verify was already done
832 866
 
833 867
         if ($result >= 0)
834 868
         {
@@ -871,22 +905,26 @@  discard block
 block discarded – undo
871 905
             	if($this->localtax1_value!='')
872 906
             	{
873 907
             		$sql .=",localtax1_value =".$this->localtax1_value;
908
+            	} else {
909
+            		$sql .=",localtax1_value =0.000";
874 910
             	}
875
-            	else $sql .=",localtax1_value =0.000";
876 911
 
912
+            } else {
913
+            	$sql .=",localtax1_value =0.000";
877 914
             }
878
-            else $sql .=",localtax1_value =0.000";
879 915
 
880 916
             if($this->localtax2_assuj==1)
881 917
             {
882 918
             	if($this->localtax2_value!='')
883 919
             	{
884 920
             		$sql .=",localtax2_value =".$this->localtax2_value;
921
+            	} else {
922
+            		$sql .=",localtax2_value =0.000";
885 923
             	}
886
-            	else $sql .=",localtax2_value =0.000";
887 924
 
925
+            } else {
926
+            	$sql .=",localtax2_value =0.000";
888 927
             }
889
-            else $sql .=",localtax2_value =0.000";
890 928
 
891 929
             $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
892 930
 
@@ -977,8 +1015,7 @@  discard block
 block discarded – undo
977 1015
 		            			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
978 1016
 		            			$error++;
979 1017
 		            		}
980
-		            	}
981
-		            	else if ($result < 0)
1018
+		            	} else if ($result < 0)
982 1019
 		            	{
983 1020
 		            		$this->error=$lmember->error;
984 1021
 		            		$error++;
@@ -995,22 +1032,27 @@  discard block
 block discarded – undo
995 1032
                 $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
996 1033
                 if (empty($reshook))
997 1034
                 {
998
-                	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1035
+                	if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
1036
+                		// For avoid conflicts if trigger used
999 1037
                 	{
1000 1038
                 		$result=$this->insertExtraFields();
1039
+                	}
1001 1040
                 		if ($result < 0)
1002 1041
                 		{
1003 1042
                 			$error++;
1004 1043
                 		}
1005 1044
                 	}
1045
+                } else if ($reshook < 0) {
1046
+                	$error++;
1006 1047
                 }
1007
-                else if ($reshook < 0) $error++;
1008 1048
 
1009 1049
                 if (! $error && $call_trigger)
1010 1050
                 {
1011 1051
                     // Call trigger
1012 1052
                     $result=$this->call_trigger('COMPANY_MODIFY',$user);
1013
-                    if ($result < 0) $error++;
1053
+                    if ($result < 0) {
1054
+                    	$error++;
1055
+                    }
1014 1056
                     // End call triggers
1015 1057
                 }
1016 1058
 
@@ -1019,22 +1061,19 @@  discard block
 block discarded – undo
1019 1061
                     dol_syslog(get_class($this)."::Update success");
1020 1062
                     $this->db->commit();
1021 1063
                     return 1;
1022
-                }
1023
-                else
1064
+                } else
1024 1065
 				{
1025 1066
                     $this->db->rollback();
1026 1067
                     return -1;
1027 1068
                 }
1028
-            }
1029
-            else
1069
+            } else
1030 1070
 			{
1031 1071
                 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1032 1072
                 {
1033 1073
                     // Doublon
1034 1074
                     $this->error = $langs->trans("ErrorDuplicateField");
1035 1075
                     $result = -1;
1036
-                }
1037
-                else
1076
+                } else
1038 1077
                 {
1039 1078
                     $this->error = $this->db->lasterror();
1040 1079
                     $result = -2;
@@ -1042,8 +1081,7 @@  discard block
 block discarded – undo
1042 1081
                 $this->db->rollback();
1043 1082
                 return $result;
1044 1083
             }
1045
-        }
1046
-        else
1084
+        } else
1047 1085
        {
1048 1086
             $this->db->rollback();
1049 1087
             dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
@@ -1072,7 +1110,9 @@  discard block
 block discarded – undo
1072 1110
         global $langs;
1073 1111
         global $conf;
1074 1112
 
1075
-        if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1113
+        if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
1114
+        	return -1;
1115
+        }
1076 1116
 
1077 1117
         $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1078 1118
         $sql .= ', s.status';
@@ -1107,17 +1147,39 @@  discard block
 block discarded – undo
1107 1147
         $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1108 1148
 		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1109 1149
 		$sql .= ' WHERE s.entity IN ('.getEntity($this->element, 1).')';
1110
-        if ($rowid)   $sql .= ' AND s.rowid = '.$rowid;
1111
-        if ($ref)     $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1112
-        if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1113
-        if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1114
-        if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1115
-        if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1116
-        if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1117
-        if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1118
-        if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1119
-        if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1120
-        if ($email)   $sql .= " AND email = '".$this->db->escape($email)."'";
1150
+        if ($rowid) {
1151
+        	$sql .= ' AND s.rowid = '.$rowid;
1152
+        }
1153
+        if ($ref) {
1154
+        	$sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1155
+        }
1156
+        if ($ref_ext) {
1157
+        	$sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1158
+        }
1159
+        if ($ref_int) {
1160
+        	$sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1161
+        }
1162
+        if ($idprof1) {
1163
+        	$sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1164
+        }
1165
+        if ($idprof2) {
1166
+        	$sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1167
+        }
1168
+        if ($idprof3) {
1169
+        	$sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1170
+        }
1171
+        if ($idprof4) {
1172
+        	$sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1173
+        }
1174
+        if ($idprof5) {
1175
+        	$sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1176
+        }
1177
+        if ($idprof6) {
1178
+        	$sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1179
+        }
1180
+        if ($email) {
1181
+        	$sql .= " AND email = '".$this->db->escape($email)."'";
1182
+        }
1121 1183
 
1122 1184
         $resql=$this->db->query($sql);
1123 1185
         if ($resql)
@@ -1128,10 +1190,11 @@  discard block
 block discarded – undo
1128 1190
                 $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1129 1191
                 dol_syslog($this->error, LOG_ERR);
1130 1192
                 $result = -2;
1131
-            }
1132
-            elseif ($num)   // $num = 1
1193
+            } elseif ($num) {
1194
+            	// $num = 1
1133 1195
             {
1134 1196
                 $obj = $this->db->fetch_object($resql);
1197
+            }
1135 1198
 
1136 1199
                 $this->id           = $obj->rowid;
1137 1200
                 $this->entity       = $obj->entity;
@@ -1256,22 +1319,22 @@  discard block
 block discarded – undo
1256 1319
 
1257 1320
                 // Retreive all extrafield for thirdparty
1258 1321
                	$this->fetch_optionals();
1259
-            }
1260
-            else
1322
+            } else
1261 1323
 			{
1262 1324
                 $result = 0;
1263 1325
             }
1264 1326
 
1265 1327
             $this->db->free($resql);
1266
-        }
1267
-        else
1328
+        } else
1268 1329
 		{
1269 1330
             $this->error=$this->db->lasterror();
1270 1331
             $result = -3;
1271 1332
         }
1272 1333
 
1273 1334
         // Use first price level if level not defined for third party
1274
-        if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1335
+        if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) {
1336
+        	$this->price_level=1;
1337
+        }
1275 1338
 
1276 1339
         return $result;
1277 1340
     }
@@ -1306,10 +1369,11 @@  discard block
 block discarded – undo
1306 1369
     	$sql.= " WHERE entity IN (".getEntity('category').")";
1307 1370
     	if (! empty($type))
1308 1371
     	{
1309
-    		if ($type == 1 || $type == 2)
1310
-    			$sql.= " AND client = ".$type;
1311
-    		elseif ($type == 3)
1312
-    			$sql.= " AND fournisseur = 1";
1372
+    		if ($type == 1 || $type == 2) {
1373
+    		    			$sql.= " AND client = ".$type;
1374
+    		} elseif ($type == 3) {
1375
+    		    			$sql.= " AND fournisseur = 1";
1376
+    		}
1313 1377
     	}
1314 1378
     	if (! empty($name))
1315 1379
     	{
@@ -1318,27 +1382,27 @@  discard block
 block discarded – undo
1318 1382
     			if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
1319 1383
     			{
1320 1384
     				$name = str_replace('*', '%', $name);
1321
-    			}
1322
-    			else
1385
+    			} else
1323 1386
     			{
1324 1387
     				$name = '%'.$name.'%';
1325 1388
     			}
1326 1389
     		}
1327 1390
     		$sql.= " AND ";
1328
-    		if (is_array($filters) && ! empty($filters))
1329
-    			$sql.= "(";
1391
+    		if (is_array($filters) && ! empty($filters)) {
1392
+    		    			$sql.= "(";
1393
+    		}
1330 1394
     		if ($similar)
1331 1395
     		{
1332 1396
     			// For test similitude (string inside name into database, or name into database inside string)
1333 1397
     			// Do not use this. Not compatible with other database.
1334 1398
     			$sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
1335
-    		}
1336
-    		else
1399
+    		} else
1337 1400
     		{
1338
-    			if (! $case)
1339
-    				$sql.= "nom LIKE '".$this->db->escape($name)."'";
1340
-    			else
1341
-    				$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
1401
+    			if (! $case) {
1402
+    			    				$sql.= "nom LIKE '".$this->db->escape($name)."'";
1403
+    			} else {
1404
+    			    				$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
1405
+    			}
1342 1406
     		}
1343 1407
     	}
1344 1408
     	if (is_array($filters) && ! empty($filters))
@@ -1350,19 +1414,20 @@  discard block
 block discarded – undo
1350 1414
     				if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
1351 1415
     				{
1352 1416
     					$value = str_replace('*', '%', $value);
1353
-    				}
1354
-    				else
1417
+    				} else
1355 1418
     				{
1356 1419
     					$value = '%'.$value.'%';
1357 1420
     				}
1358 1421
     			}
1359
-    			if (! $case)
1360
-    				$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1361
-    			else
1362
-    				$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1422
+    			if (! $case) {
1423
+    			    				$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
1424
+    			} else {
1425
+    			    				$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
1426
+    			}
1427
+    		}
1428
+    		if (! empty($name)) {
1429
+    		    			$sql.= ")";
1363 1430
     		}
1364
-    		if (! empty($name))
1365
-    			$sql.= ")";
1366 1431
     	}
1367 1432
 
1368 1433
     	$res  = $this->db->query($sql);
@@ -1376,8 +1441,7 @@  discard block
 block discarded – undo
1376 1441
     		}
1377 1442
 
1378 1443
     		return $thirdparties;
1379
-    	}
1380
-    	else
1444
+    	} else
1381 1445
     	{
1382 1446
     		$this->error=$this->db->lasterror();
1383 1447
     		return -1;
@@ -1396,7 +1460,9 @@  discard block
 block discarded – undo
1396 1460
     {
1397 1461
         global $langs, $conf, $user;
1398 1462
 
1399
-        if (empty($fuser)) $fuser=$user;
1463
+        if (empty($fuser)) {
1464
+        	$fuser=$user;
1465
+        }
1400 1466
 
1401 1467
         require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1402 1468
 
@@ -1416,7 +1482,9 @@  discard block
 block discarded – undo
1416 1482
             {
1417 1483
                 // Call trigger
1418 1484
                 $result=$this->call_trigger('COMPANY_DELETE',$fuser);
1419
-                if ($result < 0) $error++;
1485
+                if ($result < 0) {
1486
+                	$error++;
1487
+                }
1420 1488
                 // End call triggers
1421 1489
             }
1422 1490
 
@@ -1461,9 +1529,11 @@  discard block
 block discarded – undo
1461 1529
 			}
1462 1530
 
1463 1531
             // Removed extrafields
1464
-            if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1532
+            if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) {
1533
+            	// For avoid conflicts if trigger used
1465 1534
             {
1466 1535
             	$result=$this->deleteExtraFields();
1536
+            }
1467 1537
             	if ($result < 0)
1468 1538
             	{
1469 1539
             		$error++;
@@ -1498,15 +1568,15 @@  discard block
 block discarded – undo
1498 1568
                 }
1499 1569
 
1500 1570
                 return 1;
1501
-            }
1502
-            else
1571
+            } else
1503 1572
 			{
1504 1573
 				dol_syslog($this->error, LOG_ERR);
1505 1574
                 $this->db->rollback();
1506 1575
                 return -1;
1507 1576
             }
1508
-        }
1509
-		else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1577
+        } else {
1578
+			dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1579
+		}
1510 1580
         return 0;
1511 1581
     }
1512 1582
 
@@ -1520,7 +1590,10 @@  discard block
 block discarded – undo
1520 1590
         if ($this->id)
1521 1591
         {
1522 1592
             $newclient=1;
1523
-            if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1593
+            if ($this->client == 2 || $this->client == 3) {
1594
+            	$newclient=3;
1595
+            }
1596
+            //If prospect, we keep prospect tag
1524 1597
             $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1525 1598
             $sql.= " SET client = ".$newclient;
1526 1599
             $sql.= " WHERE rowid = " . $this->id;
@@ -1530,8 +1603,9 @@  discard block
 block discarded – undo
1530 1603
             {
1531 1604
                 $this->client = $newclient;
1532 1605
                 return 1;
1606
+            } else {
1607
+            	return -1;
1533 1608
             }
1534
-            else return -1;
1535 1609
         }
1536 1610
         return 0;
1537 1611
     }
@@ -1641,14 +1715,14 @@  discard block
 block discarded – undo
1641 1715
             if ($result > 0)
1642 1716
             {
1643 1717
                 return $result;
1644
-            }
1645
-            else
1718
+            } else
1646 1719
             {
1647 1720
                 $this->error=$discount->error;
1648 1721
                 return -3;
1649 1722
             }
1723
+        } else {
1724
+        	return 0;
1650 1725
         }
1651
-        else return 0;
1652 1726
     }
1653 1727
 
1654 1728
     /**
@@ -1668,8 +1742,7 @@  discard block
 block discarded – undo
1668 1742
         if ($result >= 0)
1669 1743
         {
1670 1744
             return $result;
1671
-        }
1672
-        else
1745
+        } else
1673 1746
         {
1674 1747
             $this->error=$discountstatic->error;
1675 1748
             return -1;
@@ -1696,9 +1769,9 @@  discard block
 block discarded – undo
1696 1769
         	$sql.= " WHERE ((ug.fk_user = sc.fk_user";
1697 1770
         	$sql.= " AND ug.entity = ".$conf->entity.")";
1698 1771
         	$sql.= " OR u.admin = 1)";
1772
+        } else {
1773
+                	$sql.= " WHERE entity in (0, ".$conf->entity.")";
1699 1774
         }
1700
-        else
1701
-        	$sql.= " WHERE entity in (0, ".$conf->entity.")";
1702 1775
 
1703 1776
         $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1704 1777
 
@@ -1721,8 +1794,7 @@  discard block
 block discarded – undo
1721 1794
                 $i++;
1722 1795
             }
1723 1796
             return $reparray;
1724
-        }
1725
-        else {
1797
+        } else {
1726 1798
             dol_print_error($this->db);
1727 1799
             return -1;
1728 1800
         }
@@ -1828,7 +1900,10 @@  discard block
 block discarded – undo
1828 1900
     {
1829 1901
         global $conf, $langs, $hookmanager;
1830 1902
 
1831
-        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
1903
+        if (! empty($conf->dol_no_mouse_hover)) {
1904
+        	$notooltip=1;
1905
+        }
1906
+        // Force disable tooltips
1832 1907
 
1833 1908
         $name=$this->name?$this->name:$this->nom;
1834 1909
 
@@ -1838,23 +1913,28 @@  discard block
 block discarded – undo
1838 1913
     			&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1839 1914
     			|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
1840 1915
     			)
1841
-    		)
1842
-    		$code = $this->code_client . ' - ';
1916
+    		) {
1917
+    		    		$code = $this->code_client . ' - ';
1918
+    		}
1843 1919
 
1844 1920
     		if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
1845 1921
     			&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
1846 1922
     			|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
1847 1923
     			)
1848
-    		)
1849
-    		$code .= $this->code_fournisseur . ' - ';
1924
+    		) {
1925
+    		    		$code .= $this->code_fournisseur . ' - ';
1926
+    		}
1850 1927
 
1851
-    		if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
1852
-    			$name =$code.' '.$name;
1853
-    		else
1854
-    			$name =$code;
1928
+    		if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
1929
+    		    			$name =$code.' '.$name;
1930
+    		} else {
1931
+    		    			$name =$code;
1932
+    		}
1855 1933
     	}
1856 1934
 
1857
-    	if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
1935
+    	if (!empty($this->name_alias)) {
1936
+    		$name .= ' ('.$this->name_alias.')';
1937
+    	}
1858 1938
 
1859 1939
         $result=''; $label='';
1860 1940
         $linkstart=''; $linkend='';
@@ -1872,33 +1952,27 @@  discard block
 block discarded – undo
1872 1952
         {
1873 1953
            $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
1874 1954
            $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1875
-        }
1876
-        else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1955
+        } else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1877 1956
         {
1878 1957
             $label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
1879 1958
             $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
1880
-        }
1881
-        else if ($option == 'supplier')
1959
+        } else if ($option == 'supplier')
1882 1960
         {
1883 1961
             $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
1884 1962
             $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
1885
-        }
1886
-        else if ($option == 'agenda')
1963
+        } else if ($option == 'agenda')
1887 1964
         {
1888 1965
             $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
1889 1966
             $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
1890
-        }
1891
-        else if ($option == 'project')
1967
+        } else if ($option == 'project')
1892 1968
         {
1893 1969
             $label.= '<u>' . $langs->trans("ShowProject") . '</u>';
1894 1970
             $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
1895
-        }
1896
-        else if ($option == 'margin')
1971
+        } else if ($option == 'margin')
1897 1972
         {
1898 1973
             $label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
1899 1974
             $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
1900
-        }
1901
-        else if ($option == 'contact')
1975
+        } else if ($option == 'contact')
1902 1976
         {
1903 1977
         	$label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
1904 1978
         	$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
@@ -1914,21 +1988,29 @@  discard block
 block discarded – undo
1914 1988
         if (! empty($this->name))
1915 1989
         {
1916 1990
             $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
1917
-            if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
1991
+            if (! empty($this->name_alias)) {
1992
+            	$label.=' ('.$this->name_alias.')';
1993
+            }
1918 1994
             $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
1919 1995
         }
1920
-        if (! empty($this->country_code))
1921
-            $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
1922
-        if (! empty($this->tva_intra))
1923
-            $label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra;
1924
-            if (! empty($this->code_client) && $this->client)
1925
-            $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
1926
-        if (! empty($this->code_fournisseur) && $this->fournisseur)
1927
-            $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
1928
-        if (! empty($conf->accounting->enabled) && $this->client)
1929
-            $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
1930
-        if (! empty($conf->accounting->enabled) && $this->fournisseur)
1931
-            $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
1996
+        if (! empty($this->country_code)) {
1997
+                    $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
1998
+        }
1999
+        if (! empty($this->tva_intra)) {
2000
+                    $label.= '<br><b>' . $langs->trans('VATNumber') . ':</b> '. $this->tva_intra;
2001
+        }
2002
+            if (! empty($this->code_client) && $this->client) {
2003
+                        $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
2004
+            }
2005
+        if (! empty($this->code_fournisseur) && $this->fournisseur) {
2006
+                    $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
2007
+        }
2008
+        if (! empty($conf->accounting->enabled) && $this->client) {
2009
+                    $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
2010
+        }
2011
+        if (! empty($conf->accounting->enabled) && $this->fournisseur) {
2012
+                    $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
2013
+        }
1932 2014
 
1933 2015
         $label.= '</div>';
1934 2016
 
@@ -1936,8 +2018,12 @@  discard block
 block discarded – undo
1936 2018
         $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
1937 2019
         // Add param to save lastsearch_values or not
1938 2020
         $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1939
-        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1940
-        if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
2021
+        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
2022
+        	$add_save_lastsearch_values=1;
2023
+        }
2024
+        if ($add_save_lastsearch_values) {
2025
+        	$linkstart.='&save_lastsearch_values=1';
2026
+        }
1941 2027
         $linkstart.='"';
1942 2028
 
1943 2029
         $linkclose='';
@@ -1959,7 +2045,9 @@  discard block
 block discarded – undo
1959 2045
     		$hookmanager->initHooks(array('societedao'));
1960 2046
     		$parameters=array('id'=>$this->id);
1961 2047
     		$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1962
-    		if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2048
+    		if ($reshook > 0) {
2049
+    			$linkclose = $hookmanager->resPrint;
2050
+    		}
1963 2051
         }
1964 2052
         $linkstart.=$linkclose.'>';
1965 2053
         $linkend='</a>';
@@ -1971,9 +2059,15 @@  discard block
 block discarded – undo
1971 2059
             $linkend='';
1972 2060
         }
1973 2061
 
1974
-        if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend);
1975
-        if ($withpicto && $withpicto != 2) $result.=' ';
1976
-        if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
2062
+        if ($withpicto) {
2063
+        	$result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend);
2064
+        }
2065
+        if ($withpicto && $withpicto != 2) {
2066
+        	$result.=' ';
2067
+        }
2068
+        if ($withpicto != 2) {
2069
+        	$result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
2070
+        }
1977 2071
 
1978 2072
         return $result;
1979 2073
     }
@@ -2003,33 +2097,57 @@  discard block
 block discarded – undo
2003 2097
 
2004 2098
         if ($mode == 0)
2005 2099
         {
2006
-            if ($statut==0) return $langs->trans("ActivityCeased");
2007
-            if ($statut==1) return $langs->trans("InActivity");
2100
+            if ($statut==0) {
2101
+            	return $langs->trans("ActivityCeased");
2102
+            }
2103
+            if ($statut==1) {
2104
+            	return $langs->trans("InActivity");
2105
+            }
2008 2106
         }
2009 2107
         if ($mode == 1)
2010 2108
         {
2011
-            if ($statut==0) return $langs->trans("ActivityCeased");
2012
-            if ($statut==1) return $langs->trans("InActivity");
2109
+            if ($statut==0) {
2110
+            	return $langs->trans("ActivityCeased");
2111
+            }
2112
+            if ($statut==1) {
2113
+            	return $langs->trans("InActivity");
2114
+            }
2013 2115
         }
2014 2116
         if ($mode == 2)
2015 2117
         {
2016
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2017
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2118
+            if ($statut==0) {
2119
+            	return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2120
+            }
2121
+            if ($statut==1) {
2122
+            	return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2123
+            }
2018 2124
         }
2019 2125
         if ($mode == 3)
2020 2126
         {
2021
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2022
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2127
+            if ($statut==0) {
2128
+            	return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2129
+            }
2130
+            if ($statut==1) {
2131
+            	return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2132
+            }
2023 2133
         }
2024 2134
         if ($mode == 4)
2025 2135
         {
2026
-            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2027
-            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2136
+            if ($statut==0) {
2137
+            	return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2138
+            }
2139
+            if ($statut==1) {
2140
+            	return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2141
+            }
2028 2142
         }
2029 2143
         if ($mode == 5)
2030 2144
         {
2031
-            if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2032
-            if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2145
+            if ($statut==0) {
2146
+            	return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2147
+            }
2148
+            if ($statut==1) {
2149
+            	return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2150
+            }
2033 2151
         }
2034 2152
     }
2035 2153
 
@@ -2046,7 +2164,9 @@  discard block
 block discarded – undo
2046 2164
         $contact_emails = $this->contact_property_array('email',1);
2047 2165
         if ($this->email && $addthirdparty)
2048 2166
         {
2049
-            if (empty($this->name)) $this->name=$this->nom;
2167
+            if (empty($this->name)) {
2168
+            	$this->name=$this->nom;
2169
+            }
2050 2170
             $contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->email."&gt;";
2051 2171
         }
2052 2172
         //var_dump($contact_emails)
@@ -2064,9 +2184,11 @@  discard block
 block discarded – undo
2064 2184
 
2065 2185
         $contact_phone = $this->contact_property_array('mobile');
2066 2186
 
2067
-        if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2187
+        if (! empty($this->phone)) {
2188
+        	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2068 2189
         {
2069 2190
             if (empty($this->name)) $this->name=$this->nom;
2191
+        }
2070 2192
             // TODO: Tester si tel non deja present dans tableau contact
2071 2193
             $contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." &lt;".$this->phone."&gt;";
2072 2194
         }
@@ -2106,24 +2228,30 @@  discard block
 block discarded – undo
2106 2228
                 while ($i < $nump)
2107 2229
                 {
2108 2230
                     $obj = $this->db->fetch_object($resql);
2109
-                    if ($mode == 'email') $property=$obj->email;
2110
-                    else if ($mode == 'mobile') $property=$obj->phone_mobile;
2111
-                    else $property=$obj->$mode;
2231
+                    if ($mode == 'email') {
2232
+                    	$property=$obj->email;
2233
+                    } else if ($mode == 'mobile') {
2234
+                    	$property=$obj->phone_mobile;
2235
+                    } else {
2236
+                    	$property=$obj->$mode;
2237
+                    }
2112 2238
 
2113 2239
 					// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2114 2240
                     if ($obj->statut == 1 || empty($hidedisabled))
2115 2241
                     {
2116 2242
                     	if (empty($property))
2117 2243
                     	{
2118
-                    		if ($mode == 'email') $property=$langs->trans("NoEMail");
2119
-                    		else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone");
2244
+                    		if ($mode == 'email') {
2245
+                    			$property=$langs->trans("NoEMail");
2246
+                    		} else if ($mode == 'mobile') {
2247
+                    			$property=$langs->trans("NoMobilePhone");
2248
+                    		}
2120 2249
                     	}
2121 2250
 
2122 2251
 	                    if (!empty($obj->poste))
2123 2252
     	                {
2124 2253
 							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2125
-						}
2126
-						else
2254
+						} else
2127 2255
 						{
2128 2256
 							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2129 2257
 						}
@@ -2131,8 +2259,7 @@  discard block
 block discarded – undo
2131 2259
                     $i++;
2132 2260
                 }
2133 2261
             }
2134
-        }
2135
-        else
2262
+        } else
2136 2263
         {
2137 2264
             dol_print_error($this->db);
2138 2265
         }
@@ -2164,8 +2291,7 @@  discard block
 block discarded – undo
2164 2291
                     $i++;
2165 2292
                 }
2166 2293
             }
2167
-        }
2168
-        else
2294
+        } else
2169 2295
         {
2170 2296
             dol_print_error($this->db);
2171 2297
         }
@@ -2199,8 +2325,7 @@  discard block
 block discarded – undo
2199 2325
                     $i++;
2200 2326
                 }
2201 2327
             }
2202
-        }
2203
-        else
2328
+        } else
2204 2329
         {
2205 2330
             dol_print_error($this->db);
2206 2331
         }
@@ -2218,7 +2343,9 @@  discard block
 block discarded – undo
2218 2343
     {
2219 2344
         $contact_property='';
2220 2345
 
2221
-        if (empty($rowid)) return '';
2346
+        if (empty($rowid)) {
2347
+        	return '';
2348
+        }
2222 2349
 
2223 2350
         $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2224 2351
         $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
@@ -2233,12 +2360,14 @@  discard block
 block discarded – undo
2233 2360
             {
2234 2361
                 $obj = $this->db->fetch_object($resql);
2235 2362
 
2236
-                if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
2237
-                else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2363
+                if ($mode == 'email') {
2364
+                	$contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
2365
+                } else if ($mode == 'mobile') {
2366
+                	$contact_property = $obj->phone_mobile;
2367
+                }
2238 2368
             }
2239 2369
             return $contact_property;
2240
-        }
2241
-        else
2370
+        } else
2242 2371
         {
2243 2372
             dol_print_error($this->db);
2244 2373
         }
@@ -2262,8 +2391,7 @@  discard block
 block discarded – undo
2262 2391
         if ($mode == 'label')
2263 2392
         {
2264 2393
         	return $bac->getRibLabel(true);
2265
-        }
2266
-        elseif ($mode == 'rum')
2394
+        } elseif ($mode == 'rum')
2267 2395
         {
2268 2396
         	if (empty($bac->rum))
2269 2397
         	{
@@ -2325,7 +2453,9 @@  discard block
 block discarded – undo
2325 2453
             foreach ($dirsociete as $dirroot)
2326 2454
             {
2327 2455
                 $res=dol_include_once($dirroot.$module.'.php');
2328
-                if ($res) break;
2456
+                if ($res) {
2457
+                	break;
2458
+                }
2329 2459
             }
2330 2460
             $mod = new $module();
2331 2461
 
@@ -2355,7 +2485,9 @@  discard block
 block discarded – undo
2355 2485
             foreach ($dirsociete as $dirroot)
2356 2486
             {
2357 2487
                 $res=dol_include_once($dirroot.$module.'.php');
2358
-                if ($res) break;
2488
+                if ($res) {
2489
+                	break;
2490
+                }
2359 2491
             }
2360 2492
             $mod = new $module();
2361 2493
 
@@ -2382,18 +2514,26 @@  discard block
 block discarded – undo
2382 2514
             foreach ($dirsociete as $dirroot)
2383 2515
             {
2384 2516
                 $res=dol_include_once($dirroot.$module.'.php');
2385
-                if ($res) break;
2517
+                if ($res) {
2518
+                	break;
2519
+                }
2386 2520
             }
2387 2521
 
2388 2522
             $mod = new $module();
2389 2523
 
2390 2524
             dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2391
-            if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2392
-            if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2393
-            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2525
+            if ($mod->code_modifiable_null && ! $this->code_client) {
2526
+            	return 1;
2527
+            }
2528
+            if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
2529
+            	return 1;
2530
+            }
2531
+            if ($mod->code_modifiable) {
2532
+            	return 1;
2533
+            }
2534
+            // A mettre en dernier
2394 2535
             return 0;
2395
-        }
2396
-        else
2536
+        } else
2397 2537
         {
2398 2538
             return 0;
2399 2539
         }
@@ -2416,18 +2556,26 @@  discard block
 block discarded – undo
2416 2556
             foreach ($dirsociete as $dirroot)
2417 2557
             {
2418 2558
                 $res=dol_include_once($dirroot.$module.'.php');
2419
-                if ($res) break;
2559
+                if ($res) {
2560
+                	break;
2561
+                }
2420 2562
             }
2421 2563
 
2422 2564
             $mod = new $module();
2423 2565
 
2424 2566
             dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2425
-            if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2426
-            if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2427
-            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2567
+            if ($mod->code_modifiable_null && ! $this->code_fournisseur) {
2568
+            	return 1;
2569
+            }
2570
+            if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
2571
+            	return 1;
2572
+            }
2573
+            if ($mod->code_modifiable) {
2574
+            	return 1;
2575
+            }
2576
+            // A mettre en dernier
2428 2577
             return 0;
2429
-        }
2430
-        else
2578
+        } else
2431 2579
         {
2432 2580
             return 0;
2433 2581
         }
@@ -2454,7 +2602,9 @@  discard block
 block discarded – undo
2454 2602
             foreach ($dirsociete as $dirroot)
2455 2603
             {
2456 2604
                 $res=dol_include_once($dirroot.$module.'.php');
2457
-                if ($res) break;
2605
+                if ($res) {
2606
+                	break;
2607
+                }
2458 2608
             }
2459 2609
 
2460 2610
             $mod = new $module();
@@ -2462,8 +2612,7 @@  discard block
 block discarded – undo
2462 2612
            	dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2463 2613
            	$result = $mod->verif($this->db, $this->code_client, $this, 0);
2464 2614
             return $result;
2465
-        }
2466
-        else
2615
+        } else
2467 2616
 		{
2468 2617
             return 0;
2469 2618
         }
@@ -2489,7 +2638,9 @@  discard block
 block discarded – undo
2489 2638
             foreach ($dirsociete as $dirroot)
2490 2639
             {
2491 2640
                 $res=dol_include_once($dirroot.$module.'.php');
2492
-                if ($res) break;
2641
+                if ($res) {
2642
+                	break;
2643
+                }
2493 2644
             }
2494 2645
 
2495 2646
             $mod = new $module();
@@ -2497,8 +2648,7 @@  discard block
 block discarded – undo
2497 2648
             dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2498 2649
             $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2499 2650
             return $result;
2500
-        }
2501
-        else
2651
+        } else
2502 2652
 		{
2503 2653
             return 0;
2504 2654
         }
@@ -2539,21 +2689,25 @@  discard block
 block discarded – undo
2539 2689
             	// Defini code compta dans $mod->code
2540 2690
             	$result = $mod->get_code($this->db, $this, $type);
2541 2691
 
2542
-            	if ($type == 'customer') $this->code_compta = $mod->code;
2543
-            	else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2692
+            	if ($type == 'customer') {
2693
+            		$this->code_compta = $mod->code;
2694
+            	} else if ($type == 'supplier') {
2695
+            		$this->code_compta_fournisseur = $mod->code;
2696
+            	}
2544 2697
 
2545 2698
             	return $result;
2546
-            }
2547
-            else
2699
+            } else
2548 2700
             {
2549 2701
             	$this->error = 'ErrorAccountancyCodeNotDefined';
2550 2702
             	return -1;
2551 2703
             }
2552
-        }
2553
-        else
2704
+        } else
2554 2705
         {
2555
-            if ($type == 'customer') $this->code_compta = '';
2556
-            else if ($type == 'supplier') $this->code_compta_fournisseur = '';
2706
+            if ($type == 'customer') {
2707
+            	$this->code_compta = '';
2708
+            } else if ($type == 'supplier') {
2709
+            	$this->code_compta_fournisseur = '';
2710
+            }
2557 2711
 
2558 2712
             return 0;
2559 2713
         }
@@ -2578,13 +2732,13 @@  discard block
 block discarded – undo
2578 2732
             {
2579 2733
             	$this->parent = $id;
2580 2734
                 return 1;
2581
-            }
2582
-            else
2735
+            } else
2583 2736
 			{
2584 2737
                 return -1;
2585 2738
             }
2739
+        } else {
2740
+        	return -1;
2586 2741
         }
2587
-        else return -1;
2588 2742
     }
2589 2743
 
2590 2744
 	/**
@@ -2664,22 +2818,26 @@  discard block
 block discarded – undo
2664 2818
 
2665 2819
          //Verify duplicate entries
2666 2820
         $sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2667
-        if($socid) $sql .= " AND rowid <> ".$socid;
2821
+        if($socid) {
2822
+        	$sql .= " AND rowid <> ".$socid;
2823
+        }
2668 2824
         $resql = $this->db->query($sql);
2669 2825
         if ($resql)
2670 2826
         {
2671 2827
             $obj = $this->db->fetch_object($resql);
2672 2828
             $count = $obj->idprof;
2673
-        }
2674
-        else
2829
+        } else
2675 2830
         {
2676 2831
             $count = 0;
2677 2832
             print $this->db->error();
2678 2833
         }
2679 2834
         $this->db->free($resql);
2680 2835
 
2681
-		if ($count > 0) return true;
2682
-		else return false;
2836
+		if ($count > 0) {
2837
+			return true;
2838
+		} else {
2839
+			return false;
2840
+		}
2683 2841
     }
2684 2842
 
2685 2843
     /**
@@ -2696,7 +2854,9 @@  discard block
 block discarded – undo
2696 2854
 
2697 2855
         $ok=1;
2698 2856
 
2699
-        if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2857
+        if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
2858
+        	return 1;
2859
+        }
2700 2860
 
2701 2861
         // Verifie SIREN si pays FR
2702 2862
         if ($idprof == 1 && $soc->country_code == 'FR')
@@ -2704,7 +2864,9 @@  discard block
 block discarded – undo
2704 2864
             $chaine=trim($this->idprof1);
2705 2865
             $chaine=preg_replace('/(\s)/','',$chaine);
2706 2866
 
2707
-            if (dol_strlen($chaine) != 9) return -1;
2867
+            if (dol_strlen($chaine) != 9) {
2868
+            	return -1;
2869
+            }
2708 2870
 
2709 2871
             $sum = 0;
2710 2872
 
@@ -2724,7 +2886,9 @@  discard block
 block discarded – undo
2724 2886
                 $sum = $sum + $ps;
2725 2887
             }
2726 2888
 
2727
-            if (substr($sum, -1) != 0) return -1;
2889
+            if (substr($sum, -1) != 0) {
2890
+            	return -1;
2891
+            }
2728 2892
         }
2729 2893
 
2730 2894
         // Verifie SIRET si pays FR
@@ -2733,7 +2897,9 @@  discard block
 block discarded – undo
2733 2897
             $chaine=trim($this->idprof2);
2734 2898
             $chaine=preg_replace('/(\s)/','',$chaine);
2735 2899
 
2736
-            if (dol_strlen($chaine) != 14) return -1;
2900
+            if (dol_strlen($chaine) != 14) {
2901
+            	return -1;
2902
+            }
2737 2903
         }
2738 2904
 
2739 2905
         //Verify CIF/NIF/NIE if pays ES
@@ -2744,53 +2910,61 @@  discard block
 block discarded – undo
2744 2910
             $string=preg_replace('/(\s)/','',$string);
2745 2911
             $string = strtoupper($string);
2746 2912
 
2747
-            for ($i = 0; $i < 9; $i ++)
2748
-            $num[$i] = substr($string, $i, 1);
2913
+            for ($i = 0; $i < 9; $i ++) {
2914
+                        $num[$i] = substr($string, $i, 1);
2915
+            }
2749 2916
 
2750 2917
             //Check format
2751
-            if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
2752
-            return 0;
2918
+            if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string)) {
2919
+                        return 0;
2920
+            }
2753 2921
 
2754 2922
             //Check NIF
2755
-            if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
2756
-            if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
2923
+            if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
2924
+                        if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
2757 2925
             return 1;
2758
-            else
2759
-            return -1;
2926
+            } else {
2927
+                        return -1;
2928
+            }
2760 2929
 
2761 2930
             //algorithm checking type code CIF
2762 2931
             $sum = $num[2] + $num[4] + $num[6];
2763
-            for ($i = 1; $i < 8; $i += 2)
2764
-            $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
2932
+            for ($i = 1; $i < 8; $i += 2) {
2933
+                        $sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
2934
+            }
2765 2935
             $n = 10 - substr($sum, strlen($sum) - 1, 1);
2766 2936
 
2767 2937
             //Chek special NIF
2768
-            if (preg_match('/^[KLM]{1}/', $string))
2769
-            if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
2938
+            if (preg_match('/^[KLM]{1}/', $string)) {
2939
+                        if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
2770 2940
             return 1;
2771
-            else
2772
-            return -1;
2941
+            } else {
2942
+                        return -1;
2943
+            }
2773 2944
 
2774 2945
             //Check CIF
2775
-            if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
2776
-            if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
2946
+            if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
2947
+                        if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
2777 2948
             return 2;
2778
-            else
2779
-            return -2;
2949
+            } else {
2950
+                        return -2;
2951
+            }
2780 2952
 
2781 2953
             //Check NIE T
2782
-            if (preg_match('/^[T]{1}/', $string))
2783
-            if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
2954
+            if (preg_match('/^[T]{1}/', $string)) {
2955
+                        if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
2784 2956
             return 3;
2785
-            else
2786
-            return -3;
2957
+            } else {
2958
+                        return -3;
2959
+            }
2787 2960
 
2788 2961
             //Check NIE XYZ
2789
-            if (preg_match('/^[XYZ]{1}/', $string))
2790
-            if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
2962
+            if (preg_match('/^[XYZ]{1}/', $string)) {
2963
+                        if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
2791 2964
             return 3;
2792
-            else
2793
-            return -3;
2965
+            } else {
2966
+                        return -3;
2967
+            }
2794 2968
 
2795 2969
             //Can not be verified
2796 2970
             return -4;
@@ -2819,17 +2993,27 @@  discard block
 block discarded – undo
2819 2993
         $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2820 2994
         if (empty($reshook))
2821 2995
         {
2822
-            if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
2996
+            if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
2997
+            	return '';
2998
+            }
2823 2999
 
2824 3000
             // TODO Move links to validate professional ID into a dictionary table "country" + "link"
2825
-            if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1;    // See also http://avis-situation-sirene.insee.fr/
3001
+            if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3002
+            	$url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1;
3003
+            }
3004
+            // See also http://avis-situation-sirene.insee.fr/
2826 3005
             //if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/';     // Link no more valid
2827
-            if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
2828
-            if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3006
+            if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3007
+            	$url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
3008
+            }
3009
+            if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3010
+            	$url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3011
+            }
2829 3012
 
2830
-            if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
2831
-        }
2832
-        else
3013
+            if ($url) {
3014
+            	return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
3015
+            }
3016
+        } else
2833 3017
         {
2834 3018
             return $hookmanager->resPrint;
2835 3019
         }
@@ -2850,8 +3034,7 @@  discard block
 block discarded – undo
2850 3034
         {
2851 3035
             $obj = $this->db->fetch_object($resql);
2852 3036
             $count = $obj->numproj;
2853
-        }
2854
-        else
3037
+        } else
2855 3038
         {
2856 3039
             $count = 0;
2857 3040
             print $this->db->error();
@@ -2902,8 +3085,7 @@  discard block
 block discarded – undo
2902 3085
 
2903 3086
             $this->db->free($result);
2904 3087
 
2905
-        }
2906
-        else
3088
+        } else
2907 3089
 		{
2908 3090
             dol_print_error($this->db);
2909 3091
         }
@@ -2920,9 +3102,13 @@  discard block
 block discarded – undo
2920 3102
 
2921 3103
         // Define if third party is treated as company (or not) when nature is unknown
2922 3104
         $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
2923
-        if (! empty($this->tva_intra)) $isacompany=1;
2924
-        else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
2925
-        else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) $isacompany=1;
3105
+        if (! empty($this->tva_intra)) {
3106
+        	$isacompany=1;
3107
+        } else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) {
3108
+        	$isacompany=0;
3109
+        } else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE','TE_GROUP'))) {
3110
+        	$isacompany=1;
3111
+        }
2926 3112
 
2927 3113
         return $isacompany;
2928 3114
     }
@@ -2947,8 +3133,7 @@  discard block
 block discarded – undo
2947 3133
                 $this->SupplierCategories[$obj->rowid] = $obj->label;
2948 3134
             }
2949 3135
             return 0;
2950
-        }
2951
-        else
3136
+        } else
2952 3137
         {
2953 3138
             return -1;
2954 3139
         }
@@ -2967,9 +3152,10 @@  discard block
 block discarded – undo
2967 3152
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
2968 3153
             $sql.= " VALUES (".$categorie_id.", ".$this->id.")";
2969 3154
 
2970
-            if ($resql=$this->db->query($sql)) return 0;
2971
-        }
2972
-        else
3155
+            if ($resql=$this->db->query($sql)) {
3156
+            	return 0;
3157
+            }
3158
+        } else
2973 3159
         {
2974 3160
             return 0;
2975 3161
         }
@@ -2989,7 +3175,9 @@  discard block
 block discarded – undo
2989 3175
         global $user,$langs;
2990 3176
 
2991 3177
         $name = $socname?$socname:$member->societe;
2992
-        if (empty($name)) $name=$member->getFullName($langs);
3178
+        if (empty($name)) {
3179
+        	$name=$member->getFullName($langs);
3180
+        }
2993 3181
 
2994 3182
         // Positionne parametres
2995 3183
         $this->nom=$name;				// TODO deprecated
@@ -3023,16 +3211,14 @@  discard block
 block discarded – undo
3023 3211
             {
3024 3212
                 $this->db->commit();
3025 3213
                 return $this->id;
3026
-            }
3027
-            else
3214
+            } else
3028 3215
             {
3029 3216
                 $this->error=$this->db->error();
3030 3217
 
3031 3218
                 $this->db->rollback();
3032 3219
                 return -1;
3033 3220
             }
3034
-        }
3035
-        else
3221
+        } else
3036 3222
         {
3037 3223
             // $this->error deja positionne
3038 3224
             dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
@@ -3078,12 +3264,13 @@  discard block
 block discarded – undo
3078 3264
     	{
3079 3265
     		$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3080 3266
     		$country_id=$tmp[0];
3081
-    		if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3267
+    		if (! empty($tmp[1])) {
3268
+    			// If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3082 3269
     		{
3083 3270
     			$country_code=$tmp[1];
3084
-    			$country_label=$tmp[2];
3085 3271
     		}
3086
-    		else                    // For backward compatibility
3272
+    			$country_label=$tmp[2];
3273
+    		} else                    // For backward compatibility
3087 3274
     		{
3088 3275
     			dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3089 3276
     			include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
@@ -3094,7 +3281,9 @@  discard block
 block discarded – undo
3094 3281
     	$this->country_id=$country_id;
3095 3282
     	$this->country_code=$country_code;
3096 3283
     	$this->country=$country_label;
3097
-    	if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3284
+    	if (is_object($langs)) {
3285
+    		$this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3286
+    	}
3098 3287
 
3099 3288
     	$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3100 3289
     	$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
@@ -3186,17 +3375,22 @@  discard block
 block discarded – undo
3186 3375
     	$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3187 3376
     	$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3188 3377
     	$sql .= " AND t.active = 1";
3189
-    	if (empty($localTaxNum))   $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3190
-    	elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3191
-    	elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3378
+    	if (empty($localTaxNum)) {
3379
+    		$sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3380
+    	} elseif ($localTaxNum == 1) {
3381
+    		$sql .= " AND t.localtax1_type <> '0'";
3382
+    	} elseif ($localTaxNum == 2) {
3383
+    		$sql .= " AND t.localtax2_type <> '0'";
3384
+    	}
3192 3385
 
3193 3386
     	dol_syslog("useLocalTax", LOG_DEBUG);
3194 3387
     	$resql=$this->db->query($sql);
3195 3388
     	if ($resql)
3196 3389
     	{
3197 3390
    			return ($this->db->num_rows($resql) > 0);
3391
+    	} else {
3392
+    		return false;
3198 3393
     	}
3199
-    	else return false;
3200 3394
     }
3201 3395
 
3202 3396
     /**
@@ -3216,8 +3410,9 @@  discard block
 block discarded – undo
3216 3410
         if ($resql)
3217 3411
         {
3218 3412
             return ($this->db->num_rows($resql) > 0);
3413
+        } else {
3414
+        	return false;
3219 3415
         }
3220
-        else return false;
3221 3416
     }
3222 3417
 
3223 3418
     /**
@@ -3238,8 +3433,7 @@  discard block
 block discarded – undo
3238 3433
 		{
3239 3434
 			$obj=$this->db->fetch_object($resql);
3240 3435
    			return (($obj->nb > 0)?true:false);
3241
-		}
3242
-		else
3436
+		} else
3243 3437
 		{
3244 3438
 			$this->error=$this->db->lasterror();
3245 3439
 			return false;
@@ -3315,36 +3509,51 @@  discard block
 block discarded – undo
3315 3509
 
3316 3510
 		if ($mode == 2)
3317 3511
 		{
3318
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3319
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3320
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3321
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3322
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3323
-			else
3512
+			if ($statut == '-1' || $statut == 'ST_NO') {
3513
+				return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3514
+			} elseif ($statut ==  '0' || $statut == 'ST_NEVER') {
3515
+				return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3516
+			} elseif ($statut ==  '1' || $statut == 'ST_TODO') {
3517
+				return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3518
+			} elseif ($statut ==  '2' || $statut == 'ST_PEND') {
3519
+				return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3520
+			} elseif ($statut ==  '3' || $statut == 'ST_DONE') {
3521
+				return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3522
+			} else
3324 3523
 			{
3325 3524
 				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3326 3525
 			}
3327 3526
 		}
3328 3527
 		if ($mode == 3)
3329 3528
 		{
3330
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1);
3331
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3332
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1);
3333
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2);
3334
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3);
3335
-			else
3529
+			if ($statut == '-1' || $statut == 'ST_NO') {
3530
+				return img_action($langs->trans("StatusProspect-1"),-1);
3531
+			} elseif ($statut ==  '0' || $statut == 'ST_NEVER') {
3532
+				return img_action($langs->trans("StatusProspect0"), 0);
3533
+			} elseif ($statut ==  '1' || $statut == 'ST_TODO') {
3534
+				return img_action($langs->trans("StatusProspect1"), 1);
3535
+			} elseif ($statut ==  '2' || $statut == 'ST_PEND') {
3536
+				return img_action($langs->trans("StatusProspect2"), 2);
3537
+			} elseif ($statut ==  '3' || $statut == 'ST_DONE') {
3538
+				return img_action($langs->trans("StatusProspect3"), 3);
3539
+			} else
3336 3540
 			{
3337 3541
 				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
3338 3542
 			}
3339 3543
 		}
3340 3544
 		if ($mode == 4)
3341 3545
 		{
3342
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3343
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3344
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3345
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3346
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3347
-			else
3546
+			if ($statut == '-1' || $statut == 'ST_NO') {
3547
+				return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3548
+			} elseif ($statut ==  '0' || $statut == 'ST_NEVER') {
3549
+				return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3550
+			} elseif ($statut ==  '1' || $statut == 'ST_TODO') {
3551
+				return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3552
+			} elseif ($statut ==  '2' || $statut == 'ST_PEND') {
3553
+				return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3554
+			} elseif ($statut ==  '3' || $statut == 'ST_DONE') {
3555
+				return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3556
+			} else
3348 3557
 			{
3349 3558
 				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3350 3559
 			}
@@ -3374,7 +3583,9 @@  discard block
 block discarded – undo
3374 3583
 	function getOutstandingProposals($mode='customer')
3375 3584
 	{
3376 3585
 		$table='propal';
3377
-		if ($mode == 'supplier') $table = 'supplier_proposal';
3586
+		if ($mode == 'supplier') {
3587
+			$table = 'supplier_proposal';
3588
+		}
3378 3589
 
3379 3590
 		$sql  = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3380 3591
 		$sql .= " WHERE fk_soc = ". $this->id;
@@ -3394,15 +3605,17 @@  discard block
 block discarded – undo
3394 3605
 			while($obj=$this->db->fetch_object($resql)) {
3395 3606
 				$outstandingTotal+= $obj->total_ht;
3396 3607
 				$outstandingTotalIncTax+= $obj->total_ttc;
3397
-				if ($obj->fk_statut != 0)    // Not a draft
3608
+				if ($obj->fk_statut != 0) {
3609
+					// Not a draft
3398 3610
 				{
3399 3611
 					$outstandingOpened+=$obj->total_ttc;
3400 3612
 				}
3613
+				}
3401 3614
 			}
3402 3615
 			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
3616
+		} else {
3617
+					return array();
3403 3618
 		}
3404
-		else
3405
-			return array();
3406 3619
 	}
3407 3620
 
3408 3621
 	/**
@@ -3414,7 +3627,9 @@  discard block
 block discarded – undo
3414 3627
 	function getOutstandingOrders($mode='customer')
3415 3628
 	{
3416 3629
 		$table='commande';
3417
-		if ($mode == 'supplier') $table = 'commande_fournisseur';
3630
+		if ($mode == 'supplier') {
3631
+			$table = 'commande_fournisseur';
3632
+		}
3418 3633
 
3419 3634
 		$sql  = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3420 3635
 		$sql .= " WHERE fk_soc = ". $this->id;
@@ -3434,15 +3649,17 @@  discard block
 block discarded – undo
3434 3649
 			while($obj=$this->db->fetch_object($resql)) {
3435 3650
 				$outstandingTotal+= $obj->total_ht;
3436 3651
 				$outstandingTotalIncTax+= $obj->total_ttc;
3437
-				if ($obj->fk_statut != 0)    // Not a draft
3652
+				if ($obj->fk_statut != 0) {
3653
+					// Not a draft
3438 3654
 				{
3439 3655
 					$outstandingOpened+=$obj->total_ttc;
3440 3656
 				}
3657
+				}
3441 3658
 			}
3442 3659
 			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
3660
+		} else {
3661
+					return array();
3443 3662
 		}
3444
-		else
3445
-			return array();
3446 3663
 	}
3447 3664
 
3448 3665
 	/**
@@ -3454,7 +3671,9 @@  discard block
 block discarded – undo
3454 3671
 	function getOutstandingBills($mode='customer')
3455 3672
 	{
3456 3673
 		$table='facture';
3457
-		if ($mode == 'supplier') $table = 'facture_fourn';
3674
+		if ($mode == 'supplier') {
3675
+			$table = 'facture_fourn';
3676
+		}
3458 3677
 
3459 3678
 		/* Accurate value of remain to pay is to sum remaintopay for each invoice
3460 3679
 		 $paiement = $invoice->getSommePaiement();
@@ -3463,8 +3682,11 @@  discard block
 block discarded – undo
3463 3682
 		 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3464 3683
 		 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3465 3684
 		 */
3466
-		if ($mode == 'supplier') $sql  = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3467
-		else $sql  = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3685
+		if ($mode == 'supplier') {
3686
+			$sql  = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3687
+		} else {
3688
+			$sql  = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3689
+		}
3468 3690
 		$sql .= " WHERE fk_soc = ". $this->id;
3469 3691
 		if ($mode == 'supplier') {
3470 3692
 			$sql .= " AND entity IN (".getEntity('facture_fourn').")";
@@ -3483,8 +3705,7 @@  discard block
 block discarded – undo
3483 3705
 			{
3484 3706
 				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
3485 3707
 				$tmpobject=new FactureFournisseur($this->db);
3486
-			}
3487
-			else
3708
+			} else
3488 3709
 			{
3489 3710
 				require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3490 3711
 				$tmpobject=new Facture($this->db);
@@ -3501,18 +3722,19 @@  discard block
 block discarded – undo
3501 3722
 				if ($obj->paye == 0
3502 3723
 					&& $obj->fk_statut != 0    // Not a draft
3503 3724
 					&& $obj->fk_statut != 3	   // Not abandonned
3504
-					&& $obj->fk_statut != 2)   // Not classified as paid
3725
+					&& $obj->fk_statut != 2) {
3726
+					// Not classified as paid
3505 3727
 				//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3506 3728
 				{
3507 3729
 					$paiement = $tmpobject->getSommePaiement();
3730
+				}
3508 3731
 					$creditnotes = $tmpobject->getSumCreditNotesUsed();
3509 3732
 					$deposits = $tmpobject->getSumDepositsUsed();
3510 3733
 					$outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
3511 3734
 				}
3512 3735
 			}
3513 3736
 			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);
3514
-		}
3515
-		else
3737
+		} else
3516 3738
 		{
3517 3739
 			return array();
3518 3740
 		}
@@ -3556,9 +3778,9 @@  discard block
 block discarded – undo
3556 3778
 	            $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3557 3779
 	        }
3558 3780
 	        return $outstandingAmount;
3781
+	    } else {
3782
+	    	        return 0;
3559 3783
 	    }
3560
-	    else
3561
-	        return 0;
3562 3784
 	}
3563 3785
 
3564 3786
 	/**
@@ -3582,10 +3804,18 @@  discard block
 block discarded – undo
3582 3804
 		global $langs;
3583 3805
 		$langs->load('companies');
3584 3806
 
3585
-		if ($statut==0) return $langs->trans("NorProspectNorCustomer");
3586
-		if ($statut==1) return $langs->trans("Customer");
3587
-		if ($statut==2) return $langs->trans("Prospect");
3588
-		if ($statut==3) return $langs->trans("ProspectCustomer");
3807
+		if ($statut==0) {
3808
+			return $langs->trans("NorProspectNorCustomer");
3809
+		}
3810
+		if ($statut==1) {
3811
+			return $langs->trans("Customer");
3812
+		}
3813
+		if ($statut==2) {
3814
+			return $langs->trans("Prospect");
3815
+		}
3816
+		if ($statut==3) {
3817
+			return $langs->trans("ProspectCustomer");
3818
+		}
3589 3819
 
3590 3820
 	}
3591 3821
 
@@ -3612,10 +3842,11 @@  discard block
 block discarded – undo
3612 3842
 		    include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3613 3843
 		    $companybankaccount = new CompanyBankAccount($this->db);
3614 3844
 		    $result = $companybankaccount->fetch($moreparams['use_companybankid']);
3615
-		    if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3845
+		    if (! $result) {
3846
+		    	dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3847
+		    }
3616 3848
 		    $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3617
-		}
3618
-		else
3849
+		} else
3619 3850
 		{
3620 3851
     		// Positionne le modele sur le nom du modele a utiliser
3621 3852
     		if (! dol_strlen($modele))
@@ -3623,8 +3854,7 @@  discard block
 block discarded – undo
3623 3854
     			if (! empty($conf->global->COMPANY_ADDON_PDF))
3624 3855
     			{
3625 3856
     				$modele = $conf->global->COMPANY_ADDON_PDF;
3626
-    			}
3627
-    			else
3857
+    			} else
3628 3858
     			{
3629 3859
     				print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3630 3860
                     return 0;
Please login to merge, or discard this patch.