Passed
Push — master ( 49af33...3cffbe )
by Alxarafe
21:21
created
dolibarr/htdocs/core/lib/files.lib.php 3 patches
Indentation   +2345 added lines, -2345 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
  */
35 35
 function dol_basename($pathfile)
36 36
 {
37
-	return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/'));
37
+    return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/'));
38 38
 }
39 39
 
40 40
 /**
@@ -58,158 +58,158 @@  discard block
 block discarded – undo
58 58
  */
59 59
 function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
60 60
 {
61
-	global $db, $hookmanager;
62
-	global $object;
63
-
64
-	dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
65
-	//print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
66
-
67
-	$loaddate=($mode==1||$mode==2)?true:false;
68
-	$loadsize=($mode==1||$mode==3)?true:false;
69
-
70
-	// Clean parameters
71
-	$path=preg_replace('/([\\/]+)$/i','',$path);
72
-	$newpath=dol_osencode($path);
73
-
74
-	$reshook = 0;
75
-	$file_list = array();
76
-
77
-	if (is_object($hookmanager) && ! $nohook)
78
-	{
79
-		$hookmanager->resArray=array();
80
-
81
-		$hookmanager->initHooks(array('fileslib'));
82
-
83
-		$parameters=array(
84
-				'path' => $newpath,
85
-				'types'=> $types,
86
-				'recursive' => $recursive,
87
-				'filter' => $filter,
88
-				'excludefilter' => $excludefilter,
89
-				'sortcriteria' => $sortcriteria,
90
-				'sortorder' => $sortorder,
91
-				'loaddate' => $loaddate,
92
-				'loadsize' => $loadsize,
93
-				'mode' => $mode
94
-		);
95
-		$reshook=$hookmanager->executeHooks('getDirList', $parameters, $object);
96
-	}
97
-
98
-	// $hookmanager->resArray may contain array stacked by other modules
99
-	if (empty($reshook))
100
-	{
101
-		if (! is_dir($newpath)) return array();
102
-
103
-		if ($dir = opendir($newpath))
104
-		{
105
-			$filedate='';
106
-			$filesize='';
107
-
108
-			while (false !== ($file = readdir($dir)))        // $file is always a basename (into directory $newpath)
109
-			{
110
-				if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure data is stored in utf8 in memory
111
-				$fullpathfile=($newpath?$newpath.'/':'').$file;
112
-
113
-				$qualified=1;
114
-
115
-				// Define excludefilterarray
116
-				$excludefilterarray=array('^\.');
117
-				if (is_array($excludefilter))
118
-				{
119
-					$excludefilterarray=array_merge($excludefilterarray,$excludefilter);
120
-				}
121
-				else if ($excludefilter) $excludefilterarray[]=$excludefilter;
122
-				// Check if file is qualified
123
-				foreach($excludefilterarray as $filt)
124
-				{
125
-					if (preg_match('/'.$filt.'/i', $file) || preg_match('/'.$filt.'/i', $fullpathfile)) {
126
-						$qualified=0; break;
127
-					}
128
-				}
129
-				//print $fullpathfile.' '.$file.' '.$qualified.'<br>';
130
-
131
-				if ($qualified)
132
-				{
133
-					$isdir=is_dir(dol_osencode($path."/".$file));
134
-					// Check whether this is a file or directory and whether we're interested in that type
135
-					if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
136
-					{
137
-						// Add entry into file_list array
138
-						if (($types=="directories") || ($types=="all"))
139
-						{
140
-							if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
141
-							if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
142
-
143
-							if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into all $path, only into $file part
144
-							{
145
-								preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
146
-								$level1name=(isset($reg[1])?$reg[1]:'');
147
-								$file_list[] = array(
148
-										"name" => $file,
149
-										"path" => $path,
150
-										"level1name" => $level1name,
151
-										"relativename" => ($relativename?$relativename.'/':'').$file,
152
-										"fullname" => $path.'/'.$file,
153
-										"date" => $filedate,
154
-										"size" => $filesize,
155
-										"type" => 'dir'
156
-								);
157
-							}
158
-						}
159
-
160
-						// if we're in a directory and we want recursive behavior, call this function again
161
-						if ($recursive)
162
-						{
163
-							if (empty($donotfollowsymlinks) || ! is_link($path."/".$file))
164
-							{
165
-								//var_dump('eee '. $path."/".$file. ' '.is_dir($path."/".$file).' '.is_link($path."/".$file));
166
-								$file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename!=''?$relativename.'/':'').$file, $donotfollowsymlinks));
167
-							}
168
-						}
169
-					}
170
-					else if (! $isdir && (($types == "files") || ($types == "all")))
171
-					{
172
-						// Add file into file_list array
173
-						if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
174
-						if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
175
-
176
-						if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into $path, only into $file
177
-						{
178
-							preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
179
-							$level1name=(isset($reg[1])?$reg[1]:'');
180
-							$file_list[] = array(
181
-									"name" => $file,
182
-									"path" => $path,
183
-									"level1name" => $level1name,
184
-									"relativename" => ($relativename?$relativename.'/':'').$file,
185
-									"fullname" => $path.'/'.$file,
186
-									"date" => $filedate,
187
-									"size" => $filesize,
188
-									"type" => 'file'
189
-							);
190
-						}
191
-					}
192
-				}
193
-			}
194
-			closedir($dir);
195
-
196
-			// Obtain a list of columns
197
-			if (! empty($sortcriteria))
198
-			{
199
-				$myarray=array();
200
-				foreach ($file_list as $key => $row)
201
-				{
202
-					$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
203
-				}
204
-				// Sort the data
205
-				if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
206
-			}
207
-		}
208
-	}
209
-
210
-	if (is_object($hookmanager) && is_array($hookmanager->resArray)) $file_list = array_merge($file_list, $hookmanager->resArray);
211
-
212
-	return $file_list;
61
+    global $db, $hookmanager;
62
+    global $object;
63
+
64
+    dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
65
+    //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
66
+
67
+    $loaddate=($mode==1||$mode==2)?true:false;
68
+    $loadsize=($mode==1||$mode==3)?true:false;
69
+
70
+    // Clean parameters
71
+    $path=preg_replace('/([\\/]+)$/i','',$path);
72
+    $newpath=dol_osencode($path);
73
+
74
+    $reshook = 0;
75
+    $file_list = array();
76
+
77
+    if (is_object($hookmanager) && ! $nohook)
78
+    {
79
+        $hookmanager->resArray=array();
80
+
81
+        $hookmanager->initHooks(array('fileslib'));
82
+
83
+        $parameters=array(
84
+                'path' => $newpath,
85
+                'types'=> $types,
86
+                'recursive' => $recursive,
87
+                'filter' => $filter,
88
+                'excludefilter' => $excludefilter,
89
+                'sortcriteria' => $sortcriteria,
90
+                'sortorder' => $sortorder,
91
+                'loaddate' => $loaddate,
92
+                'loadsize' => $loadsize,
93
+                'mode' => $mode
94
+        );
95
+        $reshook=$hookmanager->executeHooks('getDirList', $parameters, $object);
96
+    }
97
+
98
+    // $hookmanager->resArray may contain array stacked by other modules
99
+    if (empty($reshook))
100
+    {
101
+        if (! is_dir($newpath)) return array();
102
+
103
+        if ($dir = opendir($newpath))
104
+        {
105
+            $filedate='';
106
+            $filesize='';
107
+
108
+            while (false !== ($file = readdir($dir)))        // $file is always a basename (into directory $newpath)
109
+            {
110
+                if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure data is stored in utf8 in memory
111
+                $fullpathfile=($newpath?$newpath.'/':'').$file;
112
+
113
+                $qualified=1;
114
+
115
+                // Define excludefilterarray
116
+                $excludefilterarray=array('^\.');
117
+                if (is_array($excludefilter))
118
+                {
119
+                    $excludefilterarray=array_merge($excludefilterarray,$excludefilter);
120
+                }
121
+                else if ($excludefilter) $excludefilterarray[]=$excludefilter;
122
+                // Check if file is qualified
123
+                foreach($excludefilterarray as $filt)
124
+                {
125
+                    if (preg_match('/'.$filt.'/i', $file) || preg_match('/'.$filt.'/i', $fullpathfile)) {
126
+                        $qualified=0; break;
127
+                    }
128
+                }
129
+                //print $fullpathfile.' '.$file.' '.$qualified.'<br>';
130
+
131
+                if ($qualified)
132
+                {
133
+                    $isdir=is_dir(dol_osencode($path."/".$file));
134
+                    // Check whether this is a file or directory and whether we're interested in that type
135
+                    if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
136
+                    {
137
+                        // Add entry into file_list array
138
+                        if (($types=="directories") || ($types=="all"))
139
+                        {
140
+                            if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
141
+                            if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
142
+
143
+                            if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into all $path, only into $file part
144
+                            {
145
+                                preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
146
+                                $level1name=(isset($reg[1])?$reg[1]:'');
147
+                                $file_list[] = array(
148
+                                        "name" => $file,
149
+                                        "path" => $path,
150
+                                        "level1name" => $level1name,
151
+                                        "relativename" => ($relativename?$relativename.'/':'').$file,
152
+                                        "fullname" => $path.'/'.$file,
153
+                                        "date" => $filedate,
154
+                                        "size" => $filesize,
155
+                                        "type" => 'dir'
156
+                                );
157
+                            }
158
+                        }
159
+
160
+                        // if we're in a directory and we want recursive behavior, call this function again
161
+                        if ($recursive)
162
+                        {
163
+                            if (empty($donotfollowsymlinks) || ! is_link($path."/".$file))
164
+                            {
165
+                                //var_dump('eee '. $path."/".$file. ' '.is_dir($path."/".$file).' '.is_link($path."/".$file));
166
+                                $file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename!=''?$relativename.'/':'').$file, $donotfollowsymlinks));
167
+                            }
168
+                        }
169
+                    }
170
+                    else if (! $isdir && (($types == "files") || ($types == "all")))
171
+                    {
172
+                        // Add file into file_list array
173
+                        if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
174
+                        if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
175
+
176
+                        if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into $path, only into $file
177
+                        {
178
+                            preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
179
+                            $level1name=(isset($reg[1])?$reg[1]:'');
180
+                            $file_list[] = array(
181
+                                    "name" => $file,
182
+                                    "path" => $path,
183
+                                    "level1name" => $level1name,
184
+                                    "relativename" => ($relativename?$relativename.'/':'').$file,
185
+                                    "fullname" => $path.'/'.$file,
186
+                                    "date" => $filedate,
187
+                                    "size" => $filesize,
188
+                                    "type" => 'file'
189
+                            );
190
+                        }
191
+                    }
192
+                }
193
+            }
194
+            closedir($dir);
195
+
196
+            // Obtain a list of columns
197
+            if (! empty($sortcriteria))
198
+            {
199
+                $myarray=array();
200
+                foreach ($file_list as $key => $row)
201
+                {
202
+                    $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
203
+                }
204
+                // Sort the data
205
+                if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
206
+            }
207
+        }
208
+    }
209
+
210
+    if (is_object($hookmanager) && is_array($hookmanager->resArray)) $file_list = array_merge($file_list, $hookmanager->resArray);
211
+
212
+    return $file_list;
213 213
 }
214 214
 
215 215
 
@@ -228,68 +228,68 @@  discard block
 block discarded – undo
228 228
  */
229 229
 function dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0)
230 230
 {
231
-	global $conf, $db;
232
-
233
-	$sql =" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,";
234
-	$sql.=" acl, position, share";
235
-	if ($mode) $sql.=", description";
236
-	$sql.=" FROM ".MAIN_DB_PREFIX."ecm_files";
237
-	$sql.=" WHERE filepath = '".$db->escape($path)."'";
238
-	$sql.=" AND entity = ".$conf->entity;
239
-
240
-	$resql = $db->query($sql);
241
-	if ($resql)
242
-	{
243
-		$file_list=array();
244
-		$num = $db->num_rows($resql);
245
-		$i = 0;
246
-		while ($i < $num)
247
-		{
248
-			$obj = $db->fetch_object($resql);
249
-			if ($obj)
250
-			{
251
-				preg_match('/([^\/]+)\/[^\/]+$/',DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,$reg);
252
-				$level1name=(isset($reg[1])?$reg[1]:'');
253
-				$file_list[] = array(
254
-					"rowid" => $obj->rowid,
255
-					"label" => $obj->label,         // md5
256
-					"name" => $obj->filename,
257
-					"path" => DOL_DATA_ROOT.'/'.$obj->filepath,
258
-					"level1name" => $level1name,
259
-					"fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,
260
-					"fullpath_orig" => $obj->fullpath_orig,
261
-					"date_c" => $db->jdate($obj->date_c),
262
-					"date_m" => $db->jdate($obj->date_m),
263
-					"type" => 'file',
264
-					"keywords" => $obj->keywords,
265
-					"cover" => $obj->cover,
266
-					"position" => (int) $obj->position,
267
-					"acl" => $obj->acl,
268
-					"share" => $obj->share
269
-				);
270
-			}
271
-			$i++;
272
-		}
273
-
274
-		// Obtain a list of columns
275
-		if (! empty($sortcriteria))
276
-		{
277
-			$myarray=array();
278
-			foreach ($file_list as $key => $row)
279
-			{
280
-				$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
281
-			}
282
-			// Sort the data
283
-			if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
284
-		}
285
-
286
-		return $file_list;
287
-	}
288
-	else
289
-	{
290
-		dol_print_error($db);
291
-		return array();
292
-	}
231
+    global $conf, $db;
232
+
233
+    $sql =" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,";
234
+    $sql.=" acl, position, share";
235
+    if ($mode) $sql.=", description";
236
+    $sql.=" FROM ".MAIN_DB_PREFIX."ecm_files";
237
+    $sql.=" WHERE filepath = '".$db->escape($path)."'";
238
+    $sql.=" AND entity = ".$conf->entity;
239
+
240
+    $resql = $db->query($sql);
241
+    if ($resql)
242
+    {
243
+        $file_list=array();
244
+        $num = $db->num_rows($resql);
245
+        $i = 0;
246
+        while ($i < $num)
247
+        {
248
+            $obj = $db->fetch_object($resql);
249
+            if ($obj)
250
+            {
251
+                preg_match('/([^\/]+)\/[^\/]+$/',DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,$reg);
252
+                $level1name=(isset($reg[1])?$reg[1]:'');
253
+                $file_list[] = array(
254
+                    "rowid" => $obj->rowid,
255
+                    "label" => $obj->label,         // md5
256
+                    "name" => $obj->filename,
257
+                    "path" => DOL_DATA_ROOT.'/'.$obj->filepath,
258
+                    "level1name" => $level1name,
259
+                    "fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,
260
+                    "fullpath_orig" => $obj->fullpath_orig,
261
+                    "date_c" => $db->jdate($obj->date_c),
262
+                    "date_m" => $db->jdate($obj->date_m),
263
+                    "type" => 'file',
264
+                    "keywords" => $obj->keywords,
265
+                    "cover" => $obj->cover,
266
+                    "position" => (int) $obj->position,
267
+                    "acl" => $obj->acl,
268
+                    "share" => $obj->share
269
+                );
270
+            }
271
+            $i++;
272
+        }
273
+
274
+        // Obtain a list of columns
275
+        if (! empty($sortcriteria))
276
+        {
277
+            $myarray=array();
278
+            foreach ($file_list as $key => $row)
279
+            {
280
+                $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
281
+            }
282
+            // Sort the data
283
+            if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
284
+        }
285
+
286
+        return $file_list;
287
+    }
288
+    else
289
+    {
290
+        dol_print_error($db);
291
+        return array();
292
+    }
293 293
 }
294 294
 
295 295
 
@@ -303,94 +303,94 @@  discard block
 block discarded – undo
303 303
  */
304 304
 function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
305 305
 {
306
-	global $conf, $db, $user;
307
-
308
-	$filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC);
309
-
310
-	// TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed
311
-	global $modulepart;
312
-	if ($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
313
-		global $object;
314
-		if (! empty($object->id))
315
-		{
316
-			if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
317
-			else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
318
-
319
-			$relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dirold);
320
-			$relativedirold = preg_replace('/^[\\/]/','',$relativedirold);
321
-
322
-			$filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC));
323
-		}
324
-	}
325
-
326
-	//var_dump($filearray);
327
-	//var_dump($filearrayindatabase);
328
-
329
-	// Complete filearray with properties found into $filearrayindatabase
330
-	foreach($filearray as $key => $val)
331
-	{
332
-		$found=0;
333
-		// Search if it exists into $filearrayindatabase
334
-		foreach($filearrayindatabase as $key2 => $val2)
335
-		{
336
-			if ($filearrayindatabase[$key2]['name'] == $filearray[$key]['name'])
337
-			{
338
-				$filearray[$key]['position_name']=($filearrayindatabase[$key2]['position']?$filearrayindatabase[$key2]['position']:'0').'_'.$filearrayindatabase[$key2]['name'];
339
-				$filearray[$key]['position']=$filearrayindatabase[$key2]['position'];
340
-				$filearray[$key]['cover']=$filearrayindatabase[$key2]['cover'];
341
-				$filearray[$key]['acl']=$filearrayindatabase[$key2]['acl'];
342
-				$filearray[$key]['rowid']=$filearrayindatabase[$key2]['rowid'];
343
-				$filearray[$key]['label']=$filearrayindatabase[$key2]['label'];
344
-				$filearray[$key]['share']=$filearrayindatabase[$key2]['share'];
345
-				$found=1;
346
-				break;
347
-			}
348
-		}
349
-
350
-		if (! $found)    // This happen in transition toward version 6, or if files were added manually into os dir.
351
-		{
352
-			$filearray[$key]['position']='999999';     // File not indexed are at end. So if we add a file, it will not replace an existing position
353
-			$filearray[$key]['cover']=0;
354
-			$filearray[$key]['acl']='';
355
-
356
-			$rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filearray[$key]['fullname']);
357
-			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
358
-			{
359
-				dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
360
-				include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
361
-				$ecmfile=new EcmFiles($db);
362
-
363
-				// Add entry into database
364
-				$filename = basename($rel_filename);
365
-				$rel_dir = dirname($rel_filename);
366
-				$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
367
-				$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
368
-
369
-				$ecmfile->filepath = $rel_dir;
370
-				$ecmfile->filename = $filename;
371
-				$ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname']));        // $destfile is a full path to file
372
-				$ecmfile->fullpath_orig = $filearray[$key]['fullname'];
373
-				$ecmfile->gen_or_uploaded = 'unknown';
374
-				$ecmfile->description = '';    // indexed content
375
-				$ecmfile->keyword = '';        // keyword content
376
-				$result = $ecmfile->create($user);
377
-				if ($result < 0)
378
-				{
379
-					setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
380
-				}
381
-				else
382
-				{
383
-					$filearray[$key]['rowid']=$result;
384
-				}
385
-			}
386
-			else
387
-			{
388
-				$filearray[$key]['rowid']=0;     // Should not happened
389
-			}
390
-		}
391
-	}
392
-
393
-	/*var_dump($filearray);*/
306
+    global $conf, $db, $user;
307
+
308
+    $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC);
309
+
310
+    // TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed
311
+    global $modulepart;
312
+    if ($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
313
+        global $object;
314
+        if (! empty($object->id))
315
+        {
316
+            if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
317
+            else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
318
+
319
+            $relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dirold);
320
+            $relativedirold = preg_replace('/^[\\/]/','',$relativedirold);
321
+
322
+            $filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC));
323
+        }
324
+    }
325
+
326
+    //var_dump($filearray);
327
+    //var_dump($filearrayindatabase);
328
+
329
+    // Complete filearray with properties found into $filearrayindatabase
330
+    foreach($filearray as $key => $val)
331
+    {
332
+        $found=0;
333
+        // Search if it exists into $filearrayindatabase
334
+        foreach($filearrayindatabase as $key2 => $val2)
335
+        {
336
+            if ($filearrayindatabase[$key2]['name'] == $filearray[$key]['name'])
337
+            {
338
+                $filearray[$key]['position_name']=($filearrayindatabase[$key2]['position']?$filearrayindatabase[$key2]['position']:'0').'_'.$filearrayindatabase[$key2]['name'];
339
+                $filearray[$key]['position']=$filearrayindatabase[$key2]['position'];
340
+                $filearray[$key]['cover']=$filearrayindatabase[$key2]['cover'];
341
+                $filearray[$key]['acl']=$filearrayindatabase[$key2]['acl'];
342
+                $filearray[$key]['rowid']=$filearrayindatabase[$key2]['rowid'];
343
+                $filearray[$key]['label']=$filearrayindatabase[$key2]['label'];
344
+                $filearray[$key]['share']=$filearrayindatabase[$key2]['share'];
345
+                $found=1;
346
+                break;
347
+            }
348
+        }
349
+
350
+        if (! $found)    // This happen in transition toward version 6, or if files were added manually into os dir.
351
+        {
352
+            $filearray[$key]['position']='999999';     // File not indexed are at end. So if we add a file, it will not replace an existing position
353
+            $filearray[$key]['cover']=0;
354
+            $filearray[$key]['acl']='';
355
+
356
+            $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filearray[$key]['fullname']);
357
+            if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
358
+            {
359
+                dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
360
+                include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
361
+                $ecmfile=new EcmFiles($db);
362
+
363
+                // Add entry into database
364
+                $filename = basename($rel_filename);
365
+                $rel_dir = dirname($rel_filename);
366
+                $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
367
+                $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
368
+
369
+                $ecmfile->filepath = $rel_dir;
370
+                $ecmfile->filename = $filename;
371
+                $ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname']));        // $destfile is a full path to file
372
+                $ecmfile->fullpath_orig = $filearray[$key]['fullname'];
373
+                $ecmfile->gen_or_uploaded = 'unknown';
374
+                $ecmfile->description = '';    // indexed content
375
+                $ecmfile->keyword = '';        // keyword content
376
+                $result = $ecmfile->create($user);
377
+                if ($result < 0)
378
+                {
379
+                    setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
380
+                }
381
+                else
382
+                {
383
+                    $filearray[$key]['rowid']=$result;
384
+                }
385
+            }
386
+            else
387
+            {
388
+                $filearray[$key]['rowid']=0;     // Should not happened
389
+            }
390
+        }
391
+    }
392
+
393
+    /*var_dump($filearray);*/
394 394
 }
395 395
 
396 396
 
@@ -403,29 +403,29 @@  discard block
 block discarded – undo
403 403
  */
404 404
 function dol_compare_file($a, $b)
405 405
 {
406
-	global $sortorder;
407
-	global $sortfield;
408
-
409
-	$sortorder=strtoupper($sortorder);
410
-
411
-	if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
412
-	else { $retup=1; $retdown=-1; }
413
-
414
-	if ($sortfield == 'name')
415
-	{
416
-		if ($a->name == $b->name) return 0;
417
-		return ($a->name < $b->name) ? $retup : $retdown;
418
-	}
419
-	if ($sortfield == 'date')
420
-	{
421
-		if ($a->date == $b->date) return 0;
422
-		return ($a->date < $b->date) ? $retup : $retdown;
423
-	}
424
-	if ($sortfield == 'size')
425
-	{
426
-		if ($a->size == $b->size) return 0;
427
-		return ($a->size < $b->size) ? $retup : $retdown;
428
-	}
406
+    global $sortorder;
407
+    global $sortfield;
408
+
409
+    $sortorder=strtoupper($sortorder);
410
+
411
+    if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
412
+    else { $retup=1; $retdown=-1; }
413
+
414
+    if ($sortfield == 'name')
415
+    {
416
+        if ($a->name == $b->name) return 0;
417
+        return ($a->name < $b->name) ? $retup : $retdown;
418
+    }
419
+    if ($sortfield == 'date')
420
+    {
421
+        if ($a->date == $b->date) return 0;
422
+        return ($a->date < $b->date) ? $retup : $retdown;
423
+    }
424
+    if ($sortfield == 'size')
425
+    {
426
+        if ($a->size == $b->size) return 0;
427
+        return ($a->size < $b->size) ? $retup : $retdown;
428
+    }
429 429
 }
430 430
 
431 431
 
@@ -437,9 +437,9 @@  discard block
 block discarded – undo
437 437
  */
438 438
 function dol_is_dir($folder)
439 439
 {
440
-	$newfolder=dol_osencode($folder);
441
-	if (is_dir($newfolder)) return true;
442
-	else return false;
440
+    $newfolder=dol_osencode($folder);
441
+    if (is_dir($newfolder)) return true;
442
+    else return false;
443 443
 }
444 444
 
445 445
 /**
@@ -450,8 +450,8 @@  discard block
 block discarded – undo
450 450
  */
451 451
 function dol_is_file($pathoffile)
452 452
 {
453
-	$newpathoffile=dol_osencode($pathoffile);
454
-	return is_file($newpathoffile);
453
+    $newpathoffile=dol_osencode($pathoffile);
454
+    return is_file($newpathoffile);
455 455
 }
456 456
 
457 457
 /**
@@ -462,8 +462,8 @@  discard block
 block discarded – undo
462 462
  */
463 463
 function dol_is_link($pathoffile)
464 464
 {
465
-	$newpathoffile=dol_osencode($pathoffile);
466
-	return is_link($newpathoffile);
465
+    $newpathoffile=dol_osencode($pathoffile);
466
+    return is_link($newpathoffile);
467 467
 }
468 468
 
469 469
 /**
@@ -474,12 +474,12 @@  discard block
 block discarded – undo
474 474
  */
475 475
 function dol_is_url($url)
476 476
 {
477
-	$tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
478
-	foreach($tmpprot as $prot)
479
-	{
480
-		if (preg_match('/^'.$prot.':/i',$url)) return true;
481
-	}
482
-	return false;
477
+    $tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
478
+    foreach($tmpprot as $prot)
479
+    {
480
+        if (preg_match('/^'.$prot.':/i',$url)) return true;
481
+    }
482
+    return false;
483 483
 }
484 484
 
485 485
 /**
@@ -490,24 +490,24 @@  discard block
 block discarded – undo
490 490
  */
491 491
 function dol_dir_is_emtpy($folder)
492 492
 {
493
-	$newfolder=dol_osencode($folder);
494
-	if (is_dir($newfolder))
495
-	{
496
-		$handle = opendir($newfolder);
497
-		$folder_content = '';
498
-		while ((gettype($name = readdir($handle)) != "boolean"))
499
-		{
500
-			$name_array[] = $name;
501
-		}
502
-		foreach($name_array as $temp) $folder_content .= $temp;
503
-
504
-		closedir($handle);
505
-
506
-		if ($folder_content == "...") return true;
507
-		else return false;
508
-	}
509
-	else
510
-	return true; // Dir does not exists
493
+    $newfolder=dol_osencode($folder);
494
+    if (is_dir($newfolder))
495
+    {
496
+        $handle = opendir($newfolder);
497
+        $folder_content = '';
498
+        while ((gettype($name = readdir($handle)) != "boolean"))
499
+        {
500
+            $name_array[] = $name;
501
+        }
502
+        foreach($name_array as $temp) $folder_content .= $temp;
503
+
504
+        closedir($handle);
505
+
506
+        if ($folder_content == "...") return true;
507
+        else return false;
508
+    }
509
+    else
510
+    return true; // Dir does not exists
511 511
 }
512 512
 
513 513
 /**
@@ -519,27 +519,27 @@  discard block
 block discarded – undo
519 519
  */
520 520
 function dol_count_nb_of_line($file)
521 521
 {
522
-	$nb=0;
523
-
524
-	$newfile=dol_osencode($file);
525
-	//print 'x'.$file;
526
-	$fp=fopen($newfile,'r');
527
-	if ($fp)
528
-	{
529
-		while (!feof($fp))
530
-		{
531
-			$line=fgets($fp);
532
-			// We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
533
-			if (! $line === false) $nb++;
534
-		}
535
-		fclose($fp);
536
-	}
537
-	else
538
-	{
539
-		$nb=-1;
540
-	}
541
-
542
-	return $nb;
522
+    $nb=0;
523
+
524
+    $newfile=dol_osencode($file);
525
+    //print 'x'.$file;
526
+    $fp=fopen($newfile,'r');
527
+    if ($fp)
528
+    {
529
+        while (!feof($fp))
530
+        {
531
+            $line=fgets($fp);
532
+            // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
533
+            if (! $line === false) $nb++;
534
+        }
535
+        fclose($fp);
536
+    }
537
+    else
538
+    {
539
+        $nb=-1;
540
+    }
541
+
542
+    return $nb;
543 543
 }
544 544
 
545 545
 
@@ -551,8 +551,8 @@  discard block
 block discarded – undo
551 551
  */
552 552
 function dol_filesize($pathoffile)
553 553
 {
554
-	$newpathoffile=dol_osencode($pathoffile);
555
-	return filesize($newpathoffile);
554
+    $newpathoffile=dol_osencode($pathoffile);
555
+    return filesize($newpathoffile);
556 556
 }
557 557
 
558 558
 /**
@@ -563,8 +563,8 @@  discard block
 block discarded – undo
563 563
  */
564 564
 function dol_filemtime($pathoffile)
565 565
 {
566
-	$newpathoffile=dol_osencode($pathoffile);
567
-	return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
566
+    $newpathoffile=dol_osencode($pathoffile);
567
+    return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
568 568
 }
569 569
 
570 570
 /**
@@ -580,61 +580,61 @@  discard block
 block discarded – undo
580 580
  */
581 581
 function dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0)
582 582
 {
583
-	global $conf;
583
+    global $conf;
584 584
 
585
-	dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase);
585
+    dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase);
586 586
 
587
-	if (empty($srcfile)) return -1;
588
-	if (empty($destfile)) $destfile=$srcfile;
587
+    if (empty($srcfile)) return -1;
588
+    if (empty($destfile)) $destfile=$srcfile;
589 589
 
590
-	$destexists=dol_is_file($destfile);
591
-	if (($destfile != $srcfile) && $destexists) return 0;
590
+    $destexists=dol_is_file($destfile);
591
+    if (($destfile != $srcfile) && $destexists) return 0;
592 592
 
593
-	$tmpdestfile=$destfile.'.tmp';
593
+    $tmpdestfile=$destfile.'.tmp';
594 594
 
595
-	$newpathofsrcfile=dol_osencode($srcfile);
596
-	$newpathoftmpdestfile=dol_osencode($tmpdestfile);
597
-	$newpathofdestfile=dol_osencode($destfile);
598
-	$newdirdestfile=dirname($newpathofdestfile);
595
+    $newpathofsrcfile=dol_osencode($srcfile);
596
+    $newpathoftmpdestfile=dol_osencode($tmpdestfile);
597
+    $newpathofdestfile=dol_osencode($destfile);
598
+    $newdirdestfile=dirname($newpathofdestfile);
599 599
 
600
-	if ($destexists && ! is_writable($newpathofdestfile))
601
-	{
602
-		dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
603
-		return -1;
604
-	}
605
-	if (! is_writable($newdirdestfile))
606
-	{
607
-		dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
608
-		return -2;
609
-	}
600
+    if ($destexists && ! is_writable($newpathofdestfile))
601
+    {
602
+        dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
603
+        return -1;
604
+    }
605
+    if (! is_writable($newdirdestfile))
606
+    {
607
+        dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
608
+        return -2;
609
+    }
610 610
 
611
-	dol_delete_file($tmpdestfile);
611
+    dol_delete_file($tmpdestfile);
612 612
 
613
-	// Create $newpathoftmpdestfile from $newpathofsrcfile
614
-	$content = file_get_contents($newpathofsrcfile, 'r');
613
+    // Create $newpathoftmpdestfile from $newpathofsrcfile
614
+    $content = file_get_contents($newpathofsrcfile, 'r');
615 615
 
616
-	$content = make_substitutions($content, $arrayreplacement, null);
616
+    $content = make_substitutions($content, $arrayreplacement, null);
617 617
 
618
-	file_put_contents($newpathoftmpdestfile, $content);
619
-	@chmod($newpathoftmpdestfile, octdec($newmask));
618
+    file_put_contents($newpathoftmpdestfile, $content);
619
+    @chmod($newpathoftmpdestfile, octdec($newmask));
620 620
 
621
-	// Rename
622
-	$result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase);
623
-	if (! $result)
624
-	{
625
-		dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
626
-		return -3;
627
-	}
628
-	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
629
-	if (empty($newmask))	// This should no happen
630
-	{
631
-		dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
632
-		$newmask='0664';
633
-	}
621
+    // Rename
622
+    $result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase);
623
+    if (! $result)
624
+    {
625
+        dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
626
+        return -3;
627
+    }
628
+    if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
629
+    if (empty($newmask))	// This should no happen
630
+    {
631
+        dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
632
+        $newmask='0664';
633
+    }
634 634
 
635
-	@chmod($newpathofdestfile, octdec($newmask));
635
+    @chmod($newpathofdestfile, octdec($newmask));
636 636
 
637
-	return 1;
637
+    return 1;
638 638
 }
639 639
 
640 640
 /**
@@ -650,7 +650,7 @@  discard block
 block discarded – undo
650 650
  */
651 651
 function dolReplaceRegExInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0)
652 652
 {
653
-	// TODO
653
+    // TODO
654 654
 }
655 655
 
656 656
 /**
@@ -665,47 +665,47 @@  discard block
 block discarded – undo
665 665
  */
666 666
 function dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
667 667
 {
668
-	global $conf;
669
-
670
-	dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
671
-
672
-	if (empty($srcfile) || empty($destfile)) return -1;
673
-
674
-	$destexists=dol_is_file($destfile);
675
-	if (! $overwriteifexists && $destexists) return 0;
676
-
677
-	$newpathofsrcfile=dol_osencode($srcfile);
678
-	$newpathofdestfile=dol_osencode($destfile);
679
-	$newdirdestfile=dirname($newpathofdestfile);
680
-
681
-	if ($destexists && ! is_writable($newpathofdestfile))
682
-	{
683
-		dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
684
-		return -1;
685
-	}
686
-	if (! is_writable($newdirdestfile))
687
-	{
688
-		dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
689
-		return -2;
690
-	}
691
-	// Copy with overwriting if exists
692
-	$result=@copy($newpathofsrcfile, $newpathofdestfile);
693
-	//$result=copy($newpathofsrcfile, $newpathofdestfile);	// To see errors, remove @
694
-	if (! $result)
695
-	{
696
-		dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
697
-		return -3;
698
-	}
699
-	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
700
-	if (empty($newmask))	// This should no happen
701
-	{
702
-		dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
703
-		$newmask='0664';
704
-	}
705
-
706
-	@chmod($newpathofdestfile, octdec($newmask));
707
-
708
-	return 1;
668
+    global $conf;
669
+
670
+    dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
671
+
672
+    if (empty($srcfile) || empty($destfile)) return -1;
673
+
674
+    $destexists=dol_is_file($destfile);
675
+    if (! $overwriteifexists && $destexists) return 0;
676
+
677
+    $newpathofsrcfile=dol_osencode($srcfile);
678
+    $newpathofdestfile=dol_osencode($destfile);
679
+    $newdirdestfile=dirname($newpathofdestfile);
680
+
681
+    if ($destexists && ! is_writable($newpathofdestfile))
682
+    {
683
+        dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
684
+        return -1;
685
+    }
686
+    if (! is_writable($newdirdestfile))
687
+    {
688
+        dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
689
+        return -2;
690
+    }
691
+    // Copy with overwriting if exists
692
+    $result=@copy($newpathofsrcfile, $newpathofdestfile);
693
+    //$result=copy($newpathofsrcfile, $newpathofdestfile);	// To see errors, remove @
694
+    if (! $result)
695
+    {
696
+        dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
697
+        return -3;
698
+    }
699
+    if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
700
+    if (empty($newmask))	// This should no happen
701
+    {
702
+        dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
703
+        $newmask='0664';
704
+    }
705
+
706
+    @chmod($newpathofdestfile, octdec($newmask));
707
+
708
+    return 1;
709 709
 }
710 710
 
711 711
 /**
@@ -721,77 +721,77 @@  discard block
 block discarded – undo
721 721
  */
722 722
 function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null)
723 723
 {
724
-	global $conf;
725
-
726
-	$result=0;
727
-
728
-	dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
729
-
730
-	if (empty($srcfile) || empty($destfile)) return -1;
731
-
732
-	$destexists=dol_is_dir($destfile);
733
-	//if (! $overwriteifexists && $destexists) return 0;	// The overwriteifexists is for files only, so propagated to dol_copy only.
734
-
735
-	if (! $destexists)
736
-	{
737
-		// We must set mask just before creating dir, becaause it can be set differently by dol_copy
738
-		umask(0);
739
-		$dirmaskdec=octdec($newmask);
740
-		if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
741
-		$dirmaskdec |= octdec('0200');  // Set w bit required to be able to create content for recursive subdirs files
742
-		dol_mkdir($destfile, '', decoct($dirmaskdec));
743
-	}
744
-
745
-	$ossrcfile=dol_osencode($srcfile);
746
-	$osdestfile=dol_osencode($destfile);
747
-
748
-	// Recursive function to copy all subdirectories and contents:
749
-	if (is_dir($ossrcfile))
750
-	{
751
-		$dir_handle=opendir($ossrcfile);
752
-		while ($file=readdir($dir_handle))
753
-		{
754
-			if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file))
755
-			{
756
-				if (is_dir($ossrcfile."/".$file))
757
-				{
758
-					//var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
759
-					$tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement);
760
-				}
761
-				else
762
-				{
763
-					$newfile = $file;
764
-					// Replace destination filename with a new one
765
-					if (is_array($arrayreplacement))
766
-					{
767
-						foreach($arrayreplacement as $key => $val)
768
-						{
769
-							$newfile = str_replace($key, $val, $newfile);
770
-						}
771
-					}
772
-					$tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
773
-				}
774
-				// Set result
775
-				if ($result > 0 && $tmpresult >= 0)
776
-				{
777
-					// Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass
778
-				}
779
-				else
780
-				{
781
-					$result=$tmpresult;
782
-				}
783
-				if ($result < 0) break;
784
-			}
785
-		}
786
-		closedir($dir_handle);
787
-	}
788
-	else
789
-	{
790
-		// Source directory does not exists
791
-		$result = -2;
792
-	}
793
-
794
-	return $result;
724
+    global $conf;
725
+
726
+    $result=0;
727
+
728
+    dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
729
+
730
+    if (empty($srcfile) || empty($destfile)) return -1;
731
+
732
+    $destexists=dol_is_dir($destfile);
733
+    //if (! $overwriteifexists && $destexists) return 0;	// The overwriteifexists is for files only, so propagated to dol_copy only.
734
+
735
+    if (! $destexists)
736
+    {
737
+        // We must set mask just before creating dir, becaause it can be set differently by dol_copy
738
+        umask(0);
739
+        $dirmaskdec=octdec($newmask);
740
+        if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
741
+        $dirmaskdec |= octdec('0200');  // Set w bit required to be able to create content for recursive subdirs files
742
+        dol_mkdir($destfile, '', decoct($dirmaskdec));
743
+    }
744
+
745
+    $ossrcfile=dol_osencode($srcfile);
746
+    $osdestfile=dol_osencode($destfile);
747
+
748
+    // Recursive function to copy all subdirectories and contents:
749
+    if (is_dir($ossrcfile))
750
+    {
751
+        $dir_handle=opendir($ossrcfile);
752
+        while ($file=readdir($dir_handle))
753
+        {
754
+            if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file))
755
+            {
756
+                if (is_dir($ossrcfile."/".$file))
757
+                {
758
+                    //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
759
+                    $tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement);
760
+                }
761
+                else
762
+                {
763
+                    $newfile = $file;
764
+                    // Replace destination filename with a new one
765
+                    if (is_array($arrayreplacement))
766
+                    {
767
+                        foreach($arrayreplacement as $key => $val)
768
+                        {
769
+                            $newfile = str_replace($key, $val, $newfile);
770
+                        }
771
+                    }
772
+                    $tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
773
+                }
774
+                // Set result
775
+                if ($result > 0 && $tmpresult >= 0)
776
+                {
777
+                    // Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass
778
+                }
779
+                else
780
+                {
781
+                    $result=$tmpresult;
782
+                }
783
+                if ($result < 0) break;
784
+            }
785
+        }
786
+        closedir($dir_handle);
787
+    }
788
+    else
789
+    {
790
+        // Source directory does not exists
791
+        $result = -2;
792
+    }
793
+
794
+    return $result;
795 795
 }
796 796
 
797 797
 
@@ -813,123 +813,123 @@  discard block
 block discarded – undo
813 813
  */
814 814
 function dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
815 815
 {
816
-	global $user, $db, $conf;
817
-	$result=false;
818
-
819
-	dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
820
-	$srcexists=dol_is_file($srcfile);
821
-	$destexists=dol_is_file($destfile);
822
-
823
-	if (! $srcexists)
824
-	{
825
-		dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
826
-		return false;
827
-	}
828
-
829
-	if ($overwriteifexists || ! $destexists)
830
-	{
831
-		$newpathofsrcfile=dol_osencode($srcfile);
832
-		$newpathofdestfile=dol_osencode($destfile);
833
-
834
-		// Check virus
835
-		$testvirusarray=array();
836
-		if ($testvirus)
837
-		{
838
-			$testvirusarray=dolCheckVirus($newpathofsrcfile);
839
-			if (count($testvirusarray))
840
-			{
841
-				dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
842
-				return false;
843
-			}
844
-		}
845
-
846
-		$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
847
-		if (! $result)
848
-		{
849
-			if ($destexists)
850
-			{
851
-				dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
852
-				// We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
853
-				dol_delete_file($destfile);
854
-				$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
855
-			}
856
-			else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
857
-		}
858
-
859
-		// Move ok
860
-		if ($result && $indexdatabase)
861
-		{
862
-			// Rename entry into ecm database
863
-			$rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $srcfile);
864
-			$rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $destfile);
865
-			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
866
-			{
867
-				$rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
868
-				$rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
869
-				//var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);
870
-
871
-				dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
872
-				include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
873
-
874
-				$ecmfiletarget=new EcmFiles($db);
875
-				$resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
876
-				if ($resultecmtarget > 0)   // An entry for target name already exists for target, we delete it, a new one will be created.
877
-				{
878
-					$ecmfiletarget->delete($user);
879
-				}
880
-
881
-				$ecmfile=new EcmFiles($db);
882
-				$resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
883
-				if ($resultecm > 0)   // If an entry was found for src file, we use it to move entry
884
-				{
885
-					$filename = basename($rel_filetorenameafter);
886
-					$rel_dir = dirname($rel_filetorenameafter);
887
-					$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
888
-					$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
889
-
890
-					$ecmfile->filepath = $rel_dir;
891
-					$ecmfile->filename = $filename;
892
-					$resultecm = $ecmfile->update($user);
893
-				}
894
-				elseif ($resultecm == 0)   // If no entry were found for src files, create/update target file
895
-				{
896
-					$filename = basename($rel_filetorenameafter);
897
-					$rel_dir = dirname($rel_filetorenameafter);
898
-					$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
899
-					$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
900
-
901
-					$ecmfile->filepath = $rel_dir;
902
-					$ecmfile->filename = $filename;
903
-					$ecmfile->label = md5_file(dol_osencode($destfile));        // $destfile is a full path to file
904
-					$ecmfile->fullpath_orig = $srcfile;
905
-					$ecmfile->gen_or_uploaded = 'unknown';
906
-					$ecmfile->description = '';    // indexed content
907
-					$ecmfile->keyword = '';        // keyword content
908
-					$resultecm = $ecmfile->create($user);
909
-					if ($resultecm < 0)
910
-					{
911
-						setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
912
-					}
913
-				}
914
-				elseif ($resultecm < 0)
915
-				{
916
-					setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
917
-				}
918
-
919
-				if ($resultecm > 0) $result=true;
920
-				else $result = false;
921
-			}
922
-		}
923
-
924
-		if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
925
-		$newmaskdec=octdec($newmask);
926
-		// Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
927
-		// to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
928
-		// if ($isdir) $newmaskdec |= octdec('0111');  // Set x bit required for directories
929
-		@chmod($newpathofdestfile, $newmaskdec);
930
-	}
931
-
932
-	return $result;
816
+    global $user, $db, $conf;
817
+    $result=false;
818
+
819
+    dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
820
+    $srcexists=dol_is_file($srcfile);
821
+    $destexists=dol_is_file($destfile);
822
+
823
+    if (! $srcexists)
824
+    {
825
+        dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
826
+        return false;
827
+    }
828
+
829
+    if ($overwriteifexists || ! $destexists)
830
+    {
831
+        $newpathofsrcfile=dol_osencode($srcfile);
832
+        $newpathofdestfile=dol_osencode($destfile);
833
+
834
+        // Check virus
835
+        $testvirusarray=array();
836
+        if ($testvirus)
837
+        {
838
+            $testvirusarray=dolCheckVirus($newpathofsrcfile);
839
+            if (count($testvirusarray))
840
+            {
841
+                dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
842
+                return false;
843
+            }
844
+        }
845
+
846
+        $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
847
+        if (! $result)
848
+        {
849
+            if ($destexists)
850
+            {
851
+                dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
852
+                // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
853
+                dol_delete_file($destfile);
854
+                $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
855
+            }
856
+            else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
857
+        }
858
+
859
+        // Move ok
860
+        if ($result && $indexdatabase)
861
+        {
862
+            // Rename entry into ecm database
863
+            $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $srcfile);
864
+            $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $destfile);
865
+            if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
866
+            {
867
+                $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
868
+                $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
869
+                //var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);
870
+
871
+                dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
872
+                include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
873
+
874
+                $ecmfiletarget=new EcmFiles($db);
875
+                $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
876
+                if ($resultecmtarget > 0)   // An entry for target name already exists for target, we delete it, a new one will be created.
877
+                {
878
+                    $ecmfiletarget->delete($user);
879
+                }
880
+
881
+                $ecmfile=new EcmFiles($db);
882
+                $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
883
+                if ($resultecm > 0)   // If an entry was found for src file, we use it to move entry
884
+                {
885
+                    $filename = basename($rel_filetorenameafter);
886
+                    $rel_dir = dirname($rel_filetorenameafter);
887
+                    $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
888
+                    $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
889
+
890
+                    $ecmfile->filepath = $rel_dir;
891
+                    $ecmfile->filename = $filename;
892
+                    $resultecm = $ecmfile->update($user);
893
+                }
894
+                elseif ($resultecm == 0)   // If no entry were found for src files, create/update target file
895
+                {
896
+                    $filename = basename($rel_filetorenameafter);
897
+                    $rel_dir = dirname($rel_filetorenameafter);
898
+                    $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
899
+                    $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
900
+
901
+                    $ecmfile->filepath = $rel_dir;
902
+                    $ecmfile->filename = $filename;
903
+                    $ecmfile->label = md5_file(dol_osencode($destfile));        // $destfile is a full path to file
904
+                    $ecmfile->fullpath_orig = $srcfile;
905
+                    $ecmfile->gen_or_uploaded = 'unknown';
906
+                    $ecmfile->description = '';    // indexed content
907
+                    $ecmfile->keyword = '';        // keyword content
908
+                    $resultecm = $ecmfile->create($user);
909
+                    if ($resultecm < 0)
910
+                    {
911
+                        setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
912
+                    }
913
+                }
914
+                elseif ($resultecm < 0)
915
+                {
916
+                    setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
917
+                }
918
+
919
+                if ($resultecm > 0) $result=true;
920
+                else $result = false;
921
+            }
922
+        }
923
+
924
+        if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
925
+        $newmaskdec=octdec($newmask);
926
+        // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
927
+        // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
928
+        // if ($isdir) $newmaskdec |= octdec('0111');  // Set x bit required for directories
929
+        @chmod($newpathofdestfile, $newmaskdec);
930
+    }
931
+
932
+    return $result;
933 933
 }
934 934
 
935 935
 /**
@@ -941,10 +941,10 @@  discard block
 block discarded – undo
941 941
  */
942 942
 function dol_unescapefile($filename)
943 943
 {
944
-	// Remove path information and dots around the filename, to prevent uploading
945
-	// into different directories or replacing hidden system files.
946
-	// Also remove control characters and spaces (\x00..\x20) around the filename:
947
-	return trim(basename($filename), ".\x00..\x20");
944
+    // Remove path information and dots around the filename, to prevent uploading
945
+    // into different directories or replacing hidden system files.
946
+    // Also remove control characters and spaces (\x00..\x20) around the filename:
947
+    return trim(basename($filename), ".\x00..\x20");
948 948
 }
949 949
 
950 950
 
@@ -956,22 +956,22 @@  discard block
 block discarded – undo
956 956
  */
957 957
 function dolCheckVirus($src_file)
958 958
 {
959
-	global $conf;
960
-
961
-	if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
962
-	{
963
-		if (! class_exists('AntiVir')) {
964
-			require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
965
-		}
966
-		$antivir=new AntiVir($db);
967
-		$result = $antivir->dol_avscan_file($src_file);
968
-		if ($result < 0)	// If virus or error, we stop here
969
-		{
970
-			$reterrors=$antivir->errors;
971
-			return $reterrors;
972
-		}
973
-	}
974
-	return array();
959
+    global $conf;
960
+
961
+    if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
962
+    {
963
+        if (! class_exists('AntiVir')) {
964
+            require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
965
+        }
966
+        $antivir=new AntiVir($db);
967
+        $result = $antivir->dol_avscan_file($src_file);
968
+        if ($result < 0)	// If virus or error, we stop here
969
+        {
970
+            $reterrors=$antivir->errors;
971
+            return $reterrors;
972
+        }
973
+    }
974
+    return array();
975 975
 }
976 976
 
977 977
 
@@ -995,131 +995,131 @@  discard block
 block discarded – undo
995 995
  */
996 996
 function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile')
997 997
 {
998
-	global $conf, $db, $user, $langs;
999
-	global $object, $hookmanager;
1000
-
1001
-	$reshook=0;
1002
-	$file_name = $dest_file;
1003
-
1004
-	if (empty($nohook))
1005
-	{
1006
-		$reshook=$hookmanager->initHooks(array('fileslib'));
1007
-
1008
-		$parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
1009
-		$reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
1010
-	}
1011
-
1012
-	if (empty($reshook))
1013
-	{
1014
-		// If an upload error has been reported
1015
-		if ($uploaderrorcode)
1016
-		{
1017
-			switch($uploaderrorcode)
1018
-			{
1019
-				case UPLOAD_ERR_INI_SIZE:	// 1
1020
-					return 'ErrorFileSizeTooLarge';
1021
-					break;
1022
-				case UPLOAD_ERR_FORM_SIZE:	// 2
1023
-					return 'ErrorFileSizeTooLarge';
1024
-					break;
1025
-				case UPLOAD_ERR_PARTIAL:	// 3
1026
-					return 'ErrorPartialFile';
1027
-					break;
1028
-				case UPLOAD_ERR_NO_TMP_DIR:	//
1029
-					return 'ErrorNoTmpDir';
1030
-					break;
1031
-				case UPLOAD_ERR_CANT_WRITE:
1032
-					return 'ErrorFailedToWriteInDir';
1033
-					break;
1034
-				case UPLOAD_ERR_EXTENSION:
1035
-					return 'ErrorUploadBlockedByAddon';
1036
-					break;
1037
-				default:
1038
-					break;
1039
-			}
1040
-		}
1041
-
1042
-		// If we need to make a virus scan
1043
-		if (empty($disablevirusscan) && file_exists($src_file))
1044
-		{
1045
-			$checkvirusarray=dolCheckVirus($src_file);
1046
-			if (count($checkvirusarray))
1047
-			{
1048
-			   dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$checkvirusarray), LOG_WARNING);
1049
-			   return 'ErrorFileIsInfectedWithAVirus: '.join(',',$checkvirusarray);
1050
-			}
1051
-		}
1052
-
1053
-		// Security:
1054
-		// Disallow file with some extensions. We rename them.
1055
-		// Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
1056
-		if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
1057
-		{
1058
-			$file_name.= '.noexe';
1059
-		}
1060
-
1061
-		// Security:
1062
-		// We refuse cache files/dirs, upload using .. and pipes into filenames.
1063
-		if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file))
1064
-		{
1065
-			dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
1066
-			return -1;
1067
-		}
1068
-
1069
-		// Security:
1070
-		// On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers.
1071
-		if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file))
1072
-		{
1073
-			dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
1074
-			return -2;
1075
-		}
1076
-	}
1077
-
1078
-	if ($reshook < 0)	// At least one blocking error returned by one hook
1079
-	{
1080
-		$errmsg = join(',', $hookmanager->errors);
1081
-		if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks';	// Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1082
-		return $errmsg;
1083
-	}
1084
-	elseif (empty($reshook))
1085
-	{
1086
-		// The file functions must be in OS filesystem encoding.
1087
-		$src_file_osencoded=dol_osencode($src_file);
1088
-		$file_name_osencoded=dol_osencode($file_name);
1089
-
1090
-		// Check if destination dir is writable
1091
-		if (! is_writable(dirname($file_name_osencoded)))
1092
-		{
1093
-			dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1094
-			return 'ErrorDirNotWritable';
1095
-		}
1096
-
1097
-		// Check if destination file already exists
1098
-		if (! $allowoverwrite)
1099
-		{
1100
-			if (file_exists($file_name_osencoded))
1101
-			{
1102
-				dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1103
-				return 'ErrorFileAlreadyExists';
1104
-			}
1105
-		}
1106
-
1107
-		// Move file
1108
-		$return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1109
-		if ($return)
1110
-		{
1111
-			if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1112
-			dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1113
-			return 1;	// Success
1114
-		}
1115
-		else
1116
-		{
1117
-			dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
1118
-			return -3;	// Unknown error
1119
-		}
1120
-	}
1121
-
1122
-	return 1;	// Success
998
+    global $conf, $db, $user, $langs;
999
+    global $object, $hookmanager;
1000
+
1001
+    $reshook=0;
1002
+    $file_name = $dest_file;
1003
+
1004
+    if (empty($nohook))
1005
+    {
1006
+        $reshook=$hookmanager->initHooks(array('fileslib'));
1007
+
1008
+        $parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
1009
+        $reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
1010
+    }
1011
+
1012
+    if (empty($reshook))
1013
+    {
1014
+        // If an upload error has been reported
1015
+        if ($uploaderrorcode)
1016
+        {
1017
+            switch($uploaderrorcode)
1018
+            {
1019
+                case UPLOAD_ERR_INI_SIZE:	// 1
1020
+                    return 'ErrorFileSizeTooLarge';
1021
+                    break;
1022
+                case UPLOAD_ERR_FORM_SIZE:	// 2
1023
+                    return 'ErrorFileSizeTooLarge';
1024
+                    break;
1025
+                case UPLOAD_ERR_PARTIAL:	// 3
1026
+                    return 'ErrorPartialFile';
1027
+                    break;
1028
+                case UPLOAD_ERR_NO_TMP_DIR:	//
1029
+                    return 'ErrorNoTmpDir';
1030
+                    break;
1031
+                case UPLOAD_ERR_CANT_WRITE:
1032
+                    return 'ErrorFailedToWriteInDir';
1033
+                    break;
1034
+                case UPLOAD_ERR_EXTENSION:
1035
+                    return 'ErrorUploadBlockedByAddon';
1036
+                    break;
1037
+                default:
1038
+                    break;
1039
+            }
1040
+        }
1041
+
1042
+        // If we need to make a virus scan
1043
+        if (empty($disablevirusscan) && file_exists($src_file))
1044
+        {
1045
+            $checkvirusarray=dolCheckVirus($src_file);
1046
+            if (count($checkvirusarray))
1047
+            {
1048
+                dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$checkvirusarray), LOG_WARNING);
1049
+                return 'ErrorFileIsInfectedWithAVirus: '.join(',',$checkvirusarray);
1050
+            }
1051
+        }
1052
+
1053
+        // Security:
1054
+        // Disallow file with some extensions. We rename them.
1055
+        // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
1056
+        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
1057
+        {
1058
+            $file_name.= '.noexe';
1059
+        }
1060
+
1061
+        // Security:
1062
+        // We refuse cache files/dirs, upload using .. and pipes into filenames.
1063
+        if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file))
1064
+        {
1065
+            dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
1066
+            return -1;
1067
+        }
1068
+
1069
+        // Security:
1070
+        // On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers.
1071
+        if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file))
1072
+        {
1073
+            dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
1074
+            return -2;
1075
+        }
1076
+    }
1077
+
1078
+    if ($reshook < 0)	// At least one blocking error returned by one hook
1079
+    {
1080
+        $errmsg = join(',', $hookmanager->errors);
1081
+        if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks';	// Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1082
+        return $errmsg;
1083
+    }
1084
+    elseif (empty($reshook))
1085
+    {
1086
+        // The file functions must be in OS filesystem encoding.
1087
+        $src_file_osencoded=dol_osencode($src_file);
1088
+        $file_name_osencoded=dol_osencode($file_name);
1089
+
1090
+        // Check if destination dir is writable
1091
+        if (! is_writable(dirname($file_name_osencoded)))
1092
+        {
1093
+            dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1094
+            return 'ErrorDirNotWritable';
1095
+        }
1096
+
1097
+        // Check if destination file already exists
1098
+        if (! $allowoverwrite)
1099
+        {
1100
+            if (file_exists($file_name_osencoded))
1101
+            {
1102
+                dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
1103
+                return 'ErrorFileAlreadyExists';
1104
+            }
1105
+        }
1106
+
1107
+        // Move file
1108
+        $return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1109
+        if ($return)
1110
+        {
1111
+            if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1112
+            dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1113
+            return 1;	// Success
1114
+        }
1115
+        else
1116
+        {
1117
+            dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
1118
+            return -3;	// Unknown error
1119
+        }
1120
+    }
1121
+
1122
+    return 1;	// Success
1123 1123
 }
1124 1124
 
1125 1125
 /**
@@ -1138,103 +1138,103 @@  discard block
 block discarded – undo
1138 1138
  */
1139 1139
 function dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
1140 1140
 {
1141
-	global $db, $conf, $user, $langs;
1142
-	global $hookmanager;
1141
+    global $db, $conf, $user, $langs;
1142
+    global $hookmanager;
1143 1143
 
1144
-	// Load translation files required by the page
1144
+    // Load translation files required by the page
1145 1145
     $langs->loadLangs(array('other', 'errors'));
1146 1146
 
1147
-	dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
1148
-
1149
-	// Security:
1150
-	// We refuse transversal using .. and pipes into filenames.
1151
-	if ((! $allowdotdot && preg_match('/\.\./',$file)) || preg_match('/[<>|]/',$file))
1152
-	{
1153
-		dol_syslog("Refused to delete file ".$file, LOG_WARNING);
1154
-		return false;
1155
-	}
1156
-
1157
-	if (empty($nohook))
1158
-	{
1159
-		$hookmanager->initHooks(array('fileslib'));
1160
-
1161
-		$parameters=array(
1162
-				'GET' => $_GET,
1163
-				'file' => $file,
1164
-				'disableglob'=> $disableglob,
1165
-				'nophperrors' => $nophperrors
1166
-		);
1167
-		$reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
1168
-	}
1169
-
1170
-	if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
1171
-	{
1172
-		if ($reshook < 0) return false;
1173
-		return true;
1174
-	}
1175
-	else
1176
-	{
1177
-		$error=0;
1178
-
1179
-		//print "x".$file." ".$disableglob;exit;
1180
-		$file_osencoded=dol_osencode($file);    // New filename encoded in OS filesystem encoding charset
1181
-		if (empty($disableglob) && ! empty($file_osencoded))
1182
-		{
1183
-			$ok=true;
1184
-			$globencoded=str_replace('[','\[',$file_osencoded);
1185
-			$globencoded=str_replace(']','\]',$globencoded);
1186
-			$listofdir=glob($globencoded);
1187
-			if (! empty($listofdir) && is_array($listofdir))
1188
-			{
1189
-				foreach ($listofdir as $filename)
1190
-				{
1191
-					if ($nophperrors) $ok=@unlink($filename);
1192
-					else $ok=unlink($filename);
1193
-					if ($ok)
1194
-					{
1195
-						dol_syslog("Removed file ".$filename, LOG_DEBUG);
1196
-
1197
-						// Delete entry into ecm database
1198
-						$rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filename);
1199
-						if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete))     // If not a tmp file
1200
-						{
1201
-							$rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1202
-
1203
-							if (is_object($db) && $indexdatabase)		// $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1204
-							{
1205
-								dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1206
-								include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1207
-								$ecmfile=new EcmFiles($db);
1208
-								$result = $ecmfile->fetch(0, '', $rel_filetodelete);
1209
-								if ($result >= 0 && $ecmfile->id > 0)
1210
-								{
1211
-									$result = $ecmfile->delete($user);
1212
-								}
1213
-								if ($result < 0)
1214
-								{
1215
-									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1216
-								}
1217
-							}
1218
-						}
1219
-					}
1220
-					else dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1221
-					// TODO Failure to remove can be because file was already removed or because of permission
1222
-					// If error because it does not exists, we should return true, and we should return false if this is a permission problem
1223
-				}
1224
-			}
1225
-			else dol_syslog("No files to delete found", LOG_DEBUG);
1226
-		}
1227
-		else
1228
-		{
1229
-			$ok=false;
1230
-			if ($nophperrors) $ok=@unlink($file_osencoded);
1231
-			else $ok=unlink($file_osencoded);
1232
-			if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
1233
-			else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
1234
-		}
1235
-
1236
-		return $ok;
1237
-	}
1147
+    dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
1148
+
1149
+    // Security:
1150
+    // We refuse transversal using .. and pipes into filenames.
1151
+    if ((! $allowdotdot && preg_match('/\.\./',$file)) || preg_match('/[<>|]/',$file))
1152
+    {
1153
+        dol_syslog("Refused to delete file ".$file, LOG_WARNING);
1154
+        return false;
1155
+    }
1156
+
1157
+    if (empty($nohook))
1158
+    {
1159
+        $hookmanager->initHooks(array('fileslib'));
1160
+
1161
+        $parameters=array(
1162
+                'GET' => $_GET,
1163
+                'file' => $file,
1164
+                'disableglob'=> $disableglob,
1165
+                'nophperrors' => $nophperrors
1166
+        );
1167
+        $reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
1168
+    }
1169
+
1170
+    if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
1171
+    {
1172
+        if ($reshook < 0) return false;
1173
+        return true;
1174
+    }
1175
+    else
1176
+    {
1177
+        $error=0;
1178
+
1179
+        //print "x".$file." ".$disableglob;exit;
1180
+        $file_osencoded=dol_osencode($file);    // New filename encoded in OS filesystem encoding charset
1181
+        if (empty($disableglob) && ! empty($file_osencoded))
1182
+        {
1183
+            $ok=true;
1184
+            $globencoded=str_replace('[','\[',$file_osencoded);
1185
+            $globencoded=str_replace(']','\]',$globencoded);
1186
+            $listofdir=glob($globencoded);
1187
+            if (! empty($listofdir) && is_array($listofdir))
1188
+            {
1189
+                foreach ($listofdir as $filename)
1190
+                {
1191
+                    if ($nophperrors) $ok=@unlink($filename);
1192
+                    else $ok=unlink($filename);
1193
+                    if ($ok)
1194
+                    {
1195
+                        dol_syslog("Removed file ".$filename, LOG_DEBUG);
1196
+
1197
+                        // Delete entry into ecm database
1198
+                        $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filename);
1199
+                        if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete))     // If not a tmp file
1200
+                        {
1201
+                            $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1202
+
1203
+                            if (is_object($db) && $indexdatabase)		// $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1204
+                            {
1205
+                                dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1206
+                                include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1207
+                                $ecmfile=new EcmFiles($db);
1208
+                                $result = $ecmfile->fetch(0, '', $rel_filetodelete);
1209
+                                if ($result >= 0 && $ecmfile->id > 0)
1210
+                                {
1211
+                                    $result = $ecmfile->delete($user);
1212
+                                }
1213
+                                if ($result < 0)
1214
+                                {
1215
+                                    setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
1216
+                                }
1217
+                            }
1218
+                        }
1219
+                    }
1220
+                    else dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1221
+                    // TODO Failure to remove can be because file was already removed or because of permission
1222
+                    // If error because it does not exists, we should return true, and we should return false if this is a permission problem
1223
+                }
1224
+            }
1225
+            else dol_syslog("No files to delete found", LOG_DEBUG);
1226
+        }
1227
+        else
1228
+        {
1229
+            $ok=false;
1230
+            if ($nophperrors) $ok=@unlink($file_osencoded);
1231
+            else $ok=unlink($file_osencoded);
1232
+            if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
1233
+            else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
1234
+        }
1235
+
1236
+        return $ok;
1237
+    }
1238 1238
 }
1239 1239
 
1240 1240
 /**
@@ -1248,16 +1248,16 @@  discard block
 block discarded – undo
1248 1248
  */
1249 1249
 function dol_delete_dir($dir,$nophperrors=0)
1250 1250
 {
1251
-	// Security:
1252
-	// We refuse transversal using .. and pipes into filenames.
1253
-	if (preg_match('/\.\./',$dir) || preg_match('/[<>|]/',$dir))
1254
-	{
1255
-		dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
1256
-		return false;
1257
-	}
1258
-
1259
-	$dir_osencoded=dol_osencode($dir);
1260
-	return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded));
1251
+    // Security:
1252
+    // We refuse transversal using .. and pipes into filenames.
1253
+    if (preg_match('/\.\./',$dir) || preg_match('/[<>|]/',$dir))
1254
+    {
1255
+        dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
1256
+        return false;
1257
+    }
1258
+
1259
+    $dir_osencoded=dol_osencode($dir);
1260
+    return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded));
1261 1261
 }
1262 1262
 
1263 1263
 /**
@@ -1272,44 +1272,44 @@  discard block
 block discarded – undo
1272 1272
  */
1273 1273
 function dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
1274 1274
 {
1275
-	dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG);
1276
-	if (dol_is_dir($dir))
1277
-	{
1278
-		$dir_osencoded=dol_osencode($dir);
1279
-		if ($handle = opendir("$dir_osencoded"))
1280
-		{
1281
-			while (false !== ($item = readdir($handle)))
1282
-			{
1283
-				if (! utf8_check($item)) $item=utf8_encode($item);  // should be useless
1284
-
1285
-				if ($item != "." && $item != "..")
1286
-				{
1287
-					if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item")))
1288
-					{
1289
-						$count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted);
1290
-					}
1291
-					else
1292
-					{
1293
-						$result=dol_delete_file("$dir/$item", 1, $nophperrors);
1294
-						$count++;
1295
-						if ($result) $countdeleted++;
1296
-						//else print 'Error on '.$item."\n";
1297
-					}
1298
-				}
1299
-			}
1300
-			closedir($handle);
1301
-
1302
-			if (empty($onlysub))
1303
-			{
1304
-				$result=dol_delete_dir($dir, $nophperrors);
1305
-				$count++;
1306
-				if ($result) $countdeleted++;
1307
-				//else print 'Error on '.$dir."\n";
1308
-			}
1309
-		}
1310
-	}
1311
-
1312
-	return $count;
1275
+    dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG);
1276
+    if (dol_is_dir($dir))
1277
+    {
1278
+        $dir_osencoded=dol_osencode($dir);
1279
+        if ($handle = opendir("$dir_osencoded"))
1280
+        {
1281
+            while (false !== ($item = readdir($handle)))
1282
+            {
1283
+                if (! utf8_check($item)) $item=utf8_encode($item);  // should be useless
1284
+
1285
+                if ($item != "." && $item != "..")
1286
+                {
1287
+                    if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item")))
1288
+                    {
1289
+                        $count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted);
1290
+                    }
1291
+                    else
1292
+                    {
1293
+                        $result=dol_delete_file("$dir/$item", 1, $nophperrors);
1294
+                        $count++;
1295
+                        if ($result) $countdeleted++;
1296
+                        //else print 'Error on '.$item."\n";
1297
+                    }
1298
+                }
1299
+            }
1300
+            closedir($handle);
1301
+
1302
+            if (empty($onlysub))
1303
+            {
1304
+                $result=dol_delete_dir($dir, $nophperrors);
1305
+                $count++;
1306
+                if ($result) $countdeleted++;
1307
+                //else print 'Error on '.$dir."\n";
1308
+            }
1309
+        }
1310
+    }
1311
+
1312
+    return $count;
1313 1313
 }
1314 1314
 
1315 1315
 
@@ -1323,72 +1323,72 @@  discard block
 block discarded – undo
1323 1323
  */
1324 1324
 function dol_delete_preview($object)
1325 1325
 {
1326
-	global $langs,$conf;
1327
-
1328
-	// Define parent dir of elements
1329
-	$element = $object->element;
1330
-
1331
-	if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->commande->dir_output;
1332
-	elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->facture->dir_output;
1333
-	elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
1334
-	elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1335
-	elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1336
-	elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1337
-	else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1338
-
1339
-	if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
1340
-
1341
-	$refsan = dol_sanitizeFileName($object->ref);
1342
-	$dir = $dir . "/" . $refsan ;
1343
-	$filepreviewnew = $dir . "/" . $refsan . ".pdf_preview.png";
1344
-	$filepreviewnewbis = $dir . "/" . $refsan . ".pdf_preview-0.png";
1345
-	$filepreviewold = $dir . "/" . $refsan . ".pdf.png";
1346
-
1347
-	// For new preview files
1348
-	if (file_exists($filepreviewnew) && is_writable($filepreviewnew))
1349
-	{
1350
-		if (! dol_delete_file($filepreviewnew,1))
1351
-		{
1352
-			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewnew);
1353
-			return 0;
1354
-		}
1355
-	}
1356
-	if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis))
1357
-	{
1358
-		if (! dol_delete_file($filepreviewnewbis,1))
1359
-		{
1360
-			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewnewbis);
1361
-			return 0;
1362
-		}
1363
-	}
1364
-	// For old preview files
1365
-	if (file_exists($filepreviewold) && is_writable($filepreviewold))
1366
-	{
1367
-		if (! dol_delete_file($filepreviewold,1))
1368
-		{
1369
-			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewold);
1370
-			return 0;
1371
-		}
1372
-	}
1373
-	else
1374
-	{
1375
-		$multiple = $filepreviewold . ".";
1376
-		for ($i = 0; $i < 20; $i++)
1377
-		{
1378
-			$preview = $multiple.$i;
1379
-
1380
-			if (file_exists($preview) && is_writable($preview))
1381
-			{
1382
-				if ( ! dol_delete_file($preview,1) )
1383
-				{
1384
-					$object->error=$langs->trans("ErrorFailedToOpenFile",$preview);
1385
-					return 0;
1386
-				}
1387
-			}
1388
-		}
1389
-	}
1390
-
1391
-	return 1;
1326
+    global $langs,$conf;
1327
+
1328
+    // Define parent dir of elements
1329
+    $element = $object->element;
1330
+
1331
+    if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->commande->dir_output;
1332
+    elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->facture->dir_output;
1333
+    elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
1334
+    elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1335
+    elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1336
+    elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1337
+    else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1338
+
1339
+    if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
1340
+
1341
+    $refsan = dol_sanitizeFileName($object->ref);
1342
+    $dir = $dir . "/" . $refsan ;
1343
+    $filepreviewnew = $dir . "/" . $refsan . ".pdf_preview.png";
1344
+    $filepreviewnewbis = $dir . "/" . $refsan . ".pdf_preview-0.png";
1345
+    $filepreviewold = $dir . "/" . $refsan . ".pdf.png";
1346
+
1347
+    // For new preview files
1348
+    if (file_exists($filepreviewnew) && is_writable($filepreviewnew))
1349
+    {
1350
+        if (! dol_delete_file($filepreviewnew,1))
1351
+        {
1352
+            $object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewnew);
1353
+            return 0;
1354
+        }
1355
+    }
1356
+    if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis))
1357
+    {
1358
+        if (! dol_delete_file($filepreviewnewbis,1))
1359
+        {
1360
+            $object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewnewbis);
1361
+            return 0;
1362
+        }
1363
+    }
1364
+    // For old preview files
1365
+    if (file_exists($filepreviewold) && is_writable($filepreviewold))
1366
+    {
1367
+        if (! dol_delete_file($filepreviewold,1))
1368
+        {
1369
+            $object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewold);
1370
+            return 0;
1371
+        }
1372
+    }
1373
+    else
1374
+    {
1375
+        $multiple = $filepreviewold . ".";
1376
+        for ($i = 0; $i < 20; $i++)
1377
+        {
1378
+            $preview = $multiple.$i;
1379
+
1380
+            if (file_exists($preview) && is_writable($preview))
1381
+            {
1382
+                if ( ! dol_delete_file($preview,1) )
1383
+                {
1384
+                    $object->error=$langs->trans("ErrorFailedToOpenFile",$preview);
1385
+                    return 0;
1386
+                }
1387
+            }
1388
+        }
1389
+    }
1390
+
1391
+    return 1;
1392 1392
 }
1393 1393
 
1394 1394
 /**
@@ -1401,71 +1401,71 @@  discard block
 block discarded – undo
1401 1401
  */
1402 1402
 function dol_meta_create($object)
1403 1403
 {
1404
-	global $conf;
1405
-
1406
-	// Create meta file
1407
-	if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0;	// By default, no metafile.
1408
-
1409
-	// Define parent dir of elements
1410
-	$element=$object->element;
1411
-
1412
-	if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->dir_output.'/commande';
1413
-	elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->dir_output.'/facture';
1414
-	elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
1415
-	elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1416
-	elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1417
-	elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1418
-	else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1419
-
1420
-	if ($dir)
1421
-	{
1422
-		$object->fetch_thirdparty();
1423
-
1424
-		$objectref = dol_sanitizeFileName($object->ref);
1425
-		$dir = $dir . "/" . $objectref;
1426
-		$file = $dir . "/" . $objectref . ".meta";
1427
-
1428
-		if (! is_dir($dir))
1429
-		{
1430
-			dol_mkdir($dir);
1431
-		}
1432
-
1433
-		if (is_dir($dir))
1434
-		{
1435
-			$nblignes = count($object->lines);
1436
-			$client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
1437
-			$meta = "REFERENCE=\"" . $object->ref . "\"
1404
+    global $conf;
1405
+
1406
+    // Create meta file
1407
+    if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0;	// By default, no metafile.
1408
+
1409
+    // Define parent dir of elements
1410
+    $element=$object->element;
1411
+
1412
+    if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->dir_output.'/commande';
1413
+    elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->dir_output.'/facture';
1414
+    elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
1415
+    elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1416
+    elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1417
+    elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1418
+    else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1419
+
1420
+    if ($dir)
1421
+    {
1422
+        $object->fetch_thirdparty();
1423
+
1424
+        $objectref = dol_sanitizeFileName($object->ref);
1425
+        $dir = $dir . "/" . $objectref;
1426
+        $file = $dir . "/" . $objectref . ".meta";
1427
+
1428
+        if (! is_dir($dir))
1429
+        {
1430
+            dol_mkdir($dir);
1431
+        }
1432
+
1433
+        if (is_dir($dir))
1434
+        {
1435
+            $nblignes = count($object->lines);
1436
+            $client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
1437
+            $meta = "REFERENCE=\"" . $object->ref . "\"
1438 1438
 			DATE=\"" . dol_print_date($object->date,'') . "\"
1439 1439
 			NB_ITEMS=\"" . $nblignes . "\"
1440 1440
 			CLIENT=\"" . $client . "\"
1441 1441
 			AMOUNT_EXCL_TAX=\"" . $object->total_ht . "\"
1442 1442
 			AMOUNT=\"" . $object->total_ttc . "\"\n";
1443 1443
 
1444
-			for ($i = 0 ; $i < $nblignes ; $i++)
1445
-			{
1446
-				//Pour les articles
1447
-				$meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
1444
+            for ($i = 0 ; $i < $nblignes ; $i++)
1445
+            {
1446
+                //Pour les articles
1447
+                $meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
1448 1448
 				ITEM_" . $i . "_AMOUNT_WO_TAX=\"" . $object->lines[$i]->total_ht . "\"
1449 1449
 				ITEM_" . $i . "_VAT=\"" .$object->lines[$i]->tva_tx . "\"
1450 1450
 				ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n","",nl2br($object->lines[$i]->desc)) . "\"
1451 1451
 				";
1452
-			}
1453
-		}
1454
-
1455
-		$fp = fopen($file,"w");
1456
-		fputs($fp,$meta);
1457
-		fclose($fp);
1458
-		if (! empty($conf->global->MAIN_UMASK))
1459
-		@chmod($file, octdec($conf->global->MAIN_UMASK));
1460
-
1461
-		return 1;
1462
-	}
1463
-	else
1464
-	{
1465
-		dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
1466
-	}
1467
-
1468
-	return 0;
1452
+            }
1453
+        }
1454
+
1455
+        $fp = fopen($file,"w");
1456
+        fputs($fp,$meta);
1457
+        fclose($fp);
1458
+        if (! empty($conf->global->MAIN_UMASK))
1459
+        @chmod($file, octdec($conf->global->MAIN_UMASK));
1460
+
1461
+        return 1;
1462
+    }
1463
+    else
1464
+    {
1465
+        dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
1466
+    }
1467
+
1468
+    return 0;
1469 1469
 }
1470 1470
 
1471 1471
 
@@ -1480,24 +1480,24 @@  discard block
 block discarded – undo
1480 1480
  */
1481 1481
 function dol_init_file_process($pathtoscan='', $trackid='')
1482 1482
 {
1483
-	$listofpaths=array();
1484
-	$listofnames=array();
1485
-	$listofmimes=array();
1486
-
1487
-	if ($pathtoscan)
1488
-	{
1489
-		$listoffiles=dol_dir_list($pathtoscan,'files');
1490
-		foreach($listoffiles as $key => $val)
1491
-		{
1492
-			$listofpaths[]=$val['fullname'];
1493
-			$listofnames[]=$val['name'];
1494
-			$listofmimes[]=dol_mimetype($val['name']);
1495
-		}
1496
-	}
1497
-	$keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1498
-	$_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
1499
-	$_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
1500
-	$_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
1483
+    $listofpaths=array();
1484
+    $listofnames=array();
1485
+    $listofmimes=array();
1486
+
1487
+    if ($pathtoscan)
1488
+    {
1489
+        $listoffiles=dol_dir_list($pathtoscan,'files');
1490
+        foreach($listoffiles as $key => $val)
1491
+        {
1492
+            $listofpaths[]=$val['fullname'];
1493
+            $listofnames[]=$val['name'];
1494
+            $listofmimes[]=dol_mimetype($val['name']);
1495
+        }
1496
+    }
1497
+    $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1498
+    $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
1499
+    $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
1500
+    $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
1501 1501
 }
1502 1502
 
1503 1503
 
@@ -1518,135 +1518,135 @@  discard block
 block discarded – undo
1518 1518
  */
1519 1519
 function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1)
1520 1520
 {
1521
-	global $db,$user,$conf,$langs;
1522
-
1523
-	$res = 0;
1524
-
1525
-	if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
1526
-	{
1527
-		dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
1528
-		if (dol_mkdir($upload_dir) >= 0)
1529
-		{
1530
-			$TFile = $_FILES[$varfiles];
1531
-			if (!is_array($TFile['name']))
1532
-			{
1533
-				foreach ($TFile as $key => &$val)
1534
-				{
1535
-					$val = array($val);
1536
-				}
1537
-			}
1538
-
1539
-			$nbfile = count($TFile['name']);
1540
-			$nbok = 0;
1541
-			for ($i = 0; $i < $nbfile; $i++)
1542
-			{
1543
-				// Define $destfull (path to file including filename) and $destfile (only filename)
1544
-				$destfull=$upload_dir . "/" . $TFile['name'][$i];
1545
-				$destfile=$TFile['name'][$i];
1546
-
1547
-				if ($savingdocmask)
1548
-				{
1549
-					$destfull=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
1550
-					$destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
1551
-				}
1552
-
1553
-				// dol_sanitizeFileName the file name and lowercase extension
1554
-				$info = pathinfo($destfull);
1555
-				$destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].'.'.strtolower($info['extension']));
1556
-				$info = pathinfo($destfile);
1557
-				$destfile = dol_sanitizeFileName($info['filename'].'.'.strtolower($info['extension']));
1558
-
1559
-				$resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles);
1560
-
1561
-				if (is_numeric($resupload) && $resupload > 0)   // $resupload can be 'ErrorFileAlreadyExists'
1562
-				{
1563
-					global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
1564
-
1565
-					include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1566
-
1567
-					// Generate thumbs.
1568
-					if ($generatethumbs)
1569
-					{
1570
-						if (image_format_supported($destfull) == 1)
1571
-						{
1572
-							// Create thumbs
1573
-							// We can't use $object->addThumbs here because there is no $object known
1574
-
1575
-							// Used on logon for example
1576
-							$imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
1577
-							// Create mini thumbs for image (Ratio is near 16/9)
1578
-							// Used on menu or for setup page for example
1579
-							$imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
1580
-						}
1581
-					}
1582
-
1583
-					// Update session
1584
-					if (empty($donotupdatesession))
1585
-					{
1586
-						include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1587
-						$formmail = new FormMail($db);
1588
-						$formmail->trackid = $trackid;
1589
-						$formmail->add_attached_files($destfull, $destfile, $TFile['type'][$i]);
1590
-					}
1591
-
1592
-					// Update table of files
1593
-					if ($donotupdatesession == 1)
1594
-					{
1595
-						$result = addFileIntoDatabaseIndex($upload_dir, basename($destfile), $TFile['name'][$i], 'uploaded', 0);
1596
-						if ($result < 0)
1597
-						{
1598
-							setEventMessages('FailedToAddFileIntoDatabaseIndex', '', 'warnings');
1599
-						}
1600
-					}
1601
-
1602
-					$nbok++;
1603
-				}
1604
-				else
1605
-				{
1606
-					$langs->load("errors");
1607
-					if ($resupload < 0)	// Unknown error
1608
-					{
1609
-						setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
1610
-					}
1611
-					else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
1612
-					{
1613
-						setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
1614
-					}
1615
-					else	// Known error
1616
-					{
1617
-						setEventMessages($langs->trans($resupload), null, 'errors');
1618
-					}
1619
-				}
1620
-			}
1621
-			if ($nbok > 0)
1622
-			{
1623
-				$res = 1;
1624
-				setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
1625
-			}
1626
-		}
1627
-	} elseif ($link) {
1628
-		require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1629
-		$linkObject = new Link($db);
1630
-		$linkObject->entity = $conf->entity;
1631
-		$linkObject->url = $link;
1632
-		$linkObject->objecttype = GETPOST('objecttype', 'alpha');
1633
-		$linkObject->objectid = GETPOST('objectid', 'int');
1634
-		$linkObject->label = GETPOST('label', 'alpha');
1635
-		$res = $linkObject->create($user);
1636
-		$langs->load('link');
1637
-		if ($res > 0) {
1638
-			setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
1639
-		} else {
1640
-			setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
1641
-		}
1642
-	}
1643
-	else
1644
-	{
1645
-		$langs->load("errors");
1646
-		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
1647
-	}
1648
-
1649
-	return $res;
1521
+    global $db,$user,$conf,$langs;
1522
+
1523
+    $res = 0;
1524
+
1525
+    if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
1526
+    {
1527
+        dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
1528
+        if (dol_mkdir($upload_dir) >= 0)
1529
+        {
1530
+            $TFile = $_FILES[$varfiles];
1531
+            if (!is_array($TFile['name']))
1532
+            {
1533
+                foreach ($TFile as $key => &$val)
1534
+                {
1535
+                    $val = array($val);
1536
+                }
1537
+            }
1538
+
1539
+            $nbfile = count($TFile['name']);
1540
+            $nbok = 0;
1541
+            for ($i = 0; $i < $nbfile; $i++)
1542
+            {
1543
+                // Define $destfull (path to file including filename) and $destfile (only filename)
1544
+                $destfull=$upload_dir . "/" . $TFile['name'][$i];
1545
+                $destfile=$TFile['name'][$i];
1546
+
1547
+                if ($savingdocmask)
1548
+                {
1549
+                    $destfull=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
1550
+                    $destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
1551
+                }
1552
+
1553
+                // dol_sanitizeFileName the file name and lowercase extension
1554
+                $info = pathinfo($destfull);
1555
+                $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].'.'.strtolower($info['extension']));
1556
+                $info = pathinfo($destfile);
1557
+                $destfile = dol_sanitizeFileName($info['filename'].'.'.strtolower($info['extension']));
1558
+
1559
+                $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles);
1560
+
1561
+                if (is_numeric($resupload) && $resupload > 0)   // $resupload can be 'ErrorFileAlreadyExists'
1562
+                {
1563
+                    global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
1564
+
1565
+                    include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1566
+
1567
+                    // Generate thumbs.
1568
+                    if ($generatethumbs)
1569
+                    {
1570
+                        if (image_format_supported($destfull) == 1)
1571
+                        {
1572
+                            // Create thumbs
1573
+                            // We can't use $object->addThumbs here because there is no $object known
1574
+
1575
+                            // Used on logon for example
1576
+                            $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
1577
+                            // Create mini thumbs for image (Ratio is near 16/9)
1578
+                            // Used on menu or for setup page for example
1579
+                            $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
1580
+                        }
1581
+                    }
1582
+
1583
+                    // Update session
1584
+                    if (empty($donotupdatesession))
1585
+                    {
1586
+                        include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1587
+                        $formmail = new FormMail($db);
1588
+                        $formmail->trackid = $trackid;
1589
+                        $formmail->add_attached_files($destfull, $destfile, $TFile['type'][$i]);
1590
+                    }
1591
+
1592
+                    // Update table of files
1593
+                    if ($donotupdatesession == 1)
1594
+                    {
1595
+                        $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile), $TFile['name'][$i], 'uploaded', 0);
1596
+                        if ($result < 0)
1597
+                        {
1598
+                            setEventMessages('FailedToAddFileIntoDatabaseIndex', '', 'warnings');
1599
+                        }
1600
+                    }
1601
+
1602
+                    $nbok++;
1603
+                }
1604
+                else
1605
+                {
1606
+                    $langs->load("errors");
1607
+                    if ($resupload < 0)	// Unknown error
1608
+                    {
1609
+                        setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
1610
+                    }
1611
+                    else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
1612
+                    {
1613
+                        setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
1614
+                    }
1615
+                    else	// Known error
1616
+                    {
1617
+                        setEventMessages($langs->trans($resupload), null, 'errors');
1618
+                    }
1619
+                }
1620
+            }
1621
+            if ($nbok > 0)
1622
+            {
1623
+                $res = 1;
1624
+                setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
1625
+            }
1626
+        }
1627
+    } elseif ($link) {
1628
+        require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1629
+        $linkObject = new Link($db);
1630
+        $linkObject->entity = $conf->entity;
1631
+        $linkObject->url = $link;
1632
+        $linkObject->objecttype = GETPOST('objecttype', 'alpha');
1633
+        $linkObject->objectid = GETPOST('objectid', 'int');
1634
+        $linkObject->label = GETPOST('label', 'alpha');
1635
+        $res = $linkObject->create($user);
1636
+        $langs->load('link');
1637
+        if ($res > 0) {
1638
+            setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
1639
+        } else {
1640
+            setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
1641
+        }
1642
+    }
1643
+    else
1644
+    {
1645
+        $langs->load("errors");
1646
+        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
1647
+    }
1648
+
1649
+    return $res;
1650 1650
 }
1651 1651
 
1652 1652
 
@@ -1662,41 +1662,41 @@  discard block
 block discarded – undo
1662 1662
  */
1663 1663
 function dol_remove_file_process($filenb,$donotupdatesession=0,$donotdeletefile=1,$trackid='')
1664 1664
 {
1665
-	global $db,$user,$conf,$langs,$_FILES;
1666
-
1667
-	$keytodelete=$filenb;
1668
-	$keytodelete--;
1669
-
1670
-	$listofpaths=array();
1671
-	$listofnames=array();
1672
-	$listofmimes=array();
1673
-	$keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1674
-	if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
1675
-	if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
1676
-	if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
1677
-
1678
-	if ($keytodelete >= 0)
1679
-	{
1680
-		$pathtodelete=$listofpaths[$keytodelete];
1681
-		$filetodelete=$listofnames[$keytodelete];
1682
-		if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);  // The delete of ecm database is inside the function dol_delete_file
1683
-		else $result=0;
1684
-		if ($result >= 0)
1685
-		{
1686
-			if (empty($donotdeletefile))
1687
-			{
1688
-				$langs->load("other");
1689
-				setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
1690
-			}
1691
-			if (empty($donotupdatesession))
1692
-			{
1693
-				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1694
-				$formmail = new FormMail($db);
1695
-				$formmail->trackid = $trackid;
1696
-				$formmail->remove_attached_files($keytodelete);
1697
-			}
1698
-		}
1699
-	}
1665
+    global $db,$user,$conf,$langs,$_FILES;
1666
+
1667
+    $keytodelete=$filenb;
1668
+    $keytodelete--;
1669
+
1670
+    $listofpaths=array();
1671
+    $listofnames=array();
1672
+    $listofmimes=array();
1673
+    $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1674
+    if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
1675
+    if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
1676
+    if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
1677
+
1678
+    if ($keytodelete >= 0)
1679
+    {
1680
+        $pathtodelete=$listofpaths[$keytodelete];
1681
+        $filetodelete=$listofnames[$keytodelete];
1682
+        if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);  // The delete of ecm database is inside the function dol_delete_file
1683
+        else $result=0;
1684
+        if ($result >= 0)
1685
+        {
1686
+            if (empty($donotdeletefile))
1687
+            {
1688
+                $langs->load("other");
1689
+                setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
1690
+            }
1691
+            if (empty($donotupdatesession))
1692
+            {
1693
+                include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1694
+                $formmail = new FormMail($db);
1695
+                $formmail->trackid = $trackid;
1696
+                $formmail->remove_attached_files($keytodelete);
1697
+            }
1698
+        }
1699
+    }
1700 1700
 }
1701 1701
 
1702 1702
 
@@ -1714,41 +1714,41 @@  discard block
 block discarded – undo
1714 1714
  */
1715 1715
 function addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0)
1716 1716
 {
1717
-	global $db, $user;
1718
-
1719
-	$result = 0;
1720
-
1721
-	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1722
-
1723
-	if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
1724
-	{
1725
-		$filename = basename($file);
1726
-		$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1727
-		$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1728
-
1729
-		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1730
-		$ecmfile=new EcmFiles($db);
1731
-		$ecmfile->filepath = $rel_dir;
1732
-		$ecmfile->filename = $filename;
1733
-		$ecmfile->label = md5_file(dol_osencode($dir.'/'.$file));	// MD5 of file content
1734
-		$ecmfile->fullpath_orig = $fullpathorig;
1735
-		$ecmfile->gen_or_uploaded = $mode;
1736
-		$ecmfile->description = '';    // indexed content
1737
-		$ecmfile->keyword = '';        // keyword content
1738
-		if ($setsharekey)
1739
-		{
1740
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1741
-			$ecmfile->share = getRandomPassword(true);
1742
-		}
1743
-
1744
-		$result = $ecmfile->create($user);
1745
-		if ($result < 0)
1746
-		{
1747
-			dol_syslog($ecmfile->error);
1748
-		}
1749
-	}
1750
-
1751
-	return $result;
1717
+    global $db, $user;
1718
+
1719
+    $result = 0;
1720
+
1721
+    $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1722
+
1723
+    if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
1724
+    {
1725
+        $filename = basename($file);
1726
+        $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1727
+        $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1728
+
1729
+        include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1730
+        $ecmfile=new EcmFiles($db);
1731
+        $ecmfile->filepath = $rel_dir;
1732
+        $ecmfile->filename = $filename;
1733
+        $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file));	// MD5 of file content
1734
+        $ecmfile->fullpath_orig = $fullpathorig;
1735
+        $ecmfile->gen_or_uploaded = $mode;
1736
+        $ecmfile->description = '';    // indexed content
1737
+        $ecmfile->keyword = '';        // keyword content
1738
+        if ($setsharekey)
1739
+        {
1740
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1741
+            $ecmfile->share = getRandomPassword(true);
1742
+        }
1743
+
1744
+        $result = $ecmfile->create($user);
1745
+        if ($result < 0)
1746
+        {
1747
+            dol_syslog($ecmfile->error);
1748
+        }
1749
+    }
1750
+
1751
+    return $result;
1752 1752
 }
1753 1753
 
1754 1754
 
@@ -1762,48 +1762,48 @@  discard block
 block discarded – undo
1762 1762
  */
1763 1763
 function deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded')
1764 1764
 {
1765
-	global $conf, $db, $user;
1766
-
1767
-	$error = 0;
1768
-
1769
-	if (empty($dir))
1770
-	{
1771
-		dol_syslog("deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
1772
-		return -1;
1773
-	}
1774
-
1775
-	$db->begin();
1776
-
1777
-	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1778
-
1779
-	$filename = basename($file);
1780
-	$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1781
-	$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1782
-
1783
-	if (! $error)
1784
-	{
1785
-		$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'ecm_files';
1786
-		$sql.= ' WHERE entity = '.$conf->entity;
1787
-		$sql.= " AND filepath = '" . $db->escape($rel_dir) . "'";
1788
-		if ($file) $sql.= " AND filename = '" . $db->escape($file) . "'";
1789
-		if ($mode) $sql.= " AND gen_or_uploaded = '" . $db->escape($mode) . "'";
1790
-
1791
-		$resql = $db->query($sql);
1792
-		if (!$resql)
1793
-		{
1794
-			$error++;
1795
-			dol_syslog(__METHOD__ . ' ' . $db->lasterror(), LOG_ERR);
1796
-		}
1797
-	}
1798
-
1799
-	// Commit or rollback
1800
-	if ($error) {
1801
-		$db->rollback();
1802
-		return - 1 * $error;
1803
-	} else {
1804
-		$db->commit();
1805
-		return 1;
1806
-	}
1765
+    global $conf, $db, $user;
1766
+
1767
+    $error = 0;
1768
+
1769
+    if (empty($dir))
1770
+    {
1771
+        dol_syslog("deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
1772
+        return -1;
1773
+    }
1774
+
1775
+    $db->begin();
1776
+
1777
+    $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1778
+
1779
+    $filename = basename($file);
1780
+    $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1781
+    $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1782
+
1783
+    if (! $error)
1784
+    {
1785
+        $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'ecm_files';
1786
+        $sql.= ' WHERE entity = '.$conf->entity;
1787
+        $sql.= " AND filepath = '" . $db->escape($rel_dir) . "'";
1788
+        if ($file) $sql.= " AND filename = '" . $db->escape($file) . "'";
1789
+        if ($mode) $sql.= " AND gen_or_uploaded = '" . $db->escape($mode) . "'";
1790
+
1791
+        $resql = $db->query($sql);
1792
+        if (!$resql)
1793
+        {
1794
+            $error++;
1795
+            dol_syslog(__METHOD__ . ' ' . $db->lasterror(), LOG_ERR);
1796
+        }
1797
+    }
1798
+
1799
+    // Commit or rollback
1800
+    if ($error) {
1801
+        $db->rollback();
1802
+        return - 1 * $error;
1803
+    } else {
1804
+        $db->commit();
1805
+        return 1;
1806
+    }
1807 1807
 }
1808 1808
 
1809 1809
 
@@ -1818,51 +1818,51 @@  discard block
 block discarded – undo
1818 1818
  */
1819 1819
 function dol_convert_file($fileinput, $ext='png', $fileoutput='')
1820 1820
 {
1821
-	global $langs;
1822
-
1823
-	if (class_exists('Imagick'))
1824
-	{
1825
-		$image=new Imagick();
1826
-		try {
1827
-			$ret = $image->readImage($fileinput);
1828
-		} catch(Exception $e) {
1829
-			dol_syslog("Failed to read image using Imagick. Try to install package 'apt-get install ghostscript'.", LOG_WARNING);
1830
-			return 0;
1831
-		}
1832
-		if ($ret)
1833
-		{
1834
-			$ret = $image->setImageFormat($ext);
1835
-			if ($ret)
1836
-			{
1837
-				if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
1838
-
1839
-				$count = $image->getNumberImages();
1840
-
1841
-				if (! dol_is_file($fileoutput) || is_writeable($fileoutput))
1842
-				{
1843
-					$ret = $image->writeImages($fileoutput, true);
1844
-				}
1845
-				else
1846
-				{
1847
-					dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
1848
-				}
1849
-				if ($ret) return $count;
1850
-				else return -3;
1851
-			}
1852
-			else
1853
-			{
1854
-				return -2;
1855
-			}
1856
-		}
1857
-		else
1858
-		{
1859
-			return -1;
1860
-		}
1861
-	}
1862
-	else
1863
-	{
1864
-		return 0;
1865
-	}
1821
+    global $langs;
1822
+
1823
+    if (class_exists('Imagick'))
1824
+    {
1825
+        $image=new Imagick();
1826
+        try {
1827
+            $ret = $image->readImage($fileinput);
1828
+        } catch(Exception $e) {
1829
+            dol_syslog("Failed to read image using Imagick. Try to install package 'apt-get install ghostscript'.", LOG_WARNING);
1830
+            return 0;
1831
+        }
1832
+        if ($ret)
1833
+        {
1834
+            $ret = $image->setImageFormat($ext);
1835
+            if ($ret)
1836
+            {
1837
+                if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
1838
+
1839
+                $count = $image->getNumberImages();
1840
+
1841
+                if (! dol_is_file($fileoutput) || is_writeable($fileoutput))
1842
+                {
1843
+                    $ret = $image->writeImages($fileoutput, true);
1844
+                }
1845
+                else
1846
+                {
1847
+                    dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
1848
+                }
1849
+                if ($ret) return $count;
1850
+                else return -3;
1851
+            }
1852
+            else
1853
+            {
1854
+                return -2;
1855
+            }
1856
+        }
1857
+        else
1858
+        {
1859
+            return -1;
1860
+        }
1861
+    }
1862
+    else
1863
+    {
1864
+        return 0;
1865
+    }
1866 1866
 }
1867 1867
 
1868 1868
 
@@ -1876,48 +1876,48 @@  discard block
 block discarded – undo
1876 1876
  */
1877 1877
 function dol_compress_file($inputfile, $outputfile, $mode="gz")
1878 1878
 {
1879
-	$foundhandler=0;
1880
-
1881
-	try
1882
-	{
1883
-		$data = implode("", file(dol_osencode($inputfile)));
1884
-		if ($mode == 'gz')     { $foundhandler=1; $compressdata = gzencode($data, 9); }
1885
-		elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
1886
-		elseif ($mode == 'zip')
1887
-		{
1888
-			if (defined('ODTPHP_PATHTOPCLZIP'))
1889
-			{
1890
-				$foundhandler=1;
1891
-
1892
-				include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
1893
-				$archive = new PclZip($outputfile);
1894
-				$archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
1895
-				//$archive->add($inputfile);
1896
-				return 1;
1897
-			}
1898
-		}
1899
-
1900
-		if ($foundhandler)
1901
-		{
1902
-			$fp = fopen($outputfile, "w");
1903
-			fwrite($fp, $compressdata);
1904
-			fclose($fp);
1905
-			return 1;
1906
-		}
1907
-		else
1908
-		{
1909
-			dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
1910
-			return -2;
1911
-		}
1912
-	}
1913
-	catch (Exception $e)
1914
-	{
1915
-		global $langs, $errormsg;
1916
-		$langs->load("errors");
1917
-		dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
1918
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir");
1919
-		return -1;
1920
-	}
1879
+    $foundhandler=0;
1880
+
1881
+    try
1882
+    {
1883
+        $data = implode("", file(dol_osencode($inputfile)));
1884
+        if ($mode == 'gz')     { $foundhandler=1; $compressdata = gzencode($data, 9); }
1885
+        elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
1886
+        elseif ($mode == 'zip')
1887
+        {
1888
+            if (defined('ODTPHP_PATHTOPCLZIP'))
1889
+            {
1890
+                $foundhandler=1;
1891
+
1892
+                include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
1893
+                $archive = new PclZip($outputfile);
1894
+                $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
1895
+                //$archive->add($inputfile);
1896
+                return 1;
1897
+            }
1898
+        }
1899
+
1900
+        if ($foundhandler)
1901
+        {
1902
+            $fp = fopen($outputfile, "w");
1903
+            fwrite($fp, $compressdata);
1904
+            fclose($fp);
1905
+            return 1;
1906
+        }
1907
+        else
1908
+        {
1909
+            dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
1910
+            return -2;
1911
+        }
1912
+    }
1913
+    catch (Exception $e)
1914
+    {
1915
+        global $langs, $errormsg;
1916
+        $langs->load("errors");
1917
+        dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
1918
+        $errormsg=$langs->trans("ErrorFailedToWriteInDir");
1919
+        return -1;
1920
+    }
1921 1921
 }
1922 1922
 
1923 1923
 /**
@@ -1929,54 +1929,54 @@  discard block
 block discarded – undo
1929 1929
  */
1930 1930
 function dol_uncompress($inputfile,$outputdir)
1931 1931
 {
1932
-	global $langs;
1933
-
1934
-	if (defined('ODTPHP_PATHTOPCLZIP'))
1935
-	{
1936
-		dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
1937
-		include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
1938
-		$archive = new PclZip($inputfile);
1939
-		$result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
1940
-		//var_dump($result);
1941
-		if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
1942
-		else
1943
-		{
1944
-			$ok=1; $errmsg='';
1945
-			// Loop on each file to check result for unzipping file
1946
-			foreach($result as $key => $val)
1947
-			{
1948
-				if ($val['status'] == 'path_creation_fail')
1949
-				{
1950
-					$langs->load("errors");
1951
-					$ok=0;
1952
-					$errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']);
1953
-					break;
1954
-				}
1955
-			}
1956
-
1957
-			if ($ok) return array();
1958
-			else return array('error'=>$errmsg);
1959
-		}
1960
-	}
1961
-
1962
-	if (class_exists('ZipArchive'))
1963
-	{
1964
-		dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
1965
-		$zip = new ZipArchive;
1966
-		$res = $zip->open($inputfile);
1967
-		if ($res === true)
1968
-		{
1969
-			$zip->extractTo($outputdir.'/');
1970
-			$zip->close();
1971
-			return array();
1972
-		}
1973
-		else
1974
-		{
1975
-			return array('error'=>'ErrUnzipFails');
1976
-		}
1977
-	}
1978
-
1979
-	return array('error'=>'ErrNoZipEngine');
1932
+    global $langs;
1933
+
1934
+    if (defined('ODTPHP_PATHTOPCLZIP'))
1935
+    {
1936
+        dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
1937
+        include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
1938
+        $archive = new PclZip($inputfile);
1939
+        $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
1940
+        //var_dump($result);
1941
+        if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
1942
+        else
1943
+        {
1944
+            $ok=1; $errmsg='';
1945
+            // Loop on each file to check result for unzipping file
1946
+            foreach($result as $key => $val)
1947
+            {
1948
+                if ($val['status'] == 'path_creation_fail')
1949
+                {
1950
+                    $langs->load("errors");
1951
+                    $ok=0;
1952
+                    $errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']);
1953
+                    break;
1954
+                }
1955
+            }
1956
+
1957
+            if ($ok) return array();
1958
+            else return array('error'=>$errmsg);
1959
+        }
1960
+    }
1961
+
1962
+    if (class_exists('ZipArchive'))
1963
+    {
1964
+        dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
1965
+        $zip = new ZipArchive;
1966
+        $res = $zip->open($inputfile);
1967
+        if ($res === true)
1968
+        {
1969
+            $zip->extractTo($outputdir.'/');
1970
+            $zip->close();
1971
+            return array();
1972
+        }
1973
+        else
1974
+        {
1975
+            return array('error'=>'ErrUnzipFails');
1976
+        }
1977
+    }
1978
+
1979
+    return array('error'=>'ErrNoZipEngine');
1980 1980
 }
1981 1981
 
1982 1982
 
@@ -1990,25 +1990,25 @@  discard block
 block discarded – undo
1990 1990
  */
1991 1991
 function dol_compress_dir($inputdir, $outputfile, $mode="zip")
1992 1992
 {
1993
-	$foundhandler=0;
1994
-
1995
-	dol_syslog("Try to zip dir ".$inputdir." into ".$outputdir." mode=".$mode);
1996
-
1997
-	if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile)))
1998
-	{
1999
-		global $langs, $errormsg;
2000
-		$langs->load("errors");
2001
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile);
2002
-		return -3;
2003
-	}
2004
-
2005
-	try
2006
-	{
2007
-		if ($mode == 'gz')     { $foundhandler=0; }
2008
-		elseif ($mode == 'bz') { $foundhandler=0; }
2009
-		elseif ($mode == 'zip')
2010
-		{
2011
-			/*if (defined('ODTPHP_PATHTOPCLZIP'))
1993
+    $foundhandler=0;
1994
+
1995
+    dol_syslog("Try to zip dir ".$inputdir." into ".$outputdir." mode=".$mode);
1996
+
1997
+    if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile)))
1998
+    {
1999
+        global $langs, $errormsg;
2000
+        $langs->load("errors");
2001
+        $errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile);
2002
+        return -3;
2003
+    }
2004
+
2005
+    try
2006
+    {
2007
+        if ($mode == 'gz')     { $foundhandler=0; }
2008
+        elseif ($mode == 'bz') { $foundhandler=0; }
2009
+        elseif ($mode == 'zip')
2010
+        {
2011
+            /*if (defined('ODTPHP_PATHTOPCLZIP'))
2012 2012
             {
2013 2013
                 $foundhandler=0;        // TODO implement this
2014 2014
 
@@ -2019,61 +2019,61 @@  discard block
 block discarded – undo
2019 2019
                 return 1;
2020 2020
             }
2021 2021
             else*/
2022
-			if (class_exists('ZipArchive'))
2023
-			{
2024
-				$foundhandler=1;
2025
-
2026
-				// Initialize archive object
2027
-				$zip = new ZipArchive();
2028
-				$result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2029
-
2030
-				// Create recursive directory iterator
2031
-				/** @var SplFileInfo[] $files */
2032
-				$files = new RecursiveIteratorIterator(
2033
-					new RecursiveDirectoryIterator($inputdir),
2034
-					RecursiveIteratorIterator::LEAVES_ONLY
2035
-					);
2036
-
2037
-				foreach ($files as $name => $file)
2038
-				{
2039
-					// Skip directories (they would be added automatically)
2040
-					if (!$file->isDir())
2041
-					{
2042
-						// Get real and relative path for current file
2043
-						$filePath = $file->getRealPath();
2044
-						$relativePath = substr($filePath, strlen($inputdir) + 1);
2045
-
2046
-						// Add current file to archive
2047
-						$zip->addFile($filePath, $relativePath);
2048
-					}
2049
-				}
2050
-
2051
-				// Zip archive will be created only after closing object
2052
-				$zip->close();
2053
-
2054
-				return 1;
2055
-			}
2056
-		}
2057
-
2058
-		if (! $foundhandler)
2059
-		{
2060
-			dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
2061
-			return -2;
2062
-		}
2063
-		else
2064
-		{
2065
-			return 0;
2066
-		}
2067
-	}
2068
-	catch (Exception $e)
2069
-	{
2070
-		global $langs, $errormsg;
2071
-		$langs->load("errors");
2072
-		dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
2073
-		dol_syslog($e->getMessage(), LOG_ERR);
2074
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile);
2075
-		return -1;
2076
-	}
2022
+            if (class_exists('ZipArchive'))
2023
+            {
2024
+                $foundhandler=1;
2025
+
2026
+                // Initialize archive object
2027
+                $zip = new ZipArchive();
2028
+                $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
2029
+
2030
+                // Create recursive directory iterator
2031
+                /** @var SplFileInfo[] $files */
2032
+                $files = new RecursiveIteratorIterator(
2033
+                    new RecursiveDirectoryIterator($inputdir),
2034
+                    RecursiveIteratorIterator::LEAVES_ONLY
2035
+                    );
2036
+
2037
+                foreach ($files as $name => $file)
2038
+                {
2039
+                    // Skip directories (they would be added automatically)
2040
+                    if (!$file->isDir())
2041
+                    {
2042
+                        // Get real and relative path for current file
2043
+                        $filePath = $file->getRealPath();
2044
+                        $relativePath = substr($filePath, strlen($inputdir) + 1);
2045
+
2046
+                        // Add current file to archive
2047
+                        $zip->addFile($filePath, $relativePath);
2048
+                    }
2049
+                }
2050
+
2051
+                // Zip archive will be created only after closing object
2052
+                $zip->close();
2053
+
2054
+                return 1;
2055
+            }
2056
+        }
2057
+
2058
+        if (! $foundhandler)
2059
+        {
2060
+            dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
2061
+            return -2;
2062
+        }
2063
+        else
2064
+        {
2065
+            return 0;
2066
+        }
2067
+    }
2068
+    catch (Exception $e)
2069
+    {
2070
+        global $langs, $errormsg;
2071
+        $langs->load("errors");
2072
+        dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
2073
+        dol_syslog($e->getMessage(), LOG_ERR);
2074
+        $errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile);
2075
+        return -1;
2076
+    }
2077 2077
 }
2078 2078
 
2079 2079
 
@@ -2090,8 +2090,8 @@  discard block
 block discarded – undo
2090 2090
  */
2091 2091
 function dol_most_recent_file($dir,$regexfilter='',$excludefilter=array('(\.meta|_preview.*\.png)$','^\.'),$nohook=false,$mode='')
2092 2092
 {
2093
-	$tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,$mode,$nohook);
2094
-	return $tmparray[0];
2093
+    $tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,$mode,$nohook);
2094
+    return $tmparray[0];
2095 2095
 }
2096 2096
 
2097 2097
 /**
@@ -2108,770 +2108,770 @@  discard block
 block discarded – undo
2108 2108
  */
2109 2109
 function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser='', $refname='', $mode='read')
2110 2110
 {
2111
-	global $conf, $db, $user;
2112
-	global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2113
-
2114
-	if (! is_object($fuser)) $fuser=$user;
2115
-
2116
-	if (empty($modulepart)) return 'ErrorBadParameter';
2117
-	if (empty($entity))
2118
-	{
2119
-		if (empty($conf->multicompany->enabled)) $entity=1;
2120
-		else $entity=0;
2121
-	}
2122
-	// Fix modulepart
2123
-	if ($modulepart == 'users') $modulepart='user';
2124
-
2125
-	dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
2126
-	// We define $accessallowed and $sqlprotectagainstexternals
2127
-	$accessallowed=0;
2128
-	$sqlprotectagainstexternals='';
2129
-	$ret=array();
2130
-
2131
-	// Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
2132
-	if (empty($refname)) $refname=basename(dirname($original_file)."/");
2133
-
2134
-	$relative_original_file = $original_file;
2135
-
2136
-	// Define possible keys to use for permission check
2137
-	$lire='lire'; $read='read'; $download='download';
2138
-	if ($mode == 'write')
2139
-	{
2140
-		$lire='creer'; $read='write'; $download='upload';
2141
-	}
2142
-
2143
-	// Wrapping for miscellaneous medias files
2144
-	if ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
2145
-	{
2146
-		if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2147
-		$accessallowed=1;
2148
-		$original_file=$conf->medias->multidir_output[$entity].'/'.$original_file;
2149
-	}
2150
-	// Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
2151
-	elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root))
2152
-	{
2153
-		$accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
2154
-		$original_file=$dolibarr_main_data_root.'/'.$original_file;
2155
-	}
2156
-	// Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
2157
-	elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root))
2158
-	{
2159
-		// Dir for custom dirs
2160
-		$tmp=explode(',', $dolibarr_main_document_root_alt);
2161
-		$dirins = $tmp[0];
2162
-
2163
-		$accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
2164
-		$original_file=$dirins.'/'.$original_file;
2165
-	}
2166
-	// Wrapping for some images
2167
-	elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output))
2168
-	{
2169
-		$accessallowed=1;
2170
-		$original_file=$conf->mycompany->dir_output.'/'.$original_file;
2171
-	}
2172
-	// Wrapping for users photos
2173
-	elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output))
2174
-	{
2175
-		$accessallowed=1;
2176
-		$original_file=$conf->user->dir_output.'/'.$original_file;
2177
-	}
2178
-	// Wrapping for members photos
2179
-	elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output))
2180
-	{
2181
-		$accessallowed=1;
2182
-		$original_file=$conf->adherent->dir_output.'/'.$original_file;
2183
-	}
2184
-	// Wrapping pour les apercu factures
2185
-	elseif ($modulepart == 'apercufacture' && !empty($conf->facture->dir_output))
2186
-	{
2187
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2188
-		$original_file=$conf->facture->dir_output.'/'.$original_file;
2189
-	}
2190
-	// Wrapping pour les apercu propal
2191
-	elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity]))
2192
-	{
2193
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2194
-		$original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2195
-	}
2196
-	// Wrapping pour les apercu commande
2197
-	elseif ($modulepart == 'apercucommande' && !empty($conf->commande->dir_output))
2198
-	{
2199
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2200
-		$original_file=$conf->commande->dir_output.'/'.$original_file;
2201
-	}
2202
-	// Wrapping pour les apercu intervention
2203
-	elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output))
2204
-	{
2205
-		if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1;
2206
-		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2207
-	}
2208
-	// Wrapping pour les apercu conat
2209
-	elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output))
2210
-	{
2211
-		if ($fuser->rights->contrat->{$lire}) $accessallowed=1;
2212
-		$original_file=$conf->contrat->dir_output.'/'.$original_file;
2213
-	}
2214
-	// Wrapping pour les apercu supplier proposal
2215
-	elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
2216
-	{
2217
-		if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1;
2218
-		$original_file=$conf->supplier_proposal->dir_output.'/'.$original_file;
2219
-	}
2220
-	// Wrapping pour les apercu supplier order
2221
-	elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
2222
-	{
2223
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2224
-		$original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2225
-	}
2226
-	// Wrapping pour les apercu supplier invoice
2227
-	elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
2228
-	{
2229
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2230
-		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2231
-	}
2232
-	// Wrapping pour les apercu supplier invoice
2233
-	elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output))
2234
-	{
2235
-		if ($fuser->rights->expensereport->{$lire}) $accessallowed=1;
2236
-		$original_file=$conf->expensereport->dir_output.'/'.$original_file;
2237
-	}
2238
-	// Wrapping pour les images des stats propales
2239
-	elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity]))
2240
-	{
2241
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2242
-		$original_file=$conf->propal->multidir_temp[$entity].'/'.$original_file;
2243
-	}
2244
-	// Wrapping pour les images des stats commandes
2245
-	elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
2246
-	{
2247
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2248
-		$original_file=$conf->commande->dir_temp.'/'.$original_file;
2249
-	}
2250
-	elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
2251
-	{
2252
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2253
-		$original_file=$conf->fournisseur->commande->dir_temp.'/'.$original_file;
2254
-	}
2255
-	// Wrapping pour les images des stats factures
2256
-	elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
2257
-	{
2258
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2259
-		$original_file=$conf->facture->dir_temp.'/'.$original_file;
2260
-	}
2261
-	elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
2262
-	{
2263
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2264
-		$original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file;
2265
-	}
2266
-	// Wrapping pour les images des stats expeditions
2267
-	elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
2268
-	{
2269
-		if ($fuser->rights->expedition->{$lire}) $accessallowed=1;
2270
-		$original_file=$conf->expedition->dir_temp.'/'.$original_file;
2271
-	}
2272
-	// Wrapping pour les images des stats expeditions
2273
-	elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
2274
-	{
2275
-		if ($fuser->rights->deplacement->{$lire}) $accessallowed=1;
2276
-		$original_file=$conf->deplacement->dir_temp.'/'.$original_file;
2277
-	}
2278
-	// Wrapping pour les images des stats expeditions
2279
-	elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
2280
-	{
2281
-		if ($fuser->rights->adherent->{$lire}) $accessallowed=1;
2282
-		$original_file=$conf->adherent->dir_temp.'/'.$original_file;
2283
-	}
2284
-	// Wrapping pour les images des stats produits
2285
-	elseif (preg_match('/^productstats_/i',$modulepart) && !empty($conf->product->dir_temp))
2286
-	{
2287
-		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed=1;
2288
-		$original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
2289
-	}
2290
-	// Wrapping for taxes
2291
-	elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
2292
-	{
2293
-		if ($fuser->rights->tax->charges->{$lire}) $accessallowed=1;
2294
-		$original_file=$conf->tax->dir_output.'/'.$original_file;
2295
-	}
2296
-	// Wrapping for events
2297
-	elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2298
-	{
2299
-		if ($fuser->rights->agenda->myactions->{$read}) $accessallowed=1;
2300
-		$original_file=$conf->agenda->dir_output.'/'.$original_file;
2301
-	}
2302
-	// Wrapping for categories
2303
-	elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
2304
-	{
2305
-		if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2306
-		if ($fuser->rights->categorie->{$lire}) $accessallowed=1;
2307
-		$original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
2308
-	}
2309
-	// Wrapping pour les prelevements
2310
-	elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
2311
-	{
2312
-		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i',$original_file)) $accessallowed=1;
2313
-		$original_file=$conf->prelevement->dir_output.'/'.$original_file;
2314
-	}
2315
-	// Wrapping pour les graph energie
2316
-	elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp))
2317
-	{
2318
-		$accessallowed=1;
2319
-		$original_file=$conf->stock->dir_temp.'/'.$original_file;
2320
-	}
2321
-	// Wrapping pour les graph fournisseurs
2322
-	elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp))
2323
-	{
2324
-		$accessallowed=1;
2325
-		$original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
2326
-	}
2327
-	// Wrapping pour les graph des produits
2328
-	elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp))
2329
-	{
2330
-		$accessallowed=1;
2331
-		$original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
2332
-	}
2333
-	// Wrapping pour les code barre
2334
-	elseif ($modulepart == 'barcode')
2335
-	{
2336
-		$accessallowed=1;
2337
-		// If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
2338
-		//$original_file=$conf->barcode->dir_temp.'/'.$original_file;
2339
-		$original_file='';
2340
-	}
2341
-	// Wrapping pour les icones de background des mailings
2342
-	elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp))
2343
-	{
2344
-		$accessallowed=1;
2345
-		$original_file=$conf->mailing->dir_temp.'/'.$original_file;
2346
-	}
2347
-	// Wrapping pour le scanner
2348
-	elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2349
-	{
2350
-		$accessallowed=1;
2351
-		$original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2352
-	}
2353
-	// Wrapping pour les images fckeditor
2354
-	elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output))
2355
-	{
2356
-		$accessallowed=1;
2357
-		$original_file=$conf->fckeditor->dir_output.'/'.$original_file;
2358
-	}
2359
-
2360
-	// Wrapping for users
2361
-	else if ($modulepart == 'user' && !empty($conf->user->dir_output))
2362
-	{
2363
-		$canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2364
-		if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card
2365
-		if ($canreaduser || preg_match('/^specimen/i',$original_file))
2366
-		{
2367
-			$accessallowed=1;
2368
-		}
2369
-		$original_file=$conf->user->dir_output.'/'.$original_file;
2370
-	}
2371
-
2372
-	// Wrapping for third parties
2373
-	else if (($modulepart == 'company' || $modulepart == 'societe') && !empty($conf->societe->dir_output))
2374
-	{
2375
-		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2376
-		if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i',$original_file))
2377
-		{
2378
-			$accessallowed=1;
2379
-		}
2380
-		$original_file=$conf->societe->multidir_output[$entity].'/'.$original_file;
2381
-		$sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")";
2382
-	}
2383
-
2384
-	// Wrapping for contact
2385
-	else if ($modulepart == 'contact' && !empty($conf->societe->dir_output))
2386
-	{
2387
-		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2388
-		if ($fuser->rights->societe->{$lire})
2389
-		{
2390
-			$accessallowed=1;
2391
-		}
2392
-		$original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file;
2393
-	}
2394
-
2395
-	// Wrapping for invoices
2396
-	else if (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->dir_output))
2397
-	{
2398
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2399
-		{
2400
-			$accessallowed=1;
2401
-		}
2402
-		$original_file=$conf->facture->dir_output.'/'.$original_file;
2403
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2404
-	}
2405
-	// Wrapping for mass actions
2406
-	else if ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity]))
2407
-	{
2408
-		if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i',$original_file))
2409
-		{
2410
-			$accessallowed=1;
2411
-		}
2412
-		$original_file=$conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2413
-	}
2414
-	else if ($modulepart == 'massfilesarea_orders')
2415
-	{
2416
-		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2417
-		{
2418
-			$accessallowed=1;
2419
-		}
2420
-		$original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2421
-	}
2422
-	else if ($modulepart == 'massfilesarea_invoices')
2423
-	{
2424
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2425
-		{
2426
-			$accessallowed=1;
2427
-		}
2428
-		$original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2429
-	}
2430
-	else if ($modulepart == 'massfilesarea_expensereport')
2431
-	{
2432
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2433
-		{
2434
-			$accessallowed=1;
2435
-		}
2436
-		$original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2437
-	}
2438
-	else if ($modulepart == 'massfilesarea_interventions')
2439
-	{
2440
-		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2441
-		{
2442
-			$accessallowed=1;
2443
-		}
2444
-		$original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2445
-	}
2446
-	else if ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
2447
-	{
2448
-		if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i',$original_file))
2449
-		{
2450
-			$accessallowed=1;
2451
-		}
2452
-		$original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2453
-	}
2454
-	else if ($modulepart == 'massfilesarea_supplier_order')
2455
-	{
2456
-		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2457
-		{
2458
-			$accessallowed=1;
2459
-		}
2460
-		$original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2461
-	}
2462
-	else if ($modulepart == 'massfilesarea_supplier_invoice')
2463
-	{
2464
-		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2465
-		{
2466
-			$accessallowed=1;
2467
-		}
2468
-		$original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2469
-	}
2470
-	else if ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output))
2471
-	{
2472
-		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2473
-		{
2474
-			$accessallowed=1;
2475
-		}
2476
-		$original_file=$conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2477
-	}
2478
-
2479
-	// Wrapping for interventions
2480
-	else if (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output))
2481
-	{
2482
-		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2483
-		{
2484
-			$accessallowed=1;
2485
-		}
2486
-		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2487
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2488
-	}
2489
-
2490
-	// Wrapping pour les deplacements et notes de frais
2491
-	else if ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output))
2492
-	{
2493
-		if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i',$original_file))
2494
-		{
2495
-			$accessallowed=1;
2496
-		}
2497
-		$original_file=$conf->deplacement->dir_output.'/'.$original_file;
2498
-		//$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2499
-	}
2500
-	// Wrapping pour les propales
2501
-	else if (($modulepart == 'propal' || $modulepart == 'propale') && !empty($conf->propal->multidir_output[$entity]))
2502
-	{
2503
-		if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i',$original_file))
2504
-		{
2505
-			$accessallowed=1;
2506
-		}
2507
-		$original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2508
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2509
-	}
2510
-
2511
-	// Wrapping pour les commandes
2512
-	else if (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->dir_output))
2513
-	{
2514
-		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2515
-		{
2516
-			$accessallowed=1;
2517
-		}
2518
-		$original_file=$conf->commande->dir_output.'/'.$original_file;
2519
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2520
-	}
2521
-
2522
-	// Wrapping pour les projets
2523
-	else if ($modulepart == 'project' && !empty($conf->projet->dir_output))
2524
-	{
2525
-		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2526
-		{
2527
-			$accessallowed=1;
2528
-		}
2529
-		$original_file=$conf->projet->dir_output.'/'.$original_file;
2530
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2531
-	}
2532
-	else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
2533
-	{
2534
-		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2535
-		{
2536
-			$accessallowed=1;
2537
-		}
2538
-		$original_file=$conf->projet->dir_output.'/'.$original_file;
2539
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2540
-	}
2541
-
2542
-	// Wrapping pour les commandes fournisseurs
2543
-	else if (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output))
2544
-	{
2545
-		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2546
-		{
2547
-			$accessallowed=1;
2548
-		}
2549
-		$original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2550
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2551
-	}
2552
-
2553
-	// Wrapping pour les factures fournisseurs
2554
-	else if (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output))
2555
-	{
2556
-		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2557
-		{
2558
-			$accessallowed=1;
2559
-		}
2560
-		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2561
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE facnumber='".$db->escape($refname)."' AND entity=".$conf->entity;
2562
-	}
2563
-	// Wrapping pour les rapport de paiements
2564
-	else if ($modulepart == 'supplier_payment')
2565
-	{
2566
-		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2567
-		{
2568
-			$accessallowed=1;
2569
-		}
2570
-		$original_file=$conf->fournisseur->payment->dir_output.'/'.$original_file;
2571
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2572
-	}
2573
-
2574
-	// Wrapping pour les rapport de paiements
2575
-	else if ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output))
2576
-	{
2577
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2578
-		{
2579
-			$accessallowed=1;
2580
-		}
2581
-		if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2582
-		else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
2583
-	}
2584
-
2585
-	// Wrapping for accounting exports
2586
-	else if ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output))
2587
-	{
2588
-		if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i',$original_file))
2589
-		{
2590
-			$accessallowed=1;
2591
-		}
2592
-		$original_file=$conf->accounting->dir_output.'/'.$original_file;
2593
-	}
2594
-
2595
-	// Wrapping pour les expedition
2596
-	else if ($modulepart == 'expedition' && !empty($conf->expedition->dir_output))
2597
-	{
2598
-		if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i',$original_file))
2599
-		{
2600
-			$accessallowed=1;
2601
-		}
2602
-		$original_file=$conf->expedition->dir_output."/sending/".$original_file;
2603
-	}
2604
-	// Wrapping pour les bons de livraison
2605
-	else if ($modulepart == 'livraison' && !empty($conf->expedition->dir_output))
2606
-	{
2607
-		if ($fuser->rights->expedition->livraison->{$lire} || preg_match('/^specimen/i',$original_file))
2608
-		{
2609
-			$accessallowed=1;
2610
-		}
2611
-		$original_file=$conf->expedition->dir_output."/receipt/".$original_file;
2612
-	}
2613
-
2614
-	// Wrapping pour les actions
2615
-	else if ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2616
-	{
2617
-		if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i',$original_file))
2618
-		{
2619
-			$accessallowed=1;
2620
-		}
2621
-		$original_file=$conf->agenda->dir_output.'/'.$original_file;
2622
-	}
2623
-
2624
-	// Wrapping pour les actions
2625
-	else if ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp))
2626
-	{
2627
-		if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i',$original_file))
2628
-		{
2629
-			$accessallowed=1;
2630
-		}
2631
-		$original_file = $conf->agenda->dir_temp."/".$original_file;
2632
-	}
2633
-
2634
-	// Wrapping pour les produits et services
2635
-	else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
2636
-	{
2637
-		if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2638
-		if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i',$original_file))
2639
-		{
2640
-			$accessallowed=1;
2641
-		}
2642
-		if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
2643
-		elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
2644
-	}
2645
-
2646
-	// Wrapping pour les lots produits
2647
-	else if ($modulepart == 'product_batch' || $modulepart == 'produitlot')
2648
-	{
2649
-		if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2650
-		if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i',$original_file))
2651
-		{
2652
-			$accessallowed=1;
2653
-		}
2654
-		if (! empty($conf->productbatch->enabled)) $original_file=$conf->productbatch->multidir_output[$entity].'/'.$original_file;
2655
-	}
2656
-
2657
-	// Wrapping pour les contrats
2658
-	else if ($modulepart == 'contract' && !empty($conf->contrat->dir_output))
2659
-	{
2660
-		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2661
-		{
2662
-			$accessallowed=1;
2663
-		}
2664
-		$original_file=$conf->contrat->dir_output.'/'.$original_file;
2665
-		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
2666
-	}
2667
-
2668
-	// Wrapping pour les dons
2669
-	else if ($modulepart == 'donation' && !empty($conf->don->dir_output))
2670
-	{
2671
-		if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i',$original_file))
2672
-		{
2673
-			$accessallowed=1;
2674
-		}
2675
-		$original_file=$conf->don->dir_output.'/'.$original_file;
2676
-	}
2677
-
2678
-	// Wrapping pour les dons
2679
-	else if ($modulepart == 'dolresource' && !empty($conf->resource->dir_output))
2680
-	{
2681
-		if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i',$original_file))
2682
-		{
2683
-			$accessallowed=1;
2684
-		}
2685
-		$original_file=$conf->resource->dir_output.'/'.$original_file;
2686
-	}
2687
-
2688
-	// Wrapping pour les remises de cheques
2689
-	else if ($modulepart == 'remisecheque' && !empty($conf->banque->dir_output))
2690
-	{
2691
-		if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i',$original_file))
2692
-		{
2693
-			$accessallowed=1;
2694
-		}
2695
-
2696
-		$original_file=$conf->bank->dir_output.'/checkdeposits/'.$original_file;		// original_file should contains relative path so include the get_exdir result
2697
-	}
2698
-
2699
-	// Wrapping for bank
2700
-	else if ($modulepart == 'bank' && !empty($conf->bank->dir_output))
2701
-	{
2702
-		if ($fuser->rights->banque->{$lire})
2703
-		{
2704
-			$accessallowed=1;
2705
-		}
2706
-		$original_file=$conf->bank->dir_output.'/'.$original_file;
2707
-	}
2708
-
2709
-	// Wrapping for export module
2710
-	else if ($modulepart == 'export' && !empty($conf->export->dir_temp))
2711
-	{
2712
-		// Aucun test necessaire car on force le rep de download sur
2713
-		// le rep export qui est propre a l'utilisateur
2714
-		$accessallowed=1;
2715
-		$original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
2716
-	}
2717
-
2718
-	// Wrapping for import module
2719
-	else if ($modulepart == 'import' && !empty($conf->import->dir_temp))
2720
-	{
2721
-		$accessallowed=1;
2722
-		$original_file=$conf->import->dir_temp.'/'.$original_file;
2723
-	}
2724
-
2725
-	// Wrapping pour l'editeur wysiwyg
2726
-	else if ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output))
2727
-	{
2728
-		$accessallowed=1;
2729
-		$original_file=$conf->fckeditor->dir_output.'/'.$original_file;
2730
-	}
2731
-
2732
-	// Wrapping for backups
2733
-	else if ($modulepart == 'systemtools' && !empty($conf->admin->dir_output))
2734
-	{
2735
-		if ($fuser->admin) $accessallowed=1;
2736
-		$original_file=$conf->admin->dir_output.'/'.$original_file;
2737
-	}
2738
-
2739
-	// Wrapping for upload file test
2740
-	else if ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp))
2741
-	{
2742
-		if ($fuser->admin) $accessallowed=1;
2743
-		$original_file=$conf->admin->dir_temp.'/'.$original_file;
2744
-	}
2745
-
2746
-	// Wrapping pour BitTorrent
2747
-	else if ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output))
2748
-	{
2749
-		$accessallowed=1;
2750
-		$dir='files';
2751
-		if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
2752
-		$original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
2753
-	}
2754
-
2755
-	// Wrapping pour Foundation module
2756
-	else if ($modulepart == 'member' && !empty($conf->adherent->dir_output))
2757
-	{
2758
-		if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i',$original_file))
2759
-		{
2760
-			$accessallowed=1;
2761
-		}
2762
-		$original_file=$conf->adherent->dir_output.'/'.$original_file;
2763
-	}
2764
-
2765
-	// Wrapping for Scanner
2766
-	else if ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2767
-	{
2768
-		$accessallowed=1;
2769
-		$original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2770
-	}
2771
-
2772
-	// GENERIC Wrapping
2773
-	// If modulepart=module_user_temp	Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
2774
-	// If modulepart=module_temp		Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
2775
-	// If modulepart=module_user		Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
2776
-	// If modulepart=module				Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
2777
-	else
2778
-	{
2779
-		if (preg_match('/^specimen/i',$original_file))	$accessallowed=1;    // If link to a file called specimen. Test must be done before changing $original_file int full path.
2780
-		if ($fuser->admin) $accessallowed=1;    // If user is admin
2781
-
2782
-		// Define $accessallowed
2783
-		if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
2784
-		{
2785
-			if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
2786
-			{
2787
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2788
-				exit;
2789
-			}
2790
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2791
-			$original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
2792
-		}
2793
-		else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
2794
-		{
2795
-			if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
2796
-			{
2797
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2798
-				exit;
2799
-			}
2800
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2801
-			$original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
2802
-		}
2803
-		else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
2804
-		{
2805
-			if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
2806
-			{
2807
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2808
-				exit;
2809
-			}
2810
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2811
-			$original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
2812
-		}
2813
-		else if (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg))
2814
-		{
2815
-			if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
2816
-			{
2817
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2818
-				exit;
2819
-			}
2820
-			if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file))
2821
-			{
2822
-				$accessallowed=1;
2823
-			}
2824
-			$original_file=$conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2825
-		}
2826
-		else
2827
-		{
2828
-			if (empty($conf->$modulepart->dir_output))	// modulepart not supported
2829
-			{
2830
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2831
-				exit;
2832
-			}
2833
-
2834
-			$perm=GETPOST('perm');
2835
-			$subperm=GETPOST('subperm');
2836
-			if ($perm || $subperm)
2837
-			{
2838
-				if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
2839
-				$original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2840
-			}
2841
-			else
2842
-			{
2843
-				if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed=1;
2844
-				$original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2845
-			}
2846
-		}
2847
-
2848
-		// For modules who wants to manage different levels of permissions for documents
2849
-		$subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
2850
-		if (! empty($conf->global->$subPermCategoryConstName))
2851
-		{
2852
-			$subPermCategory = $conf->global->$subPermCategoryConstName;
2853
-			if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download})))
2854
-			{
2855
-				$accessallowed=1;
2856
-			}
2857
-		}
2858
-
2859
-		// Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
2860
-		$sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
2861
-		if (! empty($conf->global->$sqlProtectConstName))	// If module want to define its own $sqlprotectagainstexternals
2862
-		{
2863
-			// Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2864
-			eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
2865
-		}
2866
-	}
2867
-
2868
-	$ret = array(
2869
-		'accessallowed' => $accessallowed,
2870
-		'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
2871
-		'original_file'=>$original_file
2872
-	);
2873
-
2874
-	return $ret;
2111
+    global $conf, $db, $user;
2112
+    global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2113
+
2114
+    if (! is_object($fuser)) $fuser=$user;
2115
+
2116
+    if (empty($modulepart)) return 'ErrorBadParameter';
2117
+    if (empty($entity))
2118
+    {
2119
+        if (empty($conf->multicompany->enabled)) $entity=1;
2120
+        else $entity=0;
2121
+    }
2122
+    // Fix modulepart
2123
+    if ($modulepart == 'users') $modulepart='user';
2124
+
2125
+    dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
2126
+    // We define $accessallowed and $sqlprotectagainstexternals
2127
+    $accessallowed=0;
2128
+    $sqlprotectagainstexternals='';
2129
+    $ret=array();
2130
+
2131
+    // Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
2132
+    if (empty($refname)) $refname=basename(dirname($original_file)."/");
2133
+
2134
+    $relative_original_file = $original_file;
2135
+
2136
+    // Define possible keys to use for permission check
2137
+    $lire='lire'; $read='read'; $download='download';
2138
+    if ($mode == 'write')
2139
+    {
2140
+        $lire='creer'; $read='write'; $download='upload';
2141
+    }
2142
+
2143
+    // Wrapping for miscellaneous medias files
2144
+    if ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
2145
+    {
2146
+        if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2147
+        $accessallowed=1;
2148
+        $original_file=$conf->medias->multidir_output[$entity].'/'.$original_file;
2149
+    }
2150
+    // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
2151
+    elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root))
2152
+    {
2153
+        $accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
2154
+        $original_file=$dolibarr_main_data_root.'/'.$original_file;
2155
+    }
2156
+    // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
2157
+    elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root))
2158
+    {
2159
+        // Dir for custom dirs
2160
+        $tmp=explode(',', $dolibarr_main_document_root_alt);
2161
+        $dirins = $tmp[0];
2162
+
2163
+        $accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
2164
+        $original_file=$dirins.'/'.$original_file;
2165
+    }
2166
+    // Wrapping for some images
2167
+    elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output))
2168
+    {
2169
+        $accessallowed=1;
2170
+        $original_file=$conf->mycompany->dir_output.'/'.$original_file;
2171
+    }
2172
+    // Wrapping for users photos
2173
+    elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output))
2174
+    {
2175
+        $accessallowed=1;
2176
+        $original_file=$conf->user->dir_output.'/'.$original_file;
2177
+    }
2178
+    // Wrapping for members photos
2179
+    elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output))
2180
+    {
2181
+        $accessallowed=1;
2182
+        $original_file=$conf->adherent->dir_output.'/'.$original_file;
2183
+    }
2184
+    // Wrapping pour les apercu factures
2185
+    elseif ($modulepart == 'apercufacture' && !empty($conf->facture->dir_output))
2186
+    {
2187
+        if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2188
+        $original_file=$conf->facture->dir_output.'/'.$original_file;
2189
+    }
2190
+    // Wrapping pour les apercu propal
2191
+    elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity]))
2192
+    {
2193
+        if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2194
+        $original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2195
+    }
2196
+    // Wrapping pour les apercu commande
2197
+    elseif ($modulepart == 'apercucommande' && !empty($conf->commande->dir_output))
2198
+    {
2199
+        if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2200
+        $original_file=$conf->commande->dir_output.'/'.$original_file;
2201
+    }
2202
+    // Wrapping pour les apercu intervention
2203
+    elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output))
2204
+    {
2205
+        if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1;
2206
+        $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2207
+    }
2208
+    // Wrapping pour les apercu conat
2209
+    elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output))
2210
+    {
2211
+        if ($fuser->rights->contrat->{$lire}) $accessallowed=1;
2212
+        $original_file=$conf->contrat->dir_output.'/'.$original_file;
2213
+    }
2214
+    // Wrapping pour les apercu supplier proposal
2215
+    elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
2216
+    {
2217
+        if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1;
2218
+        $original_file=$conf->supplier_proposal->dir_output.'/'.$original_file;
2219
+    }
2220
+    // Wrapping pour les apercu supplier order
2221
+    elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
2222
+    {
2223
+        if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2224
+        $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2225
+    }
2226
+    // Wrapping pour les apercu supplier invoice
2227
+    elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
2228
+    {
2229
+        if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2230
+        $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2231
+    }
2232
+    // Wrapping pour les apercu supplier invoice
2233
+    elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output))
2234
+    {
2235
+        if ($fuser->rights->expensereport->{$lire}) $accessallowed=1;
2236
+        $original_file=$conf->expensereport->dir_output.'/'.$original_file;
2237
+    }
2238
+    // Wrapping pour les images des stats propales
2239
+    elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity]))
2240
+    {
2241
+        if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2242
+        $original_file=$conf->propal->multidir_temp[$entity].'/'.$original_file;
2243
+    }
2244
+    // Wrapping pour les images des stats commandes
2245
+    elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
2246
+    {
2247
+        if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2248
+        $original_file=$conf->commande->dir_temp.'/'.$original_file;
2249
+    }
2250
+    elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
2251
+    {
2252
+        if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2253
+        $original_file=$conf->fournisseur->commande->dir_temp.'/'.$original_file;
2254
+    }
2255
+    // Wrapping pour les images des stats factures
2256
+    elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
2257
+    {
2258
+        if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2259
+        $original_file=$conf->facture->dir_temp.'/'.$original_file;
2260
+    }
2261
+    elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
2262
+    {
2263
+        if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2264
+        $original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file;
2265
+    }
2266
+    // Wrapping pour les images des stats expeditions
2267
+    elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
2268
+    {
2269
+        if ($fuser->rights->expedition->{$lire}) $accessallowed=1;
2270
+        $original_file=$conf->expedition->dir_temp.'/'.$original_file;
2271
+    }
2272
+    // Wrapping pour les images des stats expeditions
2273
+    elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
2274
+    {
2275
+        if ($fuser->rights->deplacement->{$lire}) $accessallowed=1;
2276
+        $original_file=$conf->deplacement->dir_temp.'/'.$original_file;
2277
+    }
2278
+    // Wrapping pour les images des stats expeditions
2279
+    elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
2280
+    {
2281
+        if ($fuser->rights->adherent->{$lire}) $accessallowed=1;
2282
+        $original_file=$conf->adherent->dir_temp.'/'.$original_file;
2283
+    }
2284
+    // Wrapping pour les images des stats produits
2285
+    elseif (preg_match('/^productstats_/i',$modulepart) && !empty($conf->product->dir_temp))
2286
+    {
2287
+        if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed=1;
2288
+        $original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
2289
+    }
2290
+    // Wrapping for taxes
2291
+    elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
2292
+    {
2293
+        if ($fuser->rights->tax->charges->{$lire}) $accessallowed=1;
2294
+        $original_file=$conf->tax->dir_output.'/'.$original_file;
2295
+    }
2296
+    // Wrapping for events
2297
+    elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2298
+    {
2299
+        if ($fuser->rights->agenda->myactions->{$read}) $accessallowed=1;
2300
+        $original_file=$conf->agenda->dir_output.'/'.$original_file;
2301
+    }
2302
+    // Wrapping for categories
2303
+    elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
2304
+    {
2305
+        if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2306
+        if ($fuser->rights->categorie->{$lire}) $accessallowed=1;
2307
+        $original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
2308
+    }
2309
+    // Wrapping pour les prelevements
2310
+    elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
2311
+    {
2312
+        if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i',$original_file)) $accessallowed=1;
2313
+        $original_file=$conf->prelevement->dir_output.'/'.$original_file;
2314
+    }
2315
+    // Wrapping pour les graph energie
2316
+    elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp))
2317
+    {
2318
+        $accessallowed=1;
2319
+        $original_file=$conf->stock->dir_temp.'/'.$original_file;
2320
+    }
2321
+    // Wrapping pour les graph fournisseurs
2322
+    elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp))
2323
+    {
2324
+        $accessallowed=1;
2325
+        $original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
2326
+    }
2327
+    // Wrapping pour les graph des produits
2328
+    elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp))
2329
+    {
2330
+        $accessallowed=1;
2331
+        $original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
2332
+    }
2333
+    // Wrapping pour les code barre
2334
+    elseif ($modulepart == 'barcode')
2335
+    {
2336
+        $accessallowed=1;
2337
+        // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
2338
+        //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
2339
+        $original_file='';
2340
+    }
2341
+    // Wrapping pour les icones de background des mailings
2342
+    elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp))
2343
+    {
2344
+        $accessallowed=1;
2345
+        $original_file=$conf->mailing->dir_temp.'/'.$original_file;
2346
+    }
2347
+    // Wrapping pour le scanner
2348
+    elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2349
+    {
2350
+        $accessallowed=1;
2351
+        $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2352
+    }
2353
+    // Wrapping pour les images fckeditor
2354
+    elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output))
2355
+    {
2356
+        $accessallowed=1;
2357
+        $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
2358
+    }
2359
+
2360
+    // Wrapping for users
2361
+    else if ($modulepart == 'user' && !empty($conf->user->dir_output))
2362
+    {
2363
+        $canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2364
+        if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card
2365
+        if ($canreaduser || preg_match('/^specimen/i',$original_file))
2366
+        {
2367
+            $accessallowed=1;
2368
+        }
2369
+        $original_file=$conf->user->dir_output.'/'.$original_file;
2370
+    }
2371
+
2372
+    // Wrapping for third parties
2373
+    else if (($modulepart == 'company' || $modulepart == 'societe') && !empty($conf->societe->dir_output))
2374
+    {
2375
+        if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2376
+        if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i',$original_file))
2377
+        {
2378
+            $accessallowed=1;
2379
+        }
2380
+        $original_file=$conf->societe->multidir_output[$entity].'/'.$original_file;
2381
+        $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")";
2382
+    }
2383
+
2384
+    // Wrapping for contact
2385
+    else if ($modulepart == 'contact' && !empty($conf->societe->dir_output))
2386
+    {
2387
+        if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2388
+        if ($fuser->rights->societe->{$lire})
2389
+        {
2390
+            $accessallowed=1;
2391
+        }
2392
+        $original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file;
2393
+    }
2394
+
2395
+    // Wrapping for invoices
2396
+    else if (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->dir_output))
2397
+    {
2398
+        if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2399
+        {
2400
+            $accessallowed=1;
2401
+        }
2402
+        $original_file=$conf->facture->dir_output.'/'.$original_file;
2403
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2404
+    }
2405
+    // Wrapping for mass actions
2406
+    else if ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity]))
2407
+    {
2408
+        if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i',$original_file))
2409
+        {
2410
+            $accessallowed=1;
2411
+        }
2412
+        $original_file=$conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2413
+    }
2414
+    else if ($modulepart == 'massfilesarea_orders')
2415
+    {
2416
+        if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2417
+        {
2418
+            $accessallowed=1;
2419
+        }
2420
+        $original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2421
+    }
2422
+    else if ($modulepart == 'massfilesarea_invoices')
2423
+    {
2424
+        if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2425
+        {
2426
+            $accessallowed=1;
2427
+        }
2428
+        $original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2429
+    }
2430
+    else if ($modulepart == 'massfilesarea_expensereport')
2431
+    {
2432
+        if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2433
+        {
2434
+            $accessallowed=1;
2435
+        }
2436
+        $original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2437
+    }
2438
+    else if ($modulepart == 'massfilesarea_interventions')
2439
+    {
2440
+        if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2441
+        {
2442
+            $accessallowed=1;
2443
+        }
2444
+        $original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2445
+    }
2446
+    else if ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
2447
+    {
2448
+        if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i',$original_file))
2449
+        {
2450
+            $accessallowed=1;
2451
+        }
2452
+        $original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2453
+    }
2454
+    else if ($modulepart == 'massfilesarea_supplier_order')
2455
+    {
2456
+        if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2457
+        {
2458
+            $accessallowed=1;
2459
+        }
2460
+        $original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2461
+    }
2462
+    else if ($modulepart == 'massfilesarea_supplier_invoice')
2463
+    {
2464
+        if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2465
+        {
2466
+            $accessallowed=1;
2467
+        }
2468
+        $original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2469
+    }
2470
+    else if ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output))
2471
+    {
2472
+        if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2473
+        {
2474
+            $accessallowed=1;
2475
+        }
2476
+        $original_file=$conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2477
+    }
2478
+
2479
+    // Wrapping for interventions
2480
+    else if (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output))
2481
+    {
2482
+        if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2483
+        {
2484
+            $accessallowed=1;
2485
+        }
2486
+        $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2487
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2488
+    }
2489
+
2490
+    // Wrapping pour les deplacements et notes de frais
2491
+    else if ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output))
2492
+    {
2493
+        if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i',$original_file))
2494
+        {
2495
+            $accessallowed=1;
2496
+        }
2497
+        $original_file=$conf->deplacement->dir_output.'/'.$original_file;
2498
+        //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2499
+    }
2500
+    // Wrapping pour les propales
2501
+    else if (($modulepart == 'propal' || $modulepart == 'propale') && !empty($conf->propal->multidir_output[$entity]))
2502
+    {
2503
+        if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i',$original_file))
2504
+        {
2505
+            $accessallowed=1;
2506
+        }
2507
+        $original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2508
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2509
+    }
2510
+
2511
+    // Wrapping pour les commandes
2512
+    else if (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->dir_output))
2513
+    {
2514
+        if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2515
+        {
2516
+            $accessallowed=1;
2517
+        }
2518
+        $original_file=$conf->commande->dir_output.'/'.$original_file;
2519
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2520
+    }
2521
+
2522
+    // Wrapping pour les projets
2523
+    else if ($modulepart == 'project' && !empty($conf->projet->dir_output))
2524
+    {
2525
+        if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2526
+        {
2527
+            $accessallowed=1;
2528
+        }
2529
+        $original_file=$conf->projet->dir_output.'/'.$original_file;
2530
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2531
+    }
2532
+    else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
2533
+    {
2534
+        if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2535
+        {
2536
+            $accessallowed=1;
2537
+        }
2538
+        $original_file=$conf->projet->dir_output.'/'.$original_file;
2539
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2540
+    }
2541
+
2542
+    // Wrapping pour les commandes fournisseurs
2543
+    else if (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output))
2544
+    {
2545
+        if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2546
+        {
2547
+            $accessallowed=1;
2548
+        }
2549
+        $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2550
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2551
+    }
2552
+
2553
+    // Wrapping pour les factures fournisseurs
2554
+    else if (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output))
2555
+    {
2556
+        if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2557
+        {
2558
+            $accessallowed=1;
2559
+        }
2560
+        $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2561
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE facnumber='".$db->escape($refname)."' AND entity=".$conf->entity;
2562
+    }
2563
+    // Wrapping pour les rapport de paiements
2564
+    else if ($modulepart == 'supplier_payment')
2565
+    {
2566
+        if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2567
+        {
2568
+            $accessallowed=1;
2569
+        }
2570
+        $original_file=$conf->fournisseur->payment->dir_output.'/'.$original_file;
2571
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2572
+    }
2573
+
2574
+    // Wrapping pour les rapport de paiements
2575
+    else if ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output))
2576
+    {
2577
+        if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2578
+        {
2579
+            $accessallowed=1;
2580
+        }
2581
+        if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2582
+        else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
2583
+    }
2584
+
2585
+    // Wrapping for accounting exports
2586
+    else if ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output))
2587
+    {
2588
+        if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i',$original_file))
2589
+        {
2590
+            $accessallowed=1;
2591
+        }
2592
+        $original_file=$conf->accounting->dir_output.'/'.$original_file;
2593
+    }
2594
+
2595
+    // Wrapping pour les expedition
2596
+    else if ($modulepart == 'expedition' && !empty($conf->expedition->dir_output))
2597
+    {
2598
+        if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i',$original_file))
2599
+        {
2600
+            $accessallowed=1;
2601
+        }
2602
+        $original_file=$conf->expedition->dir_output."/sending/".$original_file;
2603
+    }
2604
+    // Wrapping pour les bons de livraison
2605
+    else if ($modulepart == 'livraison' && !empty($conf->expedition->dir_output))
2606
+    {
2607
+        if ($fuser->rights->expedition->livraison->{$lire} || preg_match('/^specimen/i',$original_file))
2608
+        {
2609
+            $accessallowed=1;
2610
+        }
2611
+        $original_file=$conf->expedition->dir_output."/receipt/".$original_file;
2612
+    }
2613
+
2614
+    // Wrapping pour les actions
2615
+    else if ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2616
+    {
2617
+        if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i',$original_file))
2618
+        {
2619
+            $accessallowed=1;
2620
+        }
2621
+        $original_file=$conf->agenda->dir_output.'/'.$original_file;
2622
+    }
2623
+
2624
+    // Wrapping pour les actions
2625
+    else if ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp))
2626
+    {
2627
+        if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i',$original_file))
2628
+        {
2629
+            $accessallowed=1;
2630
+        }
2631
+        $original_file = $conf->agenda->dir_temp."/".$original_file;
2632
+    }
2633
+
2634
+    // Wrapping pour les produits et services
2635
+    else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
2636
+    {
2637
+        if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2638
+        if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i',$original_file))
2639
+        {
2640
+            $accessallowed=1;
2641
+        }
2642
+        if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
2643
+        elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
2644
+    }
2645
+
2646
+    // Wrapping pour les lots produits
2647
+    else if ($modulepart == 'product_batch' || $modulepart == 'produitlot')
2648
+    {
2649
+        if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2650
+        if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i',$original_file))
2651
+        {
2652
+            $accessallowed=1;
2653
+        }
2654
+        if (! empty($conf->productbatch->enabled)) $original_file=$conf->productbatch->multidir_output[$entity].'/'.$original_file;
2655
+    }
2656
+
2657
+    // Wrapping pour les contrats
2658
+    else if ($modulepart == 'contract' && !empty($conf->contrat->dir_output))
2659
+    {
2660
+        if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2661
+        {
2662
+            $accessallowed=1;
2663
+        }
2664
+        $original_file=$conf->contrat->dir_output.'/'.$original_file;
2665
+        $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
2666
+    }
2667
+
2668
+    // Wrapping pour les dons
2669
+    else if ($modulepart == 'donation' && !empty($conf->don->dir_output))
2670
+    {
2671
+        if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i',$original_file))
2672
+        {
2673
+            $accessallowed=1;
2674
+        }
2675
+        $original_file=$conf->don->dir_output.'/'.$original_file;
2676
+    }
2677
+
2678
+    // Wrapping pour les dons
2679
+    else if ($modulepart == 'dolresource' && !empty($conf->resource->dir_output))
2680
+    {
2681
+        if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i',$original_file))
2682
+        {
2683
+            $accessallowed=1;
2684
+        }
2685
+        $original_file=$conf->resource->dir_output.'/'.$original_file;
2686
+    }
2687
+
2688
+    // Wrapping pour les remises de cheques
2689
+    else if ($modulepart == 'remisecheque' && !empty($conf->banque->dir_output))
2690
+    {
2691
+        if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i',$original_file))
2692
+        {
2693
+            $accessallowed=1;
2694
+        }
2695
+
2696
+        $original_file=$conf->bank->dir_output.'/checkdeposits/'.$original_file;		// original_file should contains relative path so include the get_exdir result
2697
+    }
2698
+
2699
+    // Wrapping for bank
2700
+    else if ($modulepart == 'bank' && !empty($conf->bank->dir_output))
2701
+    {
2702
+        if ($fuser->rights->banque->{$lire})
2703
+        {
2704
+            $accessallowed=1;
2705
+        }
2706
+        $original_file=$conf->bank->dir_output.'/'.$original_file;
2707
+    }
2708
+
2709
+    // Wrapping for export module
2710
+    else if ($modulepart == 'export' && !empty($conf->export->dir_temp))
2711
+    {
2712
+        // Aucun test necessaire car on force le rep de download sur
2713
+        // le rep export qui est propre a l'utilisateur
2714
+        $accessallowed=1;
2715
+        $original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
2716
+    }
2717
+
2718
+    // Wrapping for import module
2719
+    else if ($modulepart == 'import' && !empty($conf->import->dir_temp))
2720
+    {
2721
+        $accessallowed=1;
2722
+        $original_file=$conf->import->dir_temp.'/'.$original_file;
2723
+    }
2724
+
2725
+    // Wrapping pour l'editeur wysiwyg
2726
+    else if ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output))
2727
+    {
2728
+        $accessallowed=1;
2729
+        $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
2730
+    }
2731
+
2732
+    // Wrapping for backups
2733
+    else if ($modulepart == 'systemtools' && !empty($conf->admin->dir_output))
2734
+    {
2735
+        if ($fuser->admin) $accessallowed=1;
2736
+        $original_file=$conf->admin->dir_output.'/'.$original_file;
2737
+    }
2738
+
2739
+    // Wrapping for upload file test
2740
+    else if ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp))
2741
+    {
2742
+        if ($fuser->admin) $accessallowed=1;
2743
+        $original_file=$conf->admin->dir_temp.'/'.$original_file;
2744
+    }
2745
+
2746
+    // Wrapping pour BitTorrent
2747
+    else if ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output))
2748
+    {
2749
+        $accessallowed=1;
2750
+        $dir='files';
2751
+        if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
2752
+        $original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
2753
+    }
2754
+
2755
+    // Wrapping pour Foundation module
2756
+    else if ($modulepart == 'member' && !empty($conf->adherent->dir_output))
2757
+    {
2758
+        if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i',$original_file))
2759
+        {
2760
+            $accessallowed=1;
2761
+        }
2762
+        $original_file=$conf->adherent->dir_output.'/'.$original_file;
2763
+    }
2764
+
2765
+    // Wrapping for Scanner
2766
+    else if ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2767
+    {
2768
+        $accessallowed=1;
2769
+        $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2770
+    }
2771
+
2772
+    // GENERIC Wrapping
2773
+    // If modulepart=module_user_temp	Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
2774
+    // If modulepart=module_temp		Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
2775
+    // If modulepart=module_user		Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
2776
+    // If modulepart=module				Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
2777
+    else
2778
+    {
2779
+        if (preg_match('/^specimen/i',$original_file))	$accessallowed=1;    // If link to a file called specimen. Test must be done before changing $original_file int full path.
2780
+        if ($fuser->admin) $accessallowed=1;    // If user is admin
2781
+
2782
+        // Define $accessallowed
2783
+        if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
2784
+        {
2785
+            if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
2786
+            {
2787
+                dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2788
+                exit;
2789
+            }
2790
+            if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2791
+            $original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
2792
+        }
2793
+        else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
2794
+        {
2795
+            if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
2796
+            {
2797
+                dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2798
+                exit;
2799
+            }
2800
+            if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2801
+            $original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
2802
+        }
2803
+        else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
2804
+        {
2805
+            if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
2806
+            {
2807
+                dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2808
+                exit;
2809
+            }
2810
+            if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2811
+            $original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
2812
+        }
2813
+        else if (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg))
2814
+        {
2815
+            if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
2816
+            {
2817
+                dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2818
+                exit;
2819
+            }
2820
+            if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file))
2821
+            {
2822
+                $accessallowed=1;
2823
+            }
2824
+            $original_file=$conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2825
+        }
2826
+        else
2827
+        {
2828
+            if (empty($conf->$modulepart->dir_output))	// modulepart not supported
2829
+            {
2830
+                dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2831
+                exit;
2832
+            }
2833
+
2834
+            $perm=GETPOST('perm');
2835
+            $subperm=GETPOST('subperm');
2836
+            if ($perm || $subperm)
2837
+            {
2838
+                if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
2839
+                $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2840
+            }
2841
+            else
2842
+            {
2843
+                if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed=1;
2844
+                $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2845
+            }
2846
+        }
2847
+
2848
+        // For modules who wants to manage different levels of permissions for documents
2849
+        $subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
2850
+        if (! empty($conf->global->$subPermCategoryConstName))
2851
+        {
2852
+            $subPermCategory = $conf->global->$subPermCategoryConstName;
2853
+            if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download})))
2854
+            {
2855
+                $accessallowed=1;
2856
+            }
2857
+        }
2858
+
2859
+        // Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
2860
+        $sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
2861
+        if (! empty($conf->global->$sqlProtectConstName))	// If module want to define its own $sqlprotectagainstexternals
2862
+        {
2863
+            // Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2864
+            eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
2865
+        }
2866
+    }
2867
+
2868
+    $ret = array(
2869
+        'accessallowed' => $accessallowed,
2870
+        'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
2871
+        'original_file'=>$original_file
2872
+    );
2873
+
2874
+    return $ret;
2875 2875
 }
2876 2876
 
2877 2877
 /**
@@ -2884,10 +2884,10 @@  discard block
 block discarded – undo
2884 2884
  */
2885 2885
 function dol_filecache($directory, $filename, $object)
2886 2886
 {
2887
-	if (! dol_is_dir($directory)) dol_mkdir($directory);
2888
-	$cachefile = $directory . $filename;
2889
-	file_put_contents($cachefile, serialize($object), LOCK_EX);
2890
-	@chmod($cachefile, 0644);
2887
+    if (! dol_is_dir($directory)) dol_mkdir($directory);
2888
+    $cachefile = $directory . $filename;
2889
+    file_put_contents($cachefile, serialize($object), LOCK_EX);
2890
+    @chmod($cachefile, 0644);
2891 2891
 }
2892 2892
 
2893 2893
 /**
@@ -2900,10 +2900,10 @@  discard block
 block discarded – undo
2900 2900
  */
2901 2901
 function dol_cache_refresh($directory, $filename, $cachetime)
2902 2902
 {
2903
-	$now = dol_now();
2904
-	$cachefile = $directory . $filename;
2905
-	$refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile);
2906
-	return $refresh;
2903
+    $now = dol_now();
2904
+    $cachefile = $directory . $filename;
2905
+    $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile);
2906
+    return $refresh;
2907 2907
 }
2908 2908
 
2909 2909
 /**
@@ -2915,9 +2915,9 @@  discard block
 block discarded – undo
2915 2915
  */
2916 2916
 function dol_readcachefile($directory, $filename)
2917 2917
 {
2918
-	$cachefile = $directory . $filename;
2919
-	$object = unserialize(file_get_contents($cachefile));
2920
-	return $object;
2918
+    $cachefile = $directory . $filename;
2919
+    $object = unserialize(file_get_contents($cachefile));
2920
+    return $object;
2921 2921
 }
2922 2922
 
2923 2923
 
@@ -2934,43 +2934,43 @@  discard block
 block discarded – undo
2934 2934
  */
2935 2935
 function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path = '', $pathref = '', &$checksumconcat = array())
2936 2936
 {
2937
-	global $conffile;
2938
-
2939
-	$exclude = 'install';
2940
-
2941
-	foreach ($dir->md5file as $file)    // $file is a simpleXMLElement
2942
-	{
2943
-		$filename = $path.$file['name'];
2944
-		$file_list['insignature'][] = $filename;
2945
-		$expectedmd5 = (string) $file;
2946
-
2947
-		//if (preg_match('#'.$exclude.'#', $filename)) continue;
2948
-
2949
-		if (!file_exists($pathref.'/'.$filename))
2950
-		{
2951
-			$file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5);
2952
-		}
2953
-		else
2954
-		{
2955
-			$md5_local = md5_file($pathref.'/'.$filename);
2956
-
2957
-			if ($conffile == '/etc/dolibarr/conf.php' && $filename == '/filefunc.inc.php')	// For install with deb or rpm, we ignore test on filefunc.inc.php that was modified by package
2958
-			{
2959
-				$checksumconcat[] = $expectedmd5;
2960
-			}
2961
-			else
2962
-			{
2963
-				if ($md5_local != $expectedmd5) $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'md5'=>(string) $md5_local);
2964
-				$checksumconcat[] = $md5_local;
2965
-			}
2966
-		}
2967
-	}
2968
-
2969
-	foreach ($dir->dir as $subdir)			// $subdir['name'] is  '' or '/accountancy/admin' for example
2970
-	{
2971
-		getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
2972
-	}
2973
-
2974
-	return $file_list;
2937
+    global $conffile;
2938
+
2939
+    $exclude = 'install';
2940
+
2941
+    foreach ($dir->md5file as $file)    // $file is a simpleXMLElement
2942
+    {
2943
+        $filename = $path.$file['name'];
2944
+        $file_list['insignature'][] = $filename;
2945
+        $expectedmd5 = (string) $file;
2946
+
2947
+        //if (preg_match('#'.$exclude.'#', $filename)) continue;
2948
+
2949
+        if (!file_exists($pathref.'/'.$filename))
2950
+        {
2951
+            $file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5);
2952
+        }
2953
+        else
2954
+        {
2955
+            $md5_local = md5_file($pathref.'/'.$filename);
2956
+
2957
+            if ($conffile == '/etc/dolibarr/conf.php' && $filename == '/filefunc.inc.php')	// For install with deb or rpm, we ignore test on filefunc.inc.php that was modified by package
2958
+            {
2959
+                $checksumconcat[] = $expectedmd5;
2960
+            }
2961
+            else
2962
+            {
2963
+                if ($md5_local != $expectedmd5) $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'md5'=>(string) $md5_local);
2964
+                $checksumconcat[] = $md5_local;
2965
+            }
2966
+        }
2967
+    }
2968
+
2969
+    foreach ($dir->dir as $subdir)			// $subdir['name'] is  '' or '/accountancy/admin' for example
2970
+    {
2971
+        getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
2972
+    }
2973
+
2974
+    return $file_list;
2975 2975
 }
2976 2976
 
Please login to merge, or discard this patch.
Spacing   +595 added lines, -595 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
  */
35 35
 function dol_basename($pathfile)
36 36
 {
37
-	return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/'));
37
+	return preg_replace('/^.*\/([^\/]+)$/', '$1', rtrim($pathfile, '/'));
38 38
 }
39 39
 
40 40
 /**
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
  *  @return	array						Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file',...)
57 57
  *  @see dol_dir_list_indatabase
58 58
  */
59
-function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
59
+function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename = "", $donotfollowsymlinks = 0)
60 60
 {
61 61
 	global $db, $hookmanager;
62 62
 	global $object;
@@ -64,23 +64,23 @@  discard block
 block discarded – undo
64 64
 	dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
65 65
 	//print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
66 66
 
67
-	$loaddate=($mode==1||$mode==2)?true:false;
68
-	$loadsize=($mode==1||$mode==3)?true:false;
67
+	$loaddate = ($mode == 1 || $mode == 2) ?true:false;
68
+	$loadsize = ($mode == 1 || $mode == 3) ?true:false;
69 69
 
70 70
 	// Clean parameters
71
-	$path=preg_replace('/([\\/]+)$/i','',$path);
72
-	$newpath=dol_osencode($path);
71
+	$path = preg_replace('/([\\/]+)$/i', '', $path);
72
+	$newpath = dol_osencode($path);
73 73
 
74 74
 	$reshook = 0;
75 75
 	$file_list = array();
76 76
 
77
-	if (is_object($hookmanager) && ! $nohook)
77
+	if (is_object($hookmanager) && !$nohook)
78 78
 	{
79
-		$hookmanager->resArray=array();
79
+		$hookmanager->resArray = array();
80 80
 
81 81
 		$hookmanager->initHooks(array('fileslib'));
82 82
 
83
-		$parameters=array(
83
+		$parameters = array(
84 84
 				'path' => $newpath,
85 85
 				'types'=> $types,
86 86
 				'recursive' => $recursive,
@@ -92,63 +92,63 @@  discard block
 block discarded – undo
92 92
 				'loadsize' => $loadsize,
93 93
 				'mode' => $mode
94 94
 		);
95
-		$reshook=$hookmanager->executeHooks('getDirList', $parameters, $object);
95
+		$reshook = $hookmanager->executeHooks('getDirList', $parameters, $object);
96 96
 	}
97 97
 
98 98
 	// $hookmanager->resArray may contain array stacked by other modules
99 99
 	if (empty($reshook))
100 100
 	{
101
-		if (! is_dir($newpath)) return array();
101
+		if (!is_dir($newpath)) return array();
102 102
 
103 103
 		if ($dir = opendir($newpath))
104 104
 		{
105
-			$filedate='';
106
-			$filesize='';
105
+			$filedate = '';
106
+			$filesize = '';
107 107
 
108 108
 			while (false !== ($file = readdir($dir)))        // $file is always a basename (into directory $newpath)
109 109
 			{
110
-				if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure data is stored in utf8 in memory
111
-				$fullpathfile=($newpath?$newpath.'/':'').$file;
110
+				if (!utf8_check($file)) $file = utf8_encode($file); // To be sure data is stored in utf8 in memory
111
+				$fullpathfile = ($newpath ? $newpath.'/' : '').$file;
112 112
 
113
-				$qualified=1;
113
+				$qualified = 1;
114 114
 
115 115
 				// Define excludefilterarray
116
-				$excludefilterarray=array('^\.');
116
+				$excludefilterarray = array('^\.');
117 117
 				if (is_array($excludefilter))
118 118
 				{
119
-					$excludefilterarray=array_merge($excludefilterarray,$excludefilter);
119
+					$excludefilterarray = array_merge($excludefilterarray, $excludefilter);
120 120
 				}
121
-				else if ($excludefilter) $excludefilterarray[]=$excludefilter;
121
+				else if ($excludefilter) $excludefilterarray[] = $excludefilter;
122 122
 				// Check if file is qualified
123
-				foreach($excludefilterarray as $filt)
123
+				foreach ($excludefilterarray as $filt)
124 124
 				{
125 125
 					if (preg_match('/'.$filt.'/i', $file) || preg_match('/'.$filt.'/i', $fullpathfile)) {
126
-						$qualified=0; break;
126
+						$qualified = 0; break;
127 127
 					}
128 128
 				}
129 129
 				//print $fullpathfile.' '.$file.' '.$qualified.'<br>';
130 130
 
131 131
 				if ($qualified)
132 132
 				{
133
-					$isdir=is_dir(dol_osencode($path."/".$file));
133
+					$isdir = is_dir(dol_osencode($path."/".$file));
134 134
 					// Check whether this is a file or directory and whether we're interested in that type
135
-					if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
135
+					if ($isdir && (($types == "directories") || ($types == "all") || $recursive))
136 136
 					{
137 137
 						// Add entry into file_list array
138
-						if (($types=="directories") || ($types=="all"))
138
+						if (($types == "directories") || ($types == "all"))
139 139
 						{
140
-							if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
141
-							if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
140
+							if ($loaddate || $sortcriteria == 'date') $filedate = dol_filemtime($path."/".$file);
141
+							if ($loadsize || $sortcriteria == 'size') $filesize = dol_filesize($path."/".$file);
142 142
 
143
-							if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into all $path, only into $file part
143
+							if (!$filter || preg_match('/'.$filter.'/i', $file))	// We do not search key $filter into all $path, only into $file part
144 144
 							{
145
-								preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
146
-								$level1name=(isset($reg[1])?$reg[1]:'');
145
+								preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg);
146
+								$level1name = (isset($reg[1]) ? $reg[1] : '');
147 147
 								$file_list[] = array(
148 148
 										"name" => $file,
149 149
 										"path" => $path,
150 150
 										"level1name" => $level1name,
151
-										"relativename" => ($relativename?$relativename.'/':'').$file,
151
+										"relativename" => ($relativename ? $relativename.'/' : '').$file,
152 152
 										"fullname" => $path.'/'.$file,
153 153
 										"date" => $filedate,
154 154
 										"size" => $filesize,
@@ -160,28 +160,28 @@  discard block
 block discarded – undo
160 160
 						// if we're in a directory and we want recursive behavior, call this function again
161 161
 						if ($recursive)
162 162
 						{
163
-							if (empty($donotfollowsymlinks) || ! is_link($path."/".$file))
163
+							if (empty($donotfollowsymlinks) || !is_link($path."/".$file))
164 164
 							{
165 165
 								//var_dump('eee '. $path."/".$file. ' '.is_dir($path."/".$file).' '.is_link($path."/".$file));
166
-								$file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename!=''?$relativename.'/':'').$file, $donotfollowsymlinks));
166
+								$file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename != '' ? $relativename.'/' : '').$file, $donotfollowsymlinks));
167 167
 							}
168 168
 						}
169 169
 					}
170
-					else if (! $isdir && (($types == "files") || ($types == "all")))
170
+					else if (!$isdir && (($types == "files") || ($types == "all")))
171 171
 					{
172 172
 						// Add file into file_list array
173
-						if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
174
-						if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
173
+						if ($loaddate || $sortcriteria == 'date') $filedate = dol_filemtime($path."/".$file);
174
+						if ($loadsize || $sortcriteria == 'size') $filesize = dol_filesize($path."/".$file);
175 175
 
176
-						if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into $path, only into $file
176
+						if (!$filter || preg_match('/'.$filter.'/i', $file))	// We do not search key $filter into $path, only into $file
177 177
 						{
178
-							preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
179
-							$level1name=(isset($reg[1])?$reg[1]:'');
178
+							preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg);
179
+							$level1name = (isset($reg[1]) ? $reg[1] : '');
180 180
 							$file_list[] = array(
181 181
 									"name" => $file,
182 182
 									"path" => $path,
183 183
 									"level1name" => $level1name,
184
-									"relativename" => ($relativename?$relativename.'/':'').$file,
184
+									"relativename" => ($relativename ? $relativename.'/' : '').$file,
185 185
 									"fullname" => $path.'/'.$file,
186 186
 									"date" => $filedate,
187 187
 									"size" => $filesize,
@@ -194,12 +194,12 @@  discard block
 block discarded – undo
194 194
 			closedir($dir);
195 195
 
196 196
 			// Obtain a list of columns
197
-			if (! empty($sortcriteria))
197
+			if (!empty($sortcriteria))
198 198
 			{
199
-				$myarray=array();
199
+				$myarray = array();
200 200
 				foreach ($file_list as $key => $row)
201 201
 				{
202
-					$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
202
+					$myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] : '');
203 203
 				}
204 204
 				// Sort the data
205 205
 				if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
@@ -226,21 +226,21 @@  discard block
 block discarded – undo
226 226
  *  @return	array						Array of array('name'=>'xxx','fullname'=>'/abc/xxx','type'=>'dir|file',...)
227 227
  *  @see dol_dir_list
228 228
  */
229
-function dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0)
229
+function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0)
230 230
 {
231 231
 	global $conf, $db;
232 232
 
233
-	$sql =" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,";
234
-	$sql.=" acl, position, share";
235
-	if ($mode) $sql.=", description";
236
-	$sql.=" FROM ".MAIN_DB_PREFIX."ecm_files";
237
-	$sql.=" WHERE filepath = '".$db->escape($path)."'";
238
-	$sql.=" AND entity = ".$conf->entity;
233
+	$sql = " SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,";
234
+	$sql .= " acl, position, share";
235
+	if ($mode) $sql .= ", description";
236
+	$sql .= " FROM ".MAIN_DB_PREFIX."ecm_files";
237
+	$sql .= " WHERE filepath = '".$db->escape($path)."'";
238
+	$sql .= " AND entity = ".$conf->entity;
239 239
 
240 240
 	$resql = $db->query($sql);
241 241
 	if ($resql)
242 242
 	{
243
-		$file_list=array();
243
+		$file_list = array();
244 244
 		$num = $db->num_rows($resql);
245 245
 		$i = 0;
246 246
 		while ($i < $num)
@@ -248,11 +248,11 @@  discard block
 block discarded – undo
248 248
 			$obj = $db->fetch_object($resql);
249 249
 			if ($obj)
250 250
 			{
251
-				preg_match('/([^\/]+)\/[^\/]+$/',DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,$reg);
252
-				$level1name=(isset($reg[1])?$reg[1]:'');
251
+				preg_match('/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, $reg);
252
+				$level1name = (isset($reg[1]) ? $reg[1] : '');
253 253
 				$file_list[] = array(
254 254
 					"rowid" => $obj->rowid,
255
-					"label" => $obj->label,         // md5
255
+					"label" => $obj->label, // md5
256 256
 					"name" => $obj->filename,
257 257
 					"path" => DOL_DATA_ROOT.'/'.$obj->filepath,
258 258
 					"level1name" => $level1name,
@@ -272,12 +272,12 @@  discard block
 block discarded – undo
272 272
 		}
273 273
 
274 274
 		// Obtain a list of columns
275
-		if (! empty($sortcriteria))
275
+		if (!empty($sortcriteria))
276 276
 		{
277
-			$myarray=array();
277
+			$myarray = array();
278 278
 			foreach ($file_list as $key => $row)
279 279
 			{
280
-				$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
280
+				$myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] : '');
281 281
 			}
282 282
 			// Sort the data
283 283
 			if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
@@ -309,15 +309,15 @@  discard block
 block discarded – undo
309 309
 
310 310
 	// TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed
311 311
 	global $modulepart;
312
-	if ($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
312
+	if ($modulepart == 'produit' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
313 313
 		global $object;
314
-		if (! empty($object->id))
314
+		if (!empty($object->id))
315 315
 		{
316
-			if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
317
-			else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
316
+			if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
317
+			else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
318 318
 
319
-			$relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dirold);
320
-			$relativedirold = preg_replace('/^[\\/]/','',$relativedirold);
319
+			$relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dirold);
320
+			$relativedirold = preg_replace('/^[\\/]/', '', $relativedirold);
321 321
 
322 322
 			$filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC));
323 323
 		}
@@ -327,38 +327,38 @@  discard block
 block discarded – undo
327 327
 	//var_dump($filearrayindatabase);
328 328
 
329 329
 	// Complete filearray with properties found into $filearrayindatabase
330
-	foreach($filearray as $key => $val)
330
+	foreach ($filearray as $key => $val)
331 331
 	{
332
-		$found=0;
332
+		$found = 0;
333 333
 		// Search if it exists into $filearrayindatabase
334
-		foreach($filearrayindatabase as $key2 => $val2)
334
+		foreach ($filearrayindatabase as $key2 => $val2)
335 335
 		{
336 336
 			if ($filearrayindatabase[$key2]['name'] == $filearray[$key]['name'])
337 337
 			{
338
-				$filearray[$key]['position_name']=($filearrayindatabase[$key2]['position']?$filearrayindatabase[$key2]['position']:'0').'_'.$filearrayindatabase[$key2]['name'];
339
-				$filearray[$key]['position']=$filearrayindatabase[$key2]['position'];
340
-				$filearray[$key]['cover']=$filearrayindatabase[$key2]['cover'];
341
-				$filearray[$key]['acl']=$filearrayindatabase[$key2]['acl'];
342
-				$filearray[$key]['rowid']=$filearrayindatabase[$key2]['rowid'];
343
-				$filearray[$key]['label']=$filearrayindatabase[$key2]['label'];
344
-				$filearray[$key]['share']=$filearrayindatabase[$key2]['share'];
345
-				$found=1;
338
+				$filearray[$key]['position_name'] = ($filearrayindatabase[$key2]['position'] ? $filearrayindatabase[$key2]['position'] : '0').'_'.$filearrayindatabase[$key2]['name'];
339
+				$filearray[$key]['position'] = $filearrayindatabase[$key2]['position'];
340
+				$filearray[$key]['cover'] = $filearrayindatabase[$key2]['cover'];
341
+				$filearray[$key]['acl'] = $filearrayindatabase[$key2]['acl'];
342
+				$filearray[$key]['rowid'] = $filearrayindatabase[$key2]['rowid'];
343
+				$filearray[$key]['label'] = $filearrayindatabase[$key2]['label'];
344
+				$filearray[$key]['share'] = $filearrayindatabase[$key2]['share'];
345
+				$found = 1;
346 346
 				break;
347 347
 			}
348 348
 		}
349 349
 
350
-		if (! $found)    // This happen in transition toward version 6, or if files were added manually into os dir.
350
+		if (!$found)    // This happen in transition toward version 6, or if files were added manually into os dir.
351 351
 		{
352
-			$filearray[$key]['position']='999999';     // File not indexed are at end. So if we add a file, it will not replace an existing position
353
-			$filearray[$key]['cover']=0;
354
-			$filearray[$key]['acl']='';
352
+			$filearray[$key]['position'] = '999999'; // File not indexed are at end. So if we add a file, it will not replace an existing position
353
+			$filearray[$key]['cover'] = 0;
354
+			$filearray[$key]['acl'] = '';
355 355
 
356
-			$rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filearray[$key]['fullname']);
357
-			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
356
+			$rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['fullname']);
357
+			if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
358 358
 			{
359 359
 				dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
360 360
 				include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
361
-				$ecmfile=new EcmFiles($db);
361
+				$ecmfile = new EcmFiles($db);
362 362
 
363 363
 				// Add entry into database
364 364
 				$filename = basename($rel_filename);
@@ -368,11 +368,11 @@  discard block
 block discarded – undo
368 368
 
369 369
 				$ecmfile->filepath = $rel_dir;
370 370
 				$ecmfile->filename = $filename;
371
-				$ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname']));        // $destfile is a full path to file
371
+				$ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname'])); // $destfile is a full path to file
372 372
 				$ecmfile->fullpath_orig = $filearray[$key]['fullname'];
373 373
 				$ecmfile->gen_or_uploaded = 'unknown';
374
-				$ecmfile->description = '';    // indexed content
375
-				$ecmfile->keyword = '';        // keyword content
374
+				$ecmfile->description = ''; // indexed content
375
+				$ecmfile->keyword = ''; // keyword content
376 376
 				$result = $ecmfile->create($user);
377 377
 				if ($result < 0)
378 378
 				{
@@ -380,12 +380,12 @@  discard block
 block discarded – undo
380 380
 				}
381 381
 				else
382 382
 				{
383
-					$filearray[$key]['rowid']=$result;
383
+					$filearray[$key]['rowid'] = $result;
384 384
 				}
385 385
 			}
386 386
 			else
387 387
 			{
388
-				$filearray[$key]['rowid']=0;     // Should not happened
388
+				$filearray[$key]['rowid'] = 0; // Should not happened
389 389
 			}
390 390
 		}
391 391
 	}
@@ -406,10 +406,10 @@  discard block
 block discarded – undo
406 406
 	global $sortorder;
407 407
 	global $sortfield;
408 408
 
409
-	$sortorder=strtoupper($sortorder);
409
+	$sortorder = strtoupper($sortorder);
410 410
 
411
-	if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
412
-	else { $retup=1; $retdown=-1; }
411
+	if ($sortorder == 'ASC') { $retup = -1; $retdown = 1; }
412
+	else { $retup = 1; $retdown = -1; }
413 413
 
414 414
 	if ($sortfield == 'name')
415 415
 	{
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
  */
438 438
 function dol_is_dir($folder)
439 439
 {
440
-	$newfolder=dol_osencode($folder);
440
+	$newfolder = dol_osencode($folder);
441 441
 	if (is_dir($newfolder)) return true;
442 442
 	else return false;
443 443
 }
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
  */
451 451
 function dol_is_file($pathoffile)
452 452
 {
453
-	$newpathoffile=dol_osencode($pathoffile);
453
+	$newpathoffile = dol_osencode($pathoffile);
454 454
 	return is_file($newpathoffile);
455 455
 }
456 456
 
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
  */
463 463
 function dol_is_link($pathoffile)
464 464
 {
465
-	$newpathoffile=dol_osencode($pathoffile);
465
+	$newpathoffile = dol_osencode($pathoffile);
466 466
 	return is_link($newpathoffile);
467 467
 }
468 468
 
@@ -474,10 +474,10 @@  discard block
 block discarded – undo
474 474
  */
475 475
 function dol_is_url($url)
476 476
 {
477
-	$tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
478
-	foreach($tmpprot as $prot)
477
+	$tmpprot = array('file', 'http', 'https', 'ftp', 'zlib', 'data', 'ssh', 'ssh2', 'ogg', 'expect');
478
+	foreach ($tmpprot as $prot)
479 479
 	{
480
-		if (preg_match('/^'.$prot.':/i',$url)) return true;
480
+		if (preg_match('/^'.$prot.':/i', $url)) return true;
481 481
 	}
482 482
 	return false;
483 483
 }
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
  */
491 491
 function dol_dir_is_emtpy($folder)
492 492
 {
493
-	$newfolder=dol_osencode($folder);
493
+	$newfolder = dol_osencode($folder);
494 494
 	if (is_dir($newfolder))
495 495
 	{
496 496
 		$handle = opendir($newfolder);
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 		{
500 500
 			$name_array[] = $name;
501 501
 		}
502
-		foreach($name_array as $temp) $folder_content .= $temp;
502
+		foreach ($name_array as $temp) $folder_content .= $temp;
503 503
 
504 504
 		closedir($handle);
505 505
 
@@ -519,24 +519,24 @@  discard block
 block discarded – undo
519 519
  */
520 520
 function dol_count_nb_of_line($file)
521 521
 {
522
-	$nb=0;
522
+	$nb = 0;
523 523
 
524
-	$newfile=dol_osencode($file);
524
+	$newfile = dol_osencode($file);
525 525
 	//print 'x'.$file;
526
-	$fp=fopen($newfile,'r');
526
+	$fp = fopen($newfile, 'r');
527 527
 	if ($fp)
528 528
 	{
529 529
 		while (!feof($fp))
530 530
 		{
531
-			$line=fgets($fp);
531
+			$line = fgets($fp);
532 532
 			// We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
533
-			if (! $line === false) $nb++;
533
+			if (!$line === false) $nb++;
534 534
 		}
535 535
 		fclose($fp);
536 536
 	}
537 537
 	else
538 538
 	{
539
-		$nb=-1;
539
+		$nb = -1;
540 540
 	}
541 541
 
542 542
 	return $nb;
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
  */
552 552
 function dol_filesize($pathoffile)
553 553
 {
554
-	$newpathoffile=dol_osencode($pathoffile);
554
+	$newpathoffile = dol_osencode($pathoffile);
555 555
 	return filesize($newpathoffile);
556 556
 }
557 557
 
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
  */
564 564
 function dol_filemtime($pathoffile)
565 565
 {
566
-	$newpathoffile=dol_osencode($pathoffile);
566
+	$newpathoffile = dol_osencode($pathoffile);
567 567
 	return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
568 568
 }
569 569
 
@@ -578,31 +578,31 @@  discard block
 block discarded – undo
578 578
  * @return	int							<0 if error, 0 if nothing done (dest file already exists), >0 if OK
579 579
  * @see		dol_copy dolReplaceRegExInFile
580 580
  */
581
-function dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0)
581
+function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = 0, $indexdatabase = 0)
582 582
 {
583 583
 	global $conf;
584 584
 
585 585
 	dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase);
586 586
 
587 587
 	if (empty($srcfile)) return -1;
588
-	if (empty($destfile)) $destfile=$srcfile;
588
+	if (empty($destfile)) $destfile = $srcfile;
589 589
 
590
-	$destexists=dol_is_file($destfile);
590
+	$destexists = dol_is_file($destfile);
591 591
 	if (($destfile != $srcfile) && $destexists) return 0;
592 592
 
593
-	$tmpdestfile=$destfile.'.tmp';
593
+	$tmpdestfile = $destfile.'.tmp';
594 594
 
595
-	$newpathofsrcfile=dol_osencode($srcfile);
596
-	$newpathoftmpdestfile=dol_osencode($tmpdestfile);
597
-	$newpathofdestfile=dol_osencode($destfile);
598
-	$newdirdestfile=dirname($newpathofdestfile);
595
+	$newpathofsrcfile = dol_osencode($srcfile);
596
+	$newpathoftmpdestfile = dol_osencode($tmpdestfile);
597
+	$newpathofdestfile = dol_osencode($destfile);
598
+	$newdirdestfile = dirname($newpathofdestfile);
599 599
 
600
-	if ($destexists && ! is_writable($newpathofdestfile))
600
+	if ($destexists && !is_writable($newpathofdestfile))
601 601
 	{
602 602
 		dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING);
603 603
 		return -1;
604 604
 	}
605
-	if (! is_writable($newdirdestfile))
605
+	if (!is_writable($newdirdestfile))
606 606
 	{
607 607
 		dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
608 608
 		return -2;
@@ -619,17 +619,17 @@  discard block
 block discarded – undo
619 619
 	@chmod($newpathoftmpdestfile, octdec($newmask));
620 620
 
621 621
 	// Rename
622
-	$result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase);
623
-	if (! $result)
622
+	$result = dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase);
623
+	if (!$result)
624 624
 	{
625 625
 		dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
626 626
 		return -3;
627 627
 	}
628
-	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
628
+	if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
629 629
 	if (empty($newmask))	// This should no happen
630 630
 	{
631 631
 		dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
632
-		$newmask='0664';
632
+		$newmask = '0664';
633 633
 	}
634 634
 
635 635
 	@chmod($newpathofdestfile, octdec($newmask));
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
  * @return	int							<0 if error, 0 if nothing done (dest file already exists), >0 if OK
649 649
  * @see		dol_copy dolReplaceInFile
650 650
  */
651
-function dolReplaceRegExInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0)
651
+function dolReplaceRegExInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = 0, $indexdatabase = 0)
652 652
 {
653 653
 	// TODO
654 654
 }
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
  * @return	int							<0 if error, 0 if nothing done (dest file already exists and overwriteifexists=0), >0 if OK
664 664
  * @see		dol_delete_file
665 665
  */
666
-function dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
666
+function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1)
667 667
 {
668 668
 	global $conf;
669 669
 
@@ -671,36 +671,36 @@  discard block
 block discarded – undo
671 671
 
672 672
 	if (empty($srcfile) || empty($destfile)) return -1;
673 673
 
674
-	$destexists=dol_is_file($destfile);
675
-	if (! $overwriteifexists && $destexists) return 0;
674
+	$destexists = dol_is_file($destfile);
675
+	if (!$overwriteifexists && $destexists) return 0;
676 676
 
677
-	$newpathofsrcfile=dol_osencode($srcfile);
678
-	$newpathofdestfile=dol_osencode($destfile);
679
-	$newdirdestfile=dirname($newpathofdestfile);
677
+	$newpathofsrcfile = dol_osencode($srcfile);
678
+	$newpathofdestfile = dol_osencode($destfile);
679
+	$newdirdestfile = dirname($newpathofdestfile);
680 680
 
681
-	if ($destexists && ! is_writable($newpathofdestfile))
681
+	if ($destexists && !is_writable($newpathofdestfile))
682 682
 	{
683 683
 		dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
684 684
 		return -1;
685 685
 	}
686
-	if (! is_writable($newdirdestfile))
686
+	if (!is_writable($newdirdestfile))
687 687
 	{
688 688
 		dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
689 689
 		return -2;
690 690
 	}
691 691
 	// Copy with overwriting if exists
692
-	$result=@copy($newpathofsrcfile, $newpathofdestfile);
692
+	$result = @copy($newpathofsrcfile, $newpathofdestfile);
693 693
 	//$result=copy($newpathofsrcfile, $newpathofdestfile);	// To see errors, remove @
694
-	if (! $result)
694
+	if (!$result)
695 695
 	{
696 696
 		dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
697 697
 		return -3;
698 698
 	}
699
-	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
699
+	if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
700 700
 	if (empty($newmask))	// This should no happen
701 701
 	{
702 702
 		dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
703
-		$newmask='0664';
703
+		$newmask = '0664';
704 704
 	}
705 705
 
706 706
 	@chmod($newpathofdestfile, octdec($newmask));
@@ -719,44 +719,44 @@  discard block
 block discarded – undo
719 719
  * @return	int							<0 if error, 0 if nothing done (all files already exists and overwriteifexists=0), >0 if OK
720 720
  * @see		dol_copy
721 721
  */
722
-function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null)
722
+function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement = null)
723 723
 {
724 724
 	global $conf;
725 725
 
726
-	$result=0;
726
+	$result = 0;
727 727
 
728 728
 	dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
729 729
 
730 730
 	if (empty($srcfile) || empty($destfile)) return -1;
731 731
 
732
-	$destexists=dol_is_dir($destfile);
732
+	$destexists = dol_is_dir($destfile);
733 733
 	//if (! $overwriteifexists && $destexists) return 0;	// The overwriteifexists is for files only, so propagated to dol_copy only.
734 734
 
735
-	if (! $destexists)
735
+	if (!$destexists)
736 736
 	{
737 737
 		// We must set mask just before creating dir, becaause it can be set differently by dol_copy
738 738
 		umask(0);
739
-		$dirmaskdec=octdec($newmask);
740
-		if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
741
-		$dirmaskdec |= octdec('0200');  // Set w bit required to be able to create content for recursive subdirs files
739
+		$dirmaskdec = octdec($newmask);
740
+		if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $dirmaskdec = octdec($conf->global->MAIN_UMASK);
741
+		$dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
742 742
 		dol_mkdir($destfile, '', decoct($dirmaskdec));
743 743
 	}
744 744
 
745
-	$ossrcfile=dol_osencode($srcfile);
746
-	$osdestfile=dol_osencode($destfile);
745
+	$ossrcfile = dol_osencode($srcfile);
746
+	$osdestfile = dol_osencode($destfile);
747 747
 
748 748
 	// Recursive function to copy all subdirectories and contents:
749 749
 	if (is_dir($ossrcfile))
750 750
 	{
751
-		$dir_handle=opendir($ossrcfile);
752
-		while ($file=readdir($dir_handle))
751
+		$dir_handle = opendir($ossrcfile);
752
+		while ($file = readdir($dir_handle))
753 753
 		{
754
-			if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file))
754
+			if ($file != "." && $file != ".." && !is_link($ossrcfile."/".$file))
755 755
 			{
756 756
 				if (is_dir($ossrcfile."/".$file))
757 757
 				{
758 758
 					//var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
759
-					$tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement);
759
+					$tmpresult = dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement);
760 760
 				}
761 761
 				else
762 762
 				{
@@ -764,12 +764,12 @@  discard block
 block discarded – undo
764 764
 					// Replace destination filename with a new one
765 765
 					if (is_array($arrayreplacement))
766 766
 					{
767
-						foreach($arrayreplacement as $key => $val)
767
+						foreach ($arrayreplacement as $key => $val)
768 768
 						{
769 769
 							$newfile = str_replace($key, $val, $newfile);
770 770
 						}
771 771
 					}
772
-					$tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
772
+					$tmpresult = dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists);
773 773
 				}
774 774
 				// Set result
775 775
 				if ($result > 0 && $tmpresult >= 0)
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 				}
779 779
 				else
780 780
 				{
781
-					$result=$tmpresult;
781
+					$result = $tmpresult;
782 782
 				}
783 783
 				if ($result < 0) break;
784 784
 			}
@@ -811,31 +811,31 @@  discard block
 block discarded – undo
811 811
  * @return  boolean 		            True if OK, false if KO
812 812
  * @see dol_move_uploaded_file
813 813
  */
814
-function dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
814
+function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1)
815 815
 {
816 816
 	global $user, $db, $conf;
817
-	$result=false;
817
+	$result = false;
818 818
 
819 819
 	dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
820
-	$srcexists=dol_is_file($srcfile);
821
-	$destexists=dol_is_file($destfile);
820
+	$srcexists = dol_is_file($srcfile);
821
+	$destexists = dol_is_file($destfile);
822 822
 
823
-	if (! $srcexists)
823
+	if (!$srcexists)
824 824
 	{
825 825
 		dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request.");
826 826
 		return false;
827 827
 	}
828 828
 
829
-	if ($overwriteifexists || ! $destexists)
829
+	if ($overwriteifexists || !$destexists)
830 830
 	{
831
-		$newpathofsrcfile=dol_osencode($srcfile);
832
-		$newpathofdestfile=dol_osencode($destfile);
831
+		$newpathofsrcfile = dol_osencode($srcfile);
832
+		$newpathofdestfile = dol_osencode($destfile);
833 833
 
834 834
 		// Check virus
835
-		$testvirusarray=array();
835
+		$testvirusarray = array();
836 836
 		if ($testvirus)
837 837
 		{
838
-			$testvirusarray=dolCheckVirus($newpathofsrcfile);
838
+			$testvirusarray = dolCheckVirus($newpathofsrcfile);
839 839
 			if (count($testvirusarray))
840 840
 			{
841 841
 				dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING);
@@ -843,15 +843,15 @@  discard block
 block discarded – undo
843 843
 			}
844 844
 		}
845 845
 
846
-		$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
847
-		if (! $result)
846
+		$result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
847
+		if (!$result)
848 848
 		{
849 849
 			if ($destexists)
850 850
 			{
851 851
 				dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
852 852
 				// We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
853 853
 				dol_delete_file($destfile);
854
-				$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
854
+				$result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
855 855
 			}
856 856
 			else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
857 857
 		}
@@ -860,9 +860,9 @@  discard block
 block discarded – undo
860 860
 		if ($result && $indexdatabase)
861 861
 		{
862 862
 			// Rename entry into ecm database
863
-			$rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $srcfile);
864
-			$rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $destfile);
865
-			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
863
+			$rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $srcfile);
864
+			$rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destfile);
865
+			if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
866 866
 			{
867 867
 				$rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
868 868
 				$rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
@@ -871,14 +871,14 @@  discard block
 block discarded – undo
871 871
 				dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
872 872
 				include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
873 873
 
874
-				$ecmfiletarget=new EcmFiles($db);
874
+				$ecmfiletarget = new EcmFiles($db);
875 875
 				$resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
876 876
 				if ($resultecmtarget > 0)   // An entry for target name already exists for target, we delete it, a new one will be created.
877 877
 				{
878 878
 					$ecmfiletarget->delete($user);
879 879
 				}
880 880
 
881
-				$ecmfile=new EcmFiles($db);
881
+				$ecmfile = new EcmFiles($db);
882 882
 				$resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
883 883
 				if ($resultecm > 0)   // If an entry was found for src file, we use it to move entry
884 884
 				{
@@ -900,11 +900,11 @@  discard block
 block discarded – undo
900 900
 
901 901
 					$ecmfile->filepath = $rel_dir;
902 902
 					$ecmfile->filename = $filename;
903
-					$ecmfile->label = md5_file(dol_osencode($destfile));        // $destfile is a full path to file
903
+					$ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file
904 904
 					$ecmfile->fullpath_orig = $srcfile;
905 905
 					$ecmfile->gen_or_uploaded = 'unknown';
906
-					$ecmfile->description = '';    // indexed content
907
-					$ecmfile->keyword = '';        // keyword content
906
+					$ecmfile->description = ''; // indexed content
907
+					$ecmfile->keyword = ''; // keyword content
908 908
 					$resultecm = $ecmfile->create($user);
909 909
 					if ($resultecm < 0)
910 910
 					{
@@ -916,13 +916,13 @@  discard block
 block discarded – undo
916 916
 					setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
917 917
 				}
918 918
 
919
-				if ($resultecm > 0) $result=true;
919
+				if ($resultecm > 0) $result = true;
920 920
 				else $result = false;
921 921
 			}
922 922
 		}
923 923
 
924
-		if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
925
-		$newmaskdec=octdec($newmask);
924
+		if (empty($newmask)) $newmask = empty($conf->global->MAIN_UMASK) ? '0755' : $conf->global->MAIN_UMASK;
925
+		$newmaskdec = octdec($newmask);
926 926
 		// Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
927 927
 		// to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
928 928
 		// if ($isdir) $newmaskdec |= octdec('0111');  // Set x bit required for directories
@@ -958,16 +958,16 @@  discard block
 block discarded – undo
958 958
 {
959 959
 	global $conf;
960 960
 
961
-	if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
961
+	if (!empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
962 962
 	{
963
-		if (! class_exists('AntiVir')) {
963
+		if (!class_exists('AntiVir')) {
964 964
 			require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
965 965
 		}
966
-		$antivir=new AntiVir($db);
966
+		$antivir = new AntiVir($db);
967 967
 		$result = $antivir->dol_avscan_file($src_file);
968 968
 		if ($result < 0)	// If virus or error, we stop here
969 969
 		{
970
-			$reterrors=$antivir->errors;
970
+			$reterrors = $antivir->errors;
971 971
 			return $reterrors;
972 972
 		}
973 973
 	}
@@ -993,20 +993,20 @@  discard block
 block discarded – undo
993 993
  *	@return int       			  		>0 if OK, <0 or string if KO
994 994
  *  @see    dol_move
995 995
  */
996
-function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile')
996
+function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $varfiles = 'addedfile')
997 997
 {
998 998
 	global $conf, $db, $user, $langs;
999 999
 	global $object, $hookmanager;
1000 1000
 
1001
-	$reshook=0;
1001
+	$reshook = 0;
1002 1002
 	$file_name = $dest_file;
1003 1003
 
1004 1004
 	if (empty($nohook))
1005 1005
 	{
1006
-		$reshook=$hookmanager->initHooks(array('fileslib'));
1006
+		$reshook = $hookmanager->initHooks(array('fileslib'));
1007 1007
 
1008
-		$parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
1009
-		$reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
1008
+		$parameters = array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
1009
+		$reshook = $hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
1010 1010
 	}
1011 1011
 
1012 1012
 	if (empty($reshook))
@@ -1014,7 +1014,7 @@  discard block
 block discarded – undo
1014 1014
 		// If an upload error has been reported
1015 1015
 		if ($uploaderrorcode)
1016 1016
 		{
1017
-			switch($uploaderrorcode)
1017
+			switch ($uploaderrorcode)
1018 1018
 			{
1019 1019
 				case UPLOAD_ERR_INI_SIZE:	// 1
1020 1020
 					return 'ErrorFileSizeTooLarge';
@@ -1042,25 +1042,25 @@  discard block
 block discarded – undo
1042 1042
 		// If we need to make a virus scan
1043 1043
 		if (empty($disablevirusscan) && file_exists($src_file))
1044 1044
 		{
1045
-			$checkvirusarray=dolCheckVirus($src_file);
1045
+			$checkvirusarray = dolCheckVirus($src_file);
1046 1046
 			if (count($checkvirusarray))
1047 1047
 			{
1048
-			   dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$checkvirusarray), LOG_WARNING);
1049
-			   return 'ErrorFileIsInfectedWithAVirus: '.join(',',$checkvirusarray);
1048
+			   dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',', $checkvirusarray), LOG_WARNING);
1049
+			   return 'ErrorFileIsInfectedWithAVirus: '.join(',', $checkvirusarray);
1050 1050
 			}
1051 1051
 		}
1052 1052
 
1053 1053
 		// Security:
1054 1054
 		// Disallow file with some extensions. We rename them.
1055 1055
 		// Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
1056
-		if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
1056
+		if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i', $dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
1057 1057
 		{
1058
-			$file_name.= '.noexe';
1058
+			$file_name .= '.noexe';
1059 1059
 		}
1060 1060
 
1061 1061
 		// Security:
1062 1062
 		// We refuse cache files/dirs, upload using .. and pipes into filenames.
1063
-		if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file))
1063
+		if (preg_match('/^\./', $src_file) || preg_match('/\.\./', $src_file) || preg_match('/[<>|]/', $src_file))
1064 1064
 		{
1065 1065
 			dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
1066 1066
 			return -1;
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
 
1069 1069
 		// Security:
1070 1070
 		// On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers.
1071
-		if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file))
1071
+		if (preg_match('/^\./', $dest_file) || preg_match('/\.\./', $dest_file) || preg_match('/[<>|]/', $dest_file))
1072 1072
 		{
1073 1073
 			dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
1074 1074
 			return -2;
@@ -1078,24 +1078,24 @@  discard block
 block discarded – undo
1078 1078
 	if ($reshook < 0)	// At least one blocking error returned by one hook
1079 1079
 	{
1080 1080
 		$errmsg = join(',', $hookmanager->errors);
1081
-		if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks';	// Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1081
+		if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1082 1082
 		return $errmsg;
1083 1083
 	}
1084 1084
 	elseif (empty($reshook))
1085 1085
 	{
1086 1086
 		// The file functions must be in OS filesystem encoding.
1087
-		$src_file_osencoded=dol_osencode($src_file);
1088
-		$file_name_osencoded=dol_osencode($file_name);
1087
+		$src_file_osencoded = dol_osencode($src_file);
1088
+		$file_name_osencoded = dol_osencode($file_name);
1089 1089
 
1090 1090
 		// Check if destination dir is writable
1091
-		if (! is_writable(dirname($file_name_osencoded)))
1091
+		if (!is_writable(dirname($file_name_osencoded)))
1092 1092
 		{
1093 1093
 			dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
1094 1094
 			return 'ErrorDirNotWritable';
1095 1095
 		}
1096 1096
 
1097 1097
 		// Check if destination file already exists
1098
-		if (! $allowoverwrite)
1098
+		if (!$allowoverwrite)
1099 1099
 		{
1100 1100
 			if (file_exists($file_name_osencoded))
1101 1101
 			{
@@ -1105,21 +1105,21 @@  discard block
 block discarded – undo
1105 1105
 		}
1106 1106
 
1107 1107
 		// Move file
1108
-		$return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1108
+		$return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1109 1109
 		if ($return)
1110 1110
 		{
1111
-			if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1111
+			if (!empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1112 1112
 			dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1113
-			return 1;	// Success
1113
+			return 1; // Success
1114 1114
 		}
1115 1115
 		else
1116 1116
 		{
1117 1117
 			dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
1118
-			return -3;	// Unknown error
1118
+			return -3; // Unknown error
1119 1119
 		}
1120 1120
 	}
1121 1121
 
1122
-	return 1;	// Success
1122
+	return 1; // Success
1123 1123
 }
1124 1124
 
1125 1125
 /**
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
  *  @return boolean         		True if no error (file is deleted or if glob is used and there's nothing to delete), False if error
1137 1137
  *  @see dol_delete_dir
1138 1138
  */
1139
-function dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
1139
+function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object = null, $allowdotdot = false, $indexdatabase = 1)
1140 1140
 {
1141 1141
 	global $db, $conf, $user, $langs;
1142 1142
 	global $hookmanager;
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
 
1149 1149
 	// Security:
1150 1150
 	// We refuse transversal using .. and pipes into filenames.
1151
-	if ((! $allowdotdot && preg_match('/\.\./',$file)) || preg_match('/[<>|]/',$file))
1151
+	if ((!$allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file))
1152 1152
 	{
1153 1153
 		dol_syslog("Refused to delete file ".$file, LOG_WARNING);
1154 1154
 		return false;
@@ -1158,13 +1158,13 @@  discard block
 block discarded – undo
1158 1158
 	{
1159 1159
 		$hookmanager->initHooks(array('fileslib'));
1160 1160
 
1161
-		$parameters=array(
1161
+		$parameters = array(
1162 1162
 				'GET' => $_GET,
1163 1163
 				'file' => $file,
1164 1164
 				'disableglob'=> $disableglob,
1165 1165
 				'nophperrors' => $nophperrors
1166 1166
 		);
1167
-		$reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
1167
+		$reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object);
1168 1168
 	}
1169 1169
 
1170 1170
 	if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
@@ -1174,29 +1174,29 @@  discard block
 block discarded – undo
1174 1174
 	}
1175 1175
 	else
1176 1176
 	{
1177
-		$error=0;
1177
+		$error = 0;
1178 1178
 
1179 1179
 		//print "x".$file." ".$disableglob;exit;
1180
-		$file_osencoded=dol_osencode($file);    // New filename encoded in OS filesystem encoding charset
1181
-		if (empty($disableglob) && ! empty($file_osencoded))
1182
-		{
1183
-			$ok=true;
1184
-			$globencoded=str_replace('[','\[',$file_osencoded);
1185
-			$globencoded=str_replace(']','\]',$globencoded);
1186
-			$listofdir=glob($globencoded);
1187
-			if (! empty($listofdir) && is_array($listofdir))
1180
+		$file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset
1181
+		if (empty($disableglob) && !empty($file_osencoded))
1182
+		{
1183
+			$ok = true;
1184
+			$globencoded = str_replace('[', '\[', $file_osencoded);
1185
+			$globencoded = str_replace(']', '\]', $globencoded);
1186
+			$listofdir = glob($globencoded);
1187
+			if (!empty($listofdir) && is_array($listofdir))
1188 1188
 			{
1189 1189
 				foreach ($listofdir as $filename)
1190 1190
 				{
1191
-					if ($nophperrors) $ok=@unlink($filename);
1192
-					else $ok=unlink($filename);
1191
+					if ($nophperrors) $ok = @unlink($filename);
1192
+					else $ok = unlink($filename);
1193 1193
 					if ($ok)
1194 1194
 					{
1195 1195
 						dol_syslog("Removed file ".$filename, LOG_DEBUG);
1196 1196
 
1197 1197
 						// Delete entry into ecm database
1198
-						$rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filename);
1199
-						if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete))     // If not a tmp file
1198
+						$rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename);
1199
+						if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete))     // If not a tmp file
1200 1200
 						{
1201 1201
 							$rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1202 1202
 
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
 							{
1205 1205
 								dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1206 1206
 								include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1207
-								$ecmfile=new EcmFiles($db);
1207
+								$ecmfile = new EcmFiles($db);
1208 1208
 								$result = $ecmfile->fetch(0, '', $rel_filetodelete);
1209 1209
 								if ($result >= 0 && $ecmfile->id > 0)
1210 1210
 								{
@@ -1226,9 +1226,9 @@  discard block
 block discarded – undo
1226 1226
 		}
1227 1227
 		else
1228 1228
 		{
1229
-			$ok=false;
1230
-			if ($nophperrors) $ok=@unlink($file_osencoded);
1231
-			else $ok=unlink($file_osencoded);
1229
+			$ok = false;
1230
+			if ($nophperrors) $ok = @unlink($file_osencoded);
1231
+			else $ok = unlink($file_osencoded);
1232 1232
 			if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
1233 1233
 			else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
1234 1234
 		}
@@ -1246,18 +1246,18 @@  discard block
 block discarded – undo
1246 1246
  *  @return boolean         		True if success, false if error
1247 1247
  *  @see dol_delete_file dol_copy
1248 1248
  */
1249
-function dol_delete_dir($dir,$nophperrors=0)
1249
+function dol_delete_dir($dir, $nophperrors = 0)
1250 1250
 {
1251 1251
 	// Security:
1252 1252
 	// We refuse transversal using .. and pipes into filenames.
1253
-	if (preg_match('/\.\./',$dir) || preg_match('/[<>|]/',$dir))
1253
+	if (preg_match('/\.\./', $dir) || preg_match('/[<>|]/', $dir))
1254 1254
 	{
1255 1255
 		dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
1256 1256
 		return false;
1257 1257
 	}
1258 1258
 
1259
-	$dir_osencoded=dol_osencode($dir);
1260
-	return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded));
1259
+	$dir_osencoded = dol_osencode($dir);
1260
+	return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
1261 1261
 }
1262 1262
 
1263 1263
 /**
@@ -1270,27 +1270,27 @@  discard block
 block discarded – undo
1270 1270
  *  @param  int		$countdeleted   Counter to count nb of elements found really deleted
1271 1271
  *  @return int             		Number of files and directory we try to remove. NB really removed is returned into var by reference $countdeleted.
1272 1272
  */
1273
-function dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
1273
+function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0)
1274 1274
 {
1275
-	dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG);
1275
+	dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
1276 1276
 	if (dol_is_dir($dir))
1277 1277
 	{
1278
-		$dir_osencoded=dol_osencode($dir);
1278
+		$dir_osencoded = dol_osencode($dir);
1279 1279
 		if ($handle = opendir("$dir_osencoded"))
1280 1280
 		{
1281 1281
 			while (false !== ($item = readdir($handle)))
1282 1282
 			{
1283
-				if (! utf8_check($item)) $item=utf8_encode($item);  // should be useless
1283
+				if (!utf8_check($item)) $item = utf8_encode($item); // should be useless
1284 1284
 
1285 1285
 				if ($item != "." && $item != "..")
1286 1286
 				{
1287
-					if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item")))
1287
+					if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item")))
1288 1288
 					{
1289
-						$count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted);
1289
+						$count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted);
1290 1290
 					}
1291 1291
 					else
1292 1292
 					{
1293
-						$result=dol_delete_file("$dir/$item", 1, $nophperrors);
1293
+						$result = dol_delete_file("$dir/$item", 1, $nophperrors);
1294 1294
 						$count++;
1295 1295
 						if ($result) $countdeleted++;
1296 1296
 						//else print 'Error on '.$item."\n";
@@ -1301,7 +1301,7 @@  discard block
 block discarded – undo
1301 1301
 
1302 1302
 			if (empty($onlysub))
1303 1303
 			{
1304
-				$result=dol_delete_dir($dir, $nophperrors);
1304
+				$result = dol_delete_dir($dir, $nophperrors);
1305 1305
 				$count++;
1306 1306
 				if ($result) $countdeleted++;
1307 1307
 				//else print 'Error on '.$dir."\n";
@@ -1323,7 +1323,7 @@  discard block
 block discarded – undo
1323 1323
  */
1324 1324
 function dol_delete_preview($object)
1325 1325
 {
1326
-	global $langs,$conf;
1326
+	global $langs, $conf;
1327 1327
 
1328 1328
 	// Define parent dir of elements
1329 1329
 	$element = $object->element;
@@ -1334,54 +1334,54 @@  discard block
 block discarded – undo
1334 1334
 	elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1335 1335
 	elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1336 1336
 	elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1337
-	else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1337
+	else $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
1338 1338
 
1339 1339
 	if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
1340 1340
 
1341 1341
 	$refsan = dol_sanitizeFileName($object->ref);
1342
-	$dir = $dir . "/" . $refsan ;
1343
-	$filepreviewnew = $dir . "/" . $refsan . ".pdf_preview.png";
1344
-	$filepreviewnewbis = $dir . "/" . $refsan . ".pdf_preview-0.png";
1345
-	$filepreviewold = $dir . "/" . $refsan . ".pdf.png";
1342
+	$dir = $dir."/".$refsan;
1343
+	$filepreviewnew = $dir."/".$refsan.".pdf_preview.png";
1344
+	$filepreviewnewbis = $dir."/".$refsan.".pdf_preview-0.png";
1345
+	$filepreviewold = $dir."/".$refsan.".pdf.png";
1346 1346
 
1347 1347
 	// For new preview files
1348 1348
 	if (file_exists($filepreviewnew) && is_writable($filepreviewnew))
1349 1349
 	{
1350
-		if (! dol_delete_file($filepreviewnew,1))
1350
+		if (!dol_delete_file($filepreviewnew, 1))
1351 1351
 		{
1352
-			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewnew);
1352
+			$object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnew);
1353 1353
 			return 0;
1354 1354
 		}
1355 1355
 	}
1356 1356
 	if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis))
1357 1357
 	{
1358
-		if (! dol_delete_file($filepreviewnewbis,1))
1358
+		if (!dol_delete_file($filepreviewnewbis, 1))
1359 1359
 		{
1360
-			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewnewbis);
1360
+			$object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis);
1361 1361
 			return 0;
1362 1362
 		}
1363 1363
 	}
1364 1364
 	// For old preview files
1365 1365
 	if (file_exists($filepreviewold) && is_writable($filepreviewold))
1366 1366
 	{
1367
-		if (! dol_delete_file($filepreviewold,1))
1367
+		if (!dol_delete_file($filepreviewold, 1))
1368 1368
 		{
1369
-			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewold);
1369
+			$object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold);
1370 1370
 			return 0;
1371 1371
 		}
1372 1372
 	}
1373 1373
 	else
1374 1374
 	{
1375
-		$multiple = $filepreviewold . ".";
1375
+		$multiple = $filepreviewold.".";
1376 1376
 		for ($i = 0; $i < 20; $i++)
1377 1377
 		{
1378 1378
 			$preview = $multiple.$i;
1379 1379
 
1380 1380
 			if (file_exists($preview) && is_writable($preview))
1381 1381
 			{
1382
-				if ( ! dol_delete_file($preview,1) )
1382
+				if (!dol_delete_file($preview, 1))
1383 1383
 				{
1384
-					$object->error=$langs->trans("ErrorFailedToOpenFile",$preview);
1384
+					$object->error = $langs->trans("ErrorFailedToOpenFile", $preview);
1385 1385
 					return 0;
1386 1386
 				}
1387 1387
 			}
@@ -1404,10 +1404,10 @@  discard block
 block discarded – undo
1404 1404
 	global $conf;
1405 1405
 
1406 1406
 	// Create meta file
1407
-	if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0;	// By default, no metafile.
1407
+	if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0; // By default, no metafile.
1408 1408
 
1409 1409
 	// Define parent dir of elements
1410
-	$element=$object->element;
1410
+	$element = $object->element;
1411 1411
 
1412 1412
 	if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->dir_output.'/commande';
1413 1413
 	elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->dir_output.'/facture';
@@ -1415,17 +1415,17 @@  discard block
 block discarded – undo
1415 1415
 	elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1416 1416
 	elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1417 1417
 	elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1418
-	else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1418
+	else $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
1419 1419
 
1420 1420
 	if ($dir)
1421 1421
 	{
1422 1422
 		$object->fetch_thirdparty();
1423 1423
 
1424 1424
 		$objectref = dol_sanitizeFileName($object->ref);
1425
-		$dir = $dir . "/" . $objectref;
1426
-		$file = $dir . "/" . $objectref . ".meta";
1425
+		$dir = $dir."/".$objectref;
1426
+		$file = $dir."/".$objectref.".meta";
1427 1427
 
1428
-		if (! is_dir($dir))
1428
+		if (!is_dir($dir))
1429 1429
 		{
1430 1430
 			dol_mkdir($dir);
1431 1431
 		}
@@ -1433,29 +1433,29 @@  discard block
 block discarded – undo
1433 1433
 		if (is_dir($dir))
1434 1434
 		{
1435 1435
 			$nblignes = count($object->lines);
1436
-			$client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
1437
-			$meta = "REFERENCE=\"" . $object->ref . "\"
1438
-			DATE=\"" . dol_print_date($object->date,'') . "\"
1439
-			NB_ITEMS=\"" . $nblignes . "\"
1440
-			CLIENT=\"" . $client . "\"
1441
-			AMOUNT_EXCL_TAX=\"" . $object->total_ht . "\"
1442
-			AMOUNT=\"" . $object->total_ttc . "\"\n";
1443
-
1444
-			for ($i = 0 ; $i < $nblignes ; $i++)
1436
+			$client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town;
1437
+			$meta = "REFERENCE=\"".$object->ref."\"
1438
+			DATE=\"" . dol_print_date($object->date, '')."\"
1439
+			NB_ITEMS=\"" . $nblignes."\"
1440
+			CLIENT=\"" . $client."\"
1441
+			AMOUNT_EXCL_TAX=\"" . $object->total_ht."\"
1442
+			AMOUNT=\"" . $object->total_ttc."\"\n";
1443
+
1444
+			for ($i = 0; $i < $nblignes; $i++)
1445 1445
 			{
1446 1446
 				//Pour les articles
1447
-				$meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
1448
-				ITEM_" . $i . "_AMOUNT_WO_TAX=\"" . $object->lines[$i]->total_ht . "\"
1449
-				ITEM_" . $i . "_VAT=\"" .$object->lines[$i]->tva_tx . "\"
1450
-				ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n","",nl2br($object->lines[$i]->desc)) . "\"
1447
+				$meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\"
1448
+				ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\"
1449
+				ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\"
1450
+				ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\"
1451 1451
 				";
1452 1452
 			}
1453 1453
 		}
1454 1454
 
1455
-		$fp = fopen($file,"w");
1456
-		fputs($fp,$meta);
1455
+		$fp = fopen($file, "w");
1456
+		fputs($fp, $meta);
1457 1457
 		fclose($fp);
1458
-		if (! empty($conf->global->MAIN_UMASK))
1458
+		if (!empty($conf->global->MAIN_UMASK))
1459 1459
 		@chmod($file, octdec($conf->global->MAIN_UMASK));
1460 1460
 
1461 1461
 		return 1;
@@ -1478,26 +1478,26 @@  discard block
 block discarded – undo
1478 1478
  * @param   string  $trackid                Track id (used to prefix name of session vars to avoid conflict)
1479 1479
  * @return	void
1480 1480
  */
1481
-function dol_init_file_process($pathtoscan='', $trackid='')
1481
+function dol_init_file_process($pathtoscan = '', $trackid = '')
1482 1482
 {
1483
-	$listofpaths=array();
1484
-	$listofnames=array();
1485
-	$listofmimes=array();
1483
+	$listofpaths = array();
1484
+	$listofnames = array();
1485
+	$listofmimes = array();
1486 1486
 
1487 1487
 	if ($pathtoscan)
1488 1488
 	{
1489
-		$listoffiles=dol_dir_list($pathtoscan,'files');
1490
-		foreach($listoffiles as $key => $val)
1489
+		$listoffiles = dol_dir_list($pathtoscan, 'files');
1490
+		foreach ($listoffiles as $key => $val)
1491 1491
 		{
1492
-			$listofpaths[]=$val['fullname'];
1493
-			$listofnames[]=$val['name'];
1494
-			$listofmimes[]=dol_mimetype($val['name']);
1492
+			$listofpaths[] = $val['fullname'];
1493
+			$listofnames[] = $val['name'];
1494
+			$listofmimes[] = dol_mimetype($val['name']);
1495 1495
 		}
1496 1496
 	}
1497
-	$keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1498
-	$_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
1499
-	$_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
1500
-	$_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
1497
+	$keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
1498
+	$_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
1499
+	$_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
1500
+	$_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
1501 1501
 }
1502 1502
 
1503 1503
 
@@ -1516,13 +1516,13 @@  discard block
 block discarded – undo
1516 1516
  * @param	int		$generatethumbs			1=Generate also thumbs for uploaded image files
1517 1517
  * @return	int                             <=0 if KO, >0 if OK
1518 1518
  */
1519
-function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1)
1519
+function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1)
1520 1520
 {
1521
-	global $db,$user,$conf,$langs;
1521
+	global $db, $user, $conf, $langs;
1522 1522
 
1523 1523
 	$res = 0;
1524 1524
 
1525
-	if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
1525
+	if (!empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
1526 1526
 	{
1527 1527
 		dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
1528 1528
 		if (dol_mkdir($upload_dir) >= 0)
@@ -1541,13 +1541,13 @@  discard block
 block discarded – undo
1541 1541
 			for ($i = 0; $i < $nbfile; $i++)
1542 1542
 			{
1543 1543
 				// Define $destfull (path to file including filename) and $destfile (only filename)
1544
-				$destfull=$upload_dir . "/" . $TFile['name'][$i];
1545
-				$destfile=$TFile['name'][$i];
1544
+				$destfull = $upload_dir."/".$TFile['name'][$i];
1545
+				$destfile = $TFile['name'][$i];
1546 1546
 
1547 1547
 				if ($savingdocmask)
1548 1548
 				{
1549
-					$destfull=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
1550
-					$destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
1549
+					$destfull = $upload_dir."/".preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
1550
+					$destfile = preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
1551 1551
 				}
1552 1552
 
1553 1553
 				// dol_sanitizeFileName the file name and lowercase extension
@@ -1608,7 +1608,7 @@  discard block
 block discarded – undo
1608 1608
 					{
1609 1609
 						setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
1610 1610
 					}
1611
-					else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
1611
+					else if (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload))	// Files infected by a virus
1612 1612
 					{
1613 1613
 						setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
1614 1614
 					}
@@ -1625,7 +1625,7 @@  discard block
 block discarded – undo
1625 1625
 			}
1626 1626
 		}
1627 1627
 	} elseif ($link) {
1628
-		require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1628
+		require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
1629 1629
 		$linkObject = new Link($db);
1630 1630
 		$linkObject->entity = $conf->entity;
1631 1631
 		$linkObject->url = $link;
@@ -1660,33 +1660,33 @@  discard block
 block discarded – undo
1660 1660
  * @param   string  $trackid                Track id (used to prefix name of session vars to avoid conflict)
1661 1661
  * @return	void
1662 1662
  */
1663
-function dol_remove_file_process($filenb,$donotupdatesession=0,$donotdeletefile=1,$trackid='')
1663
+function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '')
1664 1664
 {
1665
-	global $db,$user,$conf,$langs,$_FILES;
1665
+	global $db, $user, $conf, $langs, $_FILES;
1666 1666
 
1667
-	$keytodelete=$filenb;
1667
+	$keytodelete = $filenb;
1668 1668
 	$keytodelete--;
1669 1669
 
1670
-	$listofpaths=array();
1671
-	$listofnames=array();
1672
-	$listofmimes=array();
1673
-	$keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1674
-	if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
1675
-	if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
1676
-	if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
1670
+	$listofpaths = array();
1671
+	$listofnames = array();
1672
+	$listofmimes = array();
1673
+	$keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
1674
+	if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
1675
+	if (!empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
1676
+	if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
1677 1677
 
1678 1678
 	if ($keytodelete >= 0)
1679 1679
 	{
1680
-		$pathtodelete=$listofpaths[$keytodelete];
1681
-		$filetodelete=$listofnames[$keytodelete];
1682
-		if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);  // The delete of ecm database is inside the function dol_delete_file
1683
-		else $result=0;
1680
+		$pathtodelete = $listofpaths[$keytodelete];
1681
+		$filetodelete = $listofnames[$keytodelete];
1682
+		if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file
1683
+		else $result = 0;
1684 1684
 		if ($result >= 0)
1685 1685
 		{
1686 1686
 			if (empty($donotdeletefile))
1687 1687
 			{
1688 1688
 				$langs->load("other");
1689
-				setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
1689
+				setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
1690 1690
 			}
1691 1691
 			if (empty($donotupdatesession))
1692 1692
 			{
@@ -1712,29 +1712,29 @@  discard block
 block discarded – undo
1712 1712
  *  @param		int		$setsharekey	Set also the share key
1713 1713
  *	@return		int						<0 if KO, 0 if nothing done, >0 if OK
1714 1714
  */
1715
-function addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0)
1715
+function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0)
1716 1716
 {
1717 1717
 	global $db, $user;
1718 1718
 
1719 1719
 	$result = 0;
1720 1720
 
1721
-	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1721
+	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
1722 1722
 
1723
-	if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
1723
+	if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
1724 1724
 	{
1725 1725
 		$filename = basename($file);
1726 1726
 		$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1727 1727
 		$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1728 1728
 
1729 1729
 		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1730
-		$ecmfile=new EcmFiles($db);
1730
+		$ecmfile = new EcmFiles($db);
1731 1731
 		$ecmfile->filepath = $rel_dir;
1732 1732
 		$ecmfile->filename = $filename;
1733
-		$ecmfile->label = md5_file(dol_osencode($dir.'/'.$file));	// MD5 of file content
1733
+		$ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content
1734 1734
 		$ecmfile->fullpath_orig = $fullpathorig;
1735 1735
 		$ecmfile->gen_or_uploaded = $mode;
1736
-		$ecmfile->description = '';    // indexed content
1737
-		$ecmfile->keyword = '';        // keyword content
1736
+		$ecmfile->description = ''; // indexed content
1737
+		$ecmfile->keyword = ''; // keyword content
1738 1738
 		if ($setsharekey)
1739 1739
 		{
1740 1740
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
  *  @param		string	$mode			How file was created ('uploaded', 'generated', ...)
1761 1761
  *	@return		int						<0 if KO, 0 if nothing done, >0 if OK
1762 1762
  */
1763
-function deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded')
1763
+function deleteFilesIntoDatabaseIndex($dir, $file, $mode = 'uploaded')
1764 1764
 {
1765 1765
 	global $conf, $db, $user;
1766 1766
 
@@ -1774,32 +1774,32 @@  discard block
 block discarded – undo
1774 1774
 
1775 1775
 	$db->begin();
1776 1776
 
1777
-	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1777
+	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
1778 1778
 
1779 1779
 	$filename = basename($file);
1780 1780
 	$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1781 1781
 	$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1782 1782
 
1783
-	if (! $error)
1783
+	if (!$error)
1784 1784
 	{
1785
-		$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'ecm_files';
1786
-		$sql.= ' WHERE entity = '.$conf->entity;
1787
-		$sql.= " AND filepath = '" . $db->escape($rel_dir) . "'";
1788
-		if ($file) $sql.= " AND filename = '" . $db->escape($file) . "'";
1789
-		if ($mode) $sql.= " AND gen_or_uploaded = '" . $db->escape($mode) . "'";
1785
+		$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'ecm_files';
1786
+		$sql .= ' WHERE entity = '.$conf->entity;
1787
+		$sql .= " AND filepath = '".$db->escape($rel_dir)."'";
1788
+		if ($file) $sql .= " AND filename = '".$db->escape($file)."'";
1789
+		if ($mode) $sql .= " AND gen_or_uploaded = '".$db->escape($mode)."'";
1790 1790
 
1791 1791
 		$resql = $db->query($sql);
1792 1792
 		if (!$resql)
1793 1793
 		{
1794 1794
 			$error++;
1795
-			dol_syslog(__METHOD__ . ' ' . $db->lasterror(), LOG_ERR);
1795
+			dol_syslog(__METHOD__.' '.$db->lasterror(), LOG_ERR);
1796 1796
 		}
1797 1797
 	}
1798 1798
 
1799 1799
 	// Commit or rollback
1800 1800
 	if ($error) {
1801 1801
 		$db->rollback();
1802
-		return - 1 * $error;
1802
+		return -1 * $error;
1803 1803
 	} else {
1804 1804
 		$db->commit();
1805 1805
 		return 1;
@@ -1816,16 +1816,16 @@  discard block
 block discarded – undo
1816 1816
  *  @param	string	$fileoutput	Output filename
1817 1817
  *  @return	int					<0 if KO, 0=Nothing done, >0 if OK
1818 1818
  */
1819
-function dol_convert_file($fileinput, $ext='png', $fileoutput='')
1819
+function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '')
1820 1820
 {
1821 1821
 	global $langs;
1822 1822
 
1823 1823
 	if (class_exists('Imagick'))
1824 1824
 	{
1825
-		$image=new Imagick();
1825
+		$image = new Imagick();
1826 1826
 		try {
1827 1827
 			$ret = $image->readImage($fileinput);
1828
-		} catch(Exception $e) {
1828
+		} catch (Exception $e) {
1829 1829
 			dol_syslog("Failed to read image using Imagick. Try to install package 'apt-get install ghostscript'.", LOG_WARNING);
1830 1830
 			return 0;
1831 1831
 		}
@@ -1834,11 +1834,11 @@  discard block
 block discarded – undo
1834 1834
 			$ret = $image->setImageFormat($ext);
1835 1835
 			if ($ret)
1836 1836
 			{
1837
-				if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
1837
+				if (empty($fileoutput)) $fileoutput = $fileinput.".".$ext;
1838 1838
 
1839 1839
 				$count = $image->getNumberImages();
1840 1840
 
1841
-				if (! dol_is_file($fileoutput) || is_writeable($fileoutput))
1841
+				if (!dol_is_file($fileoutput) || is_writeable($fileoutput))
1842 1842
 				{
1843 1843
 					$ret = $image->writeImages($fileoutput, true);
1844 1844
 				}
@@ -1874,20 +1874,20 @@  discard block
 block discarded – undo
1874 1874
  * @param 	string	$mode			'gz' or 'bz' or 'zip'
1875 1875
  * @return	int						<0 if KO, >0 if OK
1876 1876
  */
1877
-function dol_compress_file($inputfile, $outputfile, $mode="gz")
1877
+function dol_compress_file($inputfile, $outputfile, $mode = "gz")
1878 1878
 {
1879
-	$foundhandler=0;
1879
+	$foundhandler = 0;
1880 1880
 
1881 1881
 	try
1882 1882
 	{
1883 1883
 		$data = implode("", file(dol_osencode($inputfile)));
1884
-		if ($mode == 'gz')     { $foundhandler=1; $compressdata = gzencode($data, 9); }
1885
-		elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
1884
+		if ($mode == 'gz') { $foundhandler = 1; $compressdata = gzencode($data, 9); }
1885
+		elseif ($mode == 'bz') { $foundhandler = 1; $compressdata = bzcompress($data, 9); }
1886 1886
 		elseif ($mode == 'zip')
1887 1887
 		{
1888 1888
 			if (defined('ODTPHP_PATHTOPCLZIP'))
1889 1889
 			{
1890
-				$foundhandler=1;
1890
+				$foundhandler = 1;
1891 1891
 
1892 1892
 				include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
1893 1893
 				$archive = new PclZip($outputfile);
@@ -1906,7 +1906,7 @@  discard block
 block discarded – undo
1906 1906
 		}
1907 1907
 		else
1908 1908
 		{
1909
-			dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
1909
+			dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR);
1910 1910
 			return -2;
1911 1911
 		}
1912 1912
 	}
@@ -1914,8 +1914,8 @@  discard block
 block discarded – undo
1914 1914
 	{
1915 1915
 		global $langs, $errormsg;
1916 1916
 		$langs->load("errors");
1917
-		dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
1918
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir");
1917
+		dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
1918
+		$errormsg = $langs->trans("ErrorFailedToWriteInDir");
1919 1919
 		return -1;
1920 1920
 	}
1921 1921
 }
@@ -1927,7 +1927,7 @@  discard block
 block discarded – undo
1927 1927
  * @param 	string	$outputdir		Target dir name
1928 1928
  * @return 	array					array('error'=>'Error code') or array() if no error
1929 1929
  */
1930
-function dol_uncompress($inputfile,$outputdir)
1930
+function dol_uncompress($inputfile, $outputdir)
1931 1931
 {
1932 1932
 	global $langs;
1933 1933
 
@@ -1936,20 +1936,20 @@  discard block
 block discarded – undo
1936 1936
 		dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
1937 1937
 		include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
1938 1938
 		$archive = new PclZip($inputfile);
1939
-		$result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
1939
+		$result = $archive->extract(PCLZIP_OPT_PATH, $outputdir);
1940 1940
 		//var_dump($result);
1941
-		if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
1941
+		if (!is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
1942 1942
 		else
1943 1943
 		{
1944
-			$ok=1; $errmsg='';
1944
+			$ok = 1; $errmsg = '';
1945 1945
 			// Loop on each file to check result for unzipping file
1946
-			foreach($result as $key => $val)
1946
+			foreach ($result as $key => $val)
1947 1947
 			{
1948 1948
 				if ($val['status'] == 'path_creation_fail')
1949 1949
 				{
1950 1950
 					$langs->load("errors");
1951
-					$ok=0;
1952
-					$errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']);
1951
+					$ok = 0;
1952
+					$errmsg = $langs->trans("ErrorFailToCreateDir", $val['filename']);
1953 1953
 					break;
1954 1954
 				}
1955 1955
 			}
@@ -1988,24 +1988,24 @@  discard block
 block discarded – undo
1988 1988
  * @param 	string	$mode			'zip'
1989 1989
  * @return	int						<0 if KO, >0 if OK
1990 1990
  */
1991
-function dol_compress_dir($inputdir, $outputfile, $mode="zip")
1991
+function dol_compress_dir($inputdir, $outputfile, $mode = "zip")
1992 1992
 {
1993
-	$foundhandler=0;
1993
+	$foundhandler = 0;
1994 1994
 
1995 1995
 	dol_syslog("Try to zip dir ".$inputdir." into ".$outputdir." mode=".$mode);
1996 1996
 
1997
-	if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile)))
1997
+	if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile)))
1998 1998
 	{
1999 1999
 		global $langs, $errormsg;
2000 2000
 		$langs->load("errors");
2001
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile);
2001
+		$errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
2002 2002
 		return -3;
2003 2003
 	}
2004 2004
 
2005 2005
 	try
2006 2006
 	{
2007
-		if ($mode == 'gz')     { $foundhandler=0; }
2008
-		elseif ($mode == 'bz') { $foundhandler=0; }
2007
+		if ($mode == 'gz') { $foundhandler = 0; }
2008
+		elseif ($mode == 'bz') { $foundhandler = 0; }
2009 2009
 		elseif ($mode == 'zip')
2010 2010
 		{
2011 2011
 			/*if (defined('ODTPHP_PATHTOPCLZIP'))
@@ -2021,7 +2021,7 @@  discard block
 block discarded – undo
2021 2021
             else*/
2022 2022
 			if (class_exists('ZipArchive'))
2023 2023
 			{
2024
-				$foundhandler=1;
2024
+				$foundhandler = 1;
2025 2025
 
2026 2026
 				// Initialize archive object
2027 2027
 				$zip = new ZipArchive();
@@ -2055,9 +2055,9 @@  discard block
 block discarded – undo
2055 2055
 			}
2056 2056
 		}
2057 2057
 
2058
-		if (! $foundhandler)
2058
+		if (!$foundhandler)
2059 2059
 		{
2060
-			dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
2060
+			dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR);
2061 2061
 			return -2;
2062 2062
 		}
2063 2063
 		else
@@ -2071,7 +2071,7 @@  discard block
 block discarded – undo
2071 2071
 		$langs->load("errors");
2072 2072
 		dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
2073 2073
 		dol_syslog($e->getMessage(), LOG_ERR);
2074
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile);
2074
+		$errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
2075 2075
 		return -1;
2076 2076
 	}
2077 2077
 }
@@ -2088,9 +2088,9 @@  discard block
 block discarded – undo
2088 2088
  * @param	int			$mode			0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only
2089 2089
  * @return	string						Full path to most recent file
2090 2090
  */
2091
-function dol_most_recent_file($dir,$regexfilter='',$excludefilter=array('(\.meta|_preview.*\.png)$','^\.'),$nohook=false,$mode='')
2091
+function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = false, $mode = '')
2092 2092
 {
2093
-	$tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,$mode,$nohook);
2093
+	$tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook);
2094 2094
 	return $tmparray[0];
2095 2095
 }
2096 2096
 
@@ -2106,278 +2106,278 @@  discard block
 block discarded – undo
2106 2106
  * @return	mixed						Array with access information : 'accessallowed' & 'sqlprotectagainstexternals' & 'original_file' (as a full path name)
2107 2107
  * @see restrictedArea
2108 2108
  */
2109
-function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser='', $refname='', $mode='read')
2109
+function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser = '', $refname = '', $mode = 'read')
2110 2110
 {
2111 2111
 	global $conf, $db, $user;
2112 2112
 	global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2113 2113
 
2114
-	if (! is_object($fuser)) $fuser=$user;
2114
+	if (!is_object($fuser)) $fuser = $user;
2115 2115
 
2116 2116
 	if (empty($modulepart)) return 'ErrorBadParameter';
2117 2117
 	if (empty($entity))
2118 2118
 	{
2119
-		if (empty($conf->multicompany->enabled)) $entity=1;
2120
-		else $entity=0;
2119
+		if (empty($conf->multicompany->enabled)) $entity = 1;
2120
+		else $entity = 0;
2121 2121
 	}
2122 2122
 	// Fix modulepart
2123
-	if ($modulepart == 'users') $modulepart='user';
2123
+	if ($modulepart == 'users') $modulepart = 'user';
2124 2124
 
2125 2125
 	dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
2126 2126
 	// We define $accessallowed and $sqlprotectagainstexternals
2127
-	$accessallowed=0;
2128
-	$sqlprotectagainstexternals='';
2129
-	$ret=array();
2127
+	$accessallowed = 0;
2128
+	$sqlprotectagainstexternals = '';
2129
+	$ret = array();
2130 2130
 
2131 2131
 	// Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
2132
-	if (empty($refname)) $refname=basename(dirname($original_file)."/");
2132
+	if (empty($refname)) $refname = basename(dirname($original_file)."/");
2133 2133
 
2134 2134
 	$relative_original_file = $original_file;
2135 2135
 
2136 2136
 	// Define possible keys to use for permission check
2137
-	$lire='lire'; $read='read'; $download='download';
2137
+	$lire = 'lire'; $read = 'read'; $download = 'download';
2138 2138
 	if ($mode == 'write')
2139 2139
 	{
2140
-		$lire='creer'; $read='write'; $download='upload';
2140
+		$lire = 'creer'; $read = 'write'; $download = 'upload';
2141 2141
 	}
2142 2142
 
2143 2143
 	// Wrapping for miscellaneous medias files
2144 2144
 	if ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
2145 2145
 	{
2146 2146
 		if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2147
-		$accessallowed=1;
2148
-		$original_file=$conf->medias->multidir_output[$entity].'/'.$original_file;
2147
+		$accessallowed = 1;
2148
+		$original_file = $conf->medias->multidir_output[$entity].'/'.$original_file;
2149 2149
 	}
2150 2150
 	// Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
2151 2151
 	elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root))
2152 2152
 	{
2153
-		$accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
2154
-		$original_file=$dolibarr_main_data_root.'/'.$original_file;
2153
+		$accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
2154
+		$original_file = $dolibarr_main_data_root.'/'.$original_file;
2155 2155
 	}
2156 2156
 	// Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
2157 2157
 	elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root))
2158 2158
 	{
2159 2159
 		// Dir for custom dirs
2160
-		$tmp=explode(',', $dolibarr_main_document_root_alt);
2160
+		$tmp = explode(',', $dolibarr_main_document_root_alt);
2161 2161
 		$dirins = $tmp[0];
2162 2162
 
2163
-		$accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
2164
-		$original_file=$dirins.'/'.$original_file;
2163
+		$accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
2164
+		$original_file = $dirins.'/'.$original_file;
2165 2165
 	}
2166 2166
 	// Wrapping for some images
2167 2167
 	elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output))
2168 2168
 	{
2169
-		$accessallowed=1;
2170
-		$original_file=$conf->mycompany->dir_output.'/'.$original_file;
2169
+		$accessallowed = 1;
2170
+		$original_file = $conf->mycompany->dir_output.'/'.$original_file;
2171 2171
 	}
2172 2172
 	// Wrapping for users photos
2173 2173
 	elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output))
2174 2174
 	{
2175
-		$accessallowed=1;
2176
-		$original_file=$conf->user->dir_output.'/'.$original_file;
2175
+		$accessallowed = 1;
2176
+		$original_file = $conf->user->dir_output.'/'.$original_file;
2177 2177
 	}
2178 2178
 	// Wrapping for members photos
2179 2179
 	elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output))
2180 2180
 	{
2181
-		$accessallowed=1;
2182
-		$original_file=$conf->adherent->dir_output.'/'.$original_file;
2181
+		$accessallowed = 1;
2182
+		$original_file = $conf->adherent->dir_output.'/'.$original_file;
2183 2183
 	}
2184 2184
 	// Wrapping pour les apercu factures
2185 2185
 	elseif ($modulepart == 'apercufacture' && !empty($conf->facture->dir_output))
2186 2186
 	{
2187
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2188
-		$original_file=$conf->facture->dir_output.'/'.$original_file;
2187
+		if ($fuser->rights->facture->{$lire}) $accessallowed = 1;
2188
+		$original_file = $conf->facture->dir_output.'/'.$original_file;
2189 2189
 	}
2190 2190
 	// Wrapping pour les apercu propal
2191 2191
 	elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity]))
2192 2192
 	{
2193
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2194
-		$original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2193
+		if ($fuser->rights->propale->{$lire}) $accessallowed = 1;
2194
+		$original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
2195 2195
 	}
2196 2196
 	// Wrapping pour les apercu commande
2197 2197
 	elseif ($modulepart == 'apercucommande' && !empty($conf->commande->dir_output))
2198 2198
 	{
2199
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2200
-		$original_file=$conf->commande->dir_output.'/'.$original_file;
2199
+		if ($fuser->rights->commande->{$lire}) $accessallowed = 1;
2200
+		$original_file = $conf->commande->dir_output.'/'.$original_file;
2201 2201
 	}
2202 2202
 	// Wrapping pour les apercu intervention
2203 2203
 	elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output))
2204 2204
 	{
2205
-		if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1;
2206
-		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2205
+		if ($fuser->rights->ficheinter->{$lire}) $accessallowed = 1;
2206
+		$original_file = $conf->ficheinter->dir_output.'/'.$original_file;
2207 2207
 	}
2208 2208
 	// Wrapping pour les apercu conat
2209 2209
 	elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output))
2210 2210
 	{
2211
-		if ($fuser->rights->contrat->{$lire}) $accessallowed=1;
2212
-		$original_file=$conf->contrat->dir_output.'/'.$original_file;
2211
+		if ($fuser->rights->contrat->{$lire}) $accessallowed = 1;
2212
+		$original_file = $conf->contrat->dir_output.'/'.$original_file;
2213 2213
 	}
2214 2214
 	// Wrapping pour les apercu supplier proposal
2215 2215
 	elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
2216 2216
 	{
2217
-		if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1;
2218
-		$original_file=$conf->supplier_proposal->dir_output.'/'.$original_file;
2217
+		if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed = 1;
2218
+		$original_file = $conf->supplier_proposal->dir_output.'/'.$original_file;
2219 2219
 	}
2220 2220
 	// Wrapping pour les apercu supplier order
2221 2221
 	elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
2222 2222
 	{
2223
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2224
-		$original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2223
+		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1;
2224
+		$original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
2225 2225
 	}
2226 2226
 	// Wrapping pour les apercu supplier invoice
2227 2227
 	elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
2228 2228
 	{
2229
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2230
-		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2229
+		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1;
2230
+		$original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
2231 2231
 	}
2232 2232
 	// Wrapping pour les apercu supplier invoice
2233 2233
 	elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output))
2234 2234
 	{
2235
-		if ($fuser->rights->expensereport->{$lire}) $accessallowed=1;
2236
-		$original_file=$conf->expensereport->dir_output.'/'.$original_file;
2235
+		if ($fuser->rights->expensereport->{$lire}) $accessallowed = 1;
2236
+		$original_file = $conf->expensereport->dir_output.'/'.$original_file;
2237 2237
 	}
2238 2238
 	// Wrapping pour les images des stats propales
2239 2239
 	elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity]))
2240 2240
 	{
2241
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2242
-		$original_file=$conf->propal->multidir_temp[$entity].'/'.$original_file;
2241
+		if ($fuser->rights->propale->{$lire}) $accessallowed = 1;
2242
+		$original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file;
2243 2243
 	}
2244 2244
 	// Wrapping pour les images des stats commandes
2245 2245
 	elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
2246 2246
 	{
2247
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2248
-		$original_file=$conf->commande->dir_temp.'/'.$original_file;
2247
+		if ($fuser->rights->commande->{$lire}) $accessallowed = 1;
2248
+		$original_file = $conf->commande->dir_temp.'/'.$original_file;
2249 2249
 	}
2250 2250
 	elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
2251 2251
 	{
2252
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2253
-		$original_file=$conf->fournisseur->commande->dir_temp.'/'.$original_file;
2252
+		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1;
2253
+		$original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file;
2254 2254
 	}
2255 2255
 	// Wrapping pour les images des stats factures
2256 2256
 	elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
2257 2257
 	{
2258
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2259
-		$original_file=$conf->facture->dir_temp.'/'.$original_file;
2258
+		if ($fuser->rights->facture->{$lire}) $accessallowed = 1;
2259
+		$original_file = $conf->facture->dir_temp.'/'.$original_file;
2260 2260
 	}
2261 2261
 	elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
2262 2262
 	{
2263
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2264
-		$original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file;
2263
+		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1;
2264
+		$original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file;
2265 2265
 	}
2266 2266
 	// Wrapping pour les images des stats expeditions
2267 2267
 	elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
2268 2268
 	{
2269
-		if ($fuser->rights->expedition->{$lire}) $accessallowed=1;
2270
-		$original_file=$conf->expedition->dir_temp.'/'.$original_file;
2269
+		if ($fuser->rights->expedition->{$lire}) $accessallowed = 1;
2270
+		$original_file = $conf->expedition->dir_temp.'/'.$original_file;
2271 2271
 	}
2272 2272
 	// Wrapping pour les images des stats expeditions
2273 2273
 	elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
2274 2274
 	{
2275
-		if ($fuser->rights->deplacement->{$lire}) $accessallowed=1;
2276
-		$original_file=$conf->deplacement->dir_temp.'/'.$original_file;
2275
+		if ($fuser->rights->deplacement->{$lire}) $accessallowed = 1;
2276
+		$original_file = $conf->deplacement->dir_temp.'/'.$original_file;
2277 2277
 	}
2278 2278
 	// Wrapping pour les images des stats expeditions
2279 2279
 	elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
2280 2280
 	{
2281
-		if ($fuser->rights->adherent->{$lire}) $accessallowed=1;
2282
-		$original_file=$conf->adherent->dir_temp.'/'.$original_file;
2281
+		if ($fuser->rights->adherent->{$lire}) $accessallowed = 1;
2282
+		$original_file = $conf->adherent->dir_temp.'/'.$original_file;
2283 2283
 	}
2284 2284
 	// Wrapping pour les images des stats produits
2285
-	elseif (preg_match('/^productstats_/i',$modulepart) && !empty($conf->product->dir_temp))
2285
+	elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp))
2286 2286
 	{
2287
-		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed=1;
2288
-		$original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
2287
+		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed = 1;
2288
+		$original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file;
2289 2289
 	}
2290 2290
 	// Wrapping for taxes
2291 2291
 	elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
2292 2292
 	{
2293
-		if ($fuser->rights->tax->charges->{$lire}) $accessallowed=1;
2294
-		$original_file=$conf->tax->dir_output.'/'.$original_file;
2293
+		if ($fuser->rights->tax->charges->{$lire}) $accessallowed = 1;
2294
+		$original_file = $conf->tax->dir_output.'/'.$original_file;
2295 2295
 	}
2296 2296
 	// Wrapping for events
2297 2297
 	elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2298 2298
 	{
2299
-		if ($fuser->rights->agenda->myactions->{$read}) $accessallowed=1;
2300
-		$original_file=$conf->agenda->dir_output.'/'.$original_file;
2299
+		if ($fuser->rights->agenda->myactions->{$read}) $accessallowed = 1;
2300
+		$original_file = $conf->agenda->dir_output.'/'.$original_file;
2301 2301
 	}
2302 2302
 	// Wrapping for categories
2303 2303
 	elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
2304 2304
 	{
2305 2305
 		if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2306
-		if ($fuser->rights->categorie->{$lire}) $accessallowed=1;
2307
-		$original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
2306
+		if ($fuser->rights->categorie->{$lire}) $accessallowed = 1;
2307
+		$original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file;
2308 2308
 	}
2309 2309
 	// Wrapping pour les prelevements
2310 2310
 	elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
2311 2311
 	{
2312
-		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i',$original_file)) $accessallowed=1;
2313
-		$original_file=$conf->prelevement->dir_output.'/'.$original_file;
2312
+		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) $accessallowed = 1;
2313
+		$original_file = $conf->prelevement->dir_output.'/'.$original_file;
2314 2314
 	}
2315 2315
 	// Wrapping pour les graph energie
2316 2316
 	elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp))
2317 2317
 	{
2318
-		$accessallowed=1;
2319
-		$original_file=$conf->stock->dir_temp.'/'.$original_file;
2318
+		$accessallowed = 1;
2319
+		$original_file = $conf->stock->dir_temp.'/'.$original_file;
2320 2320
 	}
2321 2321
 	// Wrapping pour les graph fournisseurs
2322 2322
 	elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp))
2323 2323
 	{
2324
-		$accessallowed=1;
2325
-		$original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
2324
+		$accessallowed = 1;
2325
+		$original_file = $conf->fournisseur->dir_temp.'/'.$original_file;
2326 2326
 	}
2327 2327
 	// Wrapping pour les graph des produits
2328 2328
 	elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp))
2329 2329
 	{
2330
-		$accessallowed=1;
2331
-		$original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
2330
+		$accessallowed = 1;
2331
+		$original_file = $conf->product->multidir_temp[$entity].'/'.$original_file;
2332 2332
 	}
2333 2333
 	// Wrapping pour les code barre
2334 2334
 	elseif ($modulepart == 'barcode')
2335 2335
 	{
2336
-		$accessallowed=1;
2336
+		$accessallowed = 1;
2337 2337
 		// If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
2338 2338
 		//$original_file=$conf->barcode->dir_temp.'/'.$original_file;
2339
-		$original_file='';
2339
+		$original_file = '';
2340 2340
 	}
2341 2341
 	// Wrapping pour les icones de background des mailings
2342 2342
 	elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp))
2343 2343
 	{
2344
-		$accessallowed=1;
2345
-		$original_file=$conf->mailing->dir_temp.'/'.$original_file;
2344
+		$accessallowed = 1;
2345
+		$original_file = $conf->mailing->dir_temp.'/'.$original_file;
2346 2346
 	}
2347 2347
 	// Wrapping pour le scanner
2348 2348
 	elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2349 2349
 	{
2350
-		$accessallowed=1;
2351
-		$original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2350
+		$accessallowed = 1;
2351
+		$original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2352 2352
 	}
2353 2353
 	// Wrapping pour les images fckeditor
2354 2354
 	elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output))
2355 2355
 	{
2356
-		$accessallowed=1;
2357
-		$original_file=$conf->fckeditor->dir_output.'/'.$original_file;
2356
+		$accessallowed = 1;
2357
+		$original_file = $conf->fckeditor->dir_output.'/'.$original_file;
2358 2358
 	}
2359 2359
 
2360 2360
 	// Wrapping for users
2361 2361
 	else if ($modulepart == 'user' && !empty($conf->user->dir_output))
2362 2362
 	{
2363
-		$canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2364
-		if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card
2365
-		if ($canreaduser || preg_match('/^specimen/i',$original_file))
2363
+		$canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
2364
+		if ($fuser->id == (int) $refname) { $canreaduser = 1; } // A user can always read its own card
2365
+		if ($canreaduser || preg_match('/^specimen/i', $original_file))
2366 2366
 		{
2367
-			$accessallowed=1;
2367
+			$accessallowed = 1;
2368 2368
 		}
2369
-		$original_file=$conf->user->dir_output.'/'.$original_file;
2369
+		$original_file = $conf->user->dir_output.'/'.$original_file;
2370 2370
 	}
2371 2371
 
2372 2372
 	// Wrapping for third parties
2373 2373
 	else if (($modulepart == 'company' || $modulepart == 'societe') && !empty($conf->societe->dir_output))
2374 2374
 	{
2375 2375
 		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2376
-		if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i',$original_file))
2376
+		if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i', $original_file))
2377 2377
 		{
2378
-			$accessallowed=1;
2378
+			$accessallowed = 1;
2379 2379
 		}
2380
-		$original_file=$conf->societe->multidir_output[$entity].'/'.$original_file;
2380
+		$original_file = $conf->societe->multidir_output[$entity].'/'.$original_file;
2381 2381
 		$sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")";
2382 2382
 	}
2383 2383
 
@@ -2387,246 +2387,246 @@  discard block
 block discarded – undo
2387 2387
 		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2388 2388
 		if ($fuser->rights->societe->{$lire})
2389 2389
 		{
2390
-			$accessallowed=1;
2390
+			$accessallowed = 1;
2391 2391
 		}
2392
-		$original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file;
2392
+		$original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file;
2393 2393
 	}
2394 2394
 
2395 2395
 	// Wrapping for invoices
2396 2396
 	else if (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->dir_output))
2397 2397
 	{
2398
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2398
+		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2399 2399
 		{
2400
-			$accessallowed=1;
2400
+			$accessallowed = 1;
2401 2401
 		}
2402
-		$original_file=$conf->facture->dir_output.'/'.$original_file;
2402
+		$original_file = $conf->facture->dir_output.'/'.$original_file;
2403 2403
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2404 2404
 	}
2405 2405
 	// Wrapping for mass actions
2406 2406
 	else if ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity]))
2407 2407
 	{
2408
-		if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i',$original_file))
2408
+		if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i', $original_file))
2409 2409
 		{
2410
-			$accessallowed=1;
2410
+			$accessallowed = 1;
2411 2411
 		}
2412
-		$original_file=$conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2412
+		$original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2413 2413
 	}
2414 2414
 	else if ($modulepart == 'massfilesarea_orders')
2415 2415
 	{
2416
-		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2416
+		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file))
2417 2417
 		{
2418
-			$accessallowed=1;
2418
+			$accessallowed = 1;
2419 2419
 		}
2420
-		$original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2420
+		$original_file = $conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2421 2421
 	}
2422 2422
 	else if ($modulepart == 'massfilesarea_invoices')
2423 2423
 	{
2424
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2424
+		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2425 2425
 		{
2426
-			$accessallowed=1;
2426
+			$accessallowed = 1;
2427 2427
 		}
2428
-		$original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2428
+		$original_file = $conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2429 2429
 	}
2430 2430
 	else if ($modulepart == 'massfilesarea_expensereport')
2431 2431
 	{
2432
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2432
+		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2433 2433
 		{
2434
-			$accessallowed=1;
2434
+			$accessallowed = 1;
2435 2435
 		}
2436
-		$original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2436
+		$original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2437 2437
 	}
2438 2438
 	else if ($modulepart == 'massfilesarea_interventions')
2439 2439
 	{
2440
-		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2440
+		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file))
2441 2441
 		{
2442
-			$accessallowed=1;
2442
+			$accessallowed = 1;
2443 2443
 		}
2444
-		$original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2444
+		$original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2445 2445
 	}
2446 2446
 	else if ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
2447 2447
 	{
2448
-		if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i',$original_file))
2448
+		if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i', $original_file))
2449 2449
 		{
2450
-			$accessallowed=1;
2450
+			$accessallowed = 1;
2451 2451
 		}
2452
-		$original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2452
+		$original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2453 2453
 	}
2454 2454
 	else if ($modulepart == 'massfilesarea_supplier_order')
2455 2455
 	{
2456
-		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2456
+		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file))
2457 2457
 		{
2458
-			$accessallowed=1;
2458
+			$accessallowed = 1;
2459 2459
 		}
2460
-		$original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2460
+		$original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2461 2461
 	}
2462 2462
 	else if ($modulepart == 'massfilesarea_supplier_invoice')
2463 2463
 	{
2464
-		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2464
+		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2465 2465
 		{
2466
-			$accessallowed=1;
2466
+			$accessallowed = 1;
2467 2467
 		}
2468
-		$original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2468
+		$original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2469 2469
 	}
2470 2470
 	else if ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output))
2471 2471
 	{
2472
-		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2472
+		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file))
2473 2473
 		{
2474
-			$accessallowed=1;
2474
+			$accessallowed = 1;
2475 2475
 		}
2476
-		$original_file=$conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2476
+		$original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2477 2477
 	}
2478 2478
 
2479 2479
 	// Wrapping for interventions
2480 2480
 	else if (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output))
2481 2481
 	{
2482
-		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2482
+		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file))
2483 2483
 		{
2484
-			$accessallowed=1;
2484
+			$accessallowed = 1;
2485 2485
 		}
2486
-		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2486
+		$original_file = $conf->ficheinter->dir_output.'/'.$original_file;
2487 2487
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2488 2488
 	}
2489 2489
 
2490 2490
 	// Wrapping pour les deplacements et notes de frais
2491 2491
 	else if ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output))
2492 2492
 	{
2493
-		if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i',$original_file))
2493
+		if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i', $original_file))
2494 2494
 		{
2495
-			$accessallowed=1;
2495
+			$accessallowed = 1;
2496 2496
 		}
2497
-		$original_file=$conf->deplacement->dir_output.'/'.$original_file;
2497
+		$original_file = $conf->deplacement->dir_output.'/'.$original_file;
2498 2498
 		//$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2499 2499
 	}
2500 2500
 	// Wrapping pour les propales
2501 2501
 	else if (($modulepart == 'propal' || $modulepart == 'propale') && !empty($conf->propal->multidir_output[$entity]))
2502 2502
 	{
2503
-		if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i',$original_file))
2503
+		if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i', $original_file))
2504 2504
 		{
2505
-			$accessallowed=1;
2505
+			$accessallowed = 1;
2506 2506
 		}
2507
-		$original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2507
+		$original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
2508 2508
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2509 2509
 	}
2510 2510
 
2511 2511
 	// Wrapping pour les commandes
2512 2512
 	else if (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->dir_output))
2513 2513
 	{
2514
-		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2514
+		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file))
2515 2515
 		{
2516
-			$accessallowed=1;
2516
+			$accessallowed = 1;
2517 2517
 		}
2518
-		$original_file=$conf->commande->dir_output.'/'.$original_file;
2518
+		$original_file = $conf->commande->dir_output.'/'.$original_file;
2519 2519
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2520 2520
 	}
2521 2521
 
2522 2522
 	// Wrapping pour les projets
2523 2523
 	else if ($modulepart == 'project' && !empty($conf->projet->dir_output))
2524 2524
 	{
2525
-		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2525
+		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file))
2526 2526
 		{
2527
-			$accessallowed=1;
2527
+			$accessallowed = 1;
2528 2528
 		}
2529
-		$original_file=$conf->projet->dir_output.'/'.$original_file;
2529
+		$original_file = $conf->projet->dir_output.'/'.$original_file;
2530 2530
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2531 2531
 	}
2532 2532
 	else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
2533 2533
 	{
2534
-		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2534
+		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file))
2535 2535
 		{
2536
-			$accessallowed=1;
2536
+			$accessallowed = 1;
2537 2537
 		}
2538
-		$original_file=$conf->projet->dir_output.'/'.$original_file;
2538
+		$original_file = $conf->projet->dir_output.'/'.$original_file;
2539 2539
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2540 2540
 	}
2541 2541
 
2542 2542
 	// Wrapping pour les commandes fournisseurs
2543 2543
 	else if (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output))
2544 2544
 	{
2545
-		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2545
+		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file))
2546 2546
 		{
2547
-			$accessallowed=1;
2547
+			$accessallowed = 1;
2548 2548
 		}
2549
-		$original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2549
+		$original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
2550 2550
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2551 2551
 	}
2552 2552
 
2553 2553
 	// Wrapping pour les factures fournisseurs
2554 2554
 	else if (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output))
2555 2555
 	{
2556
-		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2556
+		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2557 2557
 		{
2558
-			$accessallowed=1;
2558
+			$accessallowed = 1;
2559 2559
 		}
2560
-		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2560
+		$original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
2561 2561
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE facnumber='".$db->escape($refname)."' AND entity=".$conf->entity;
2562 2562
 	}
2563 2563
 	// Wrapping pour les rapport de paiements
2564 2564
 	else if ($modulepart == 'supplier_payment')
2565 2565
 	{
2566
-		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2566
+		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2567 2567
 		{
2568
-			$accessallowed=1;
2568
+			$accessallowed = 1;
2569 2569
 		}
2570
-		$original_file=$conf->fournisseur->payment->dir_output.'/'.$original_file;
2570
+		$original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file;
2571 2571
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2572 2572
 	}
2573 2573
 
2574 2574
 	// Wrapping pour les rapport de paiements
2575 2575
 	else if ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output))
2576 2576
 	{
2577
-		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2577
+		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
2578 2578
 		{
2579
-			$accessallowed=1;
2579
+			$accessallowed = 1;
2580 2580
 		}
2581
-		if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2582
-		else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
2581
+		if ($fuser->societe_id > 0) $original_file = $conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2582
+		else $original_file = $conf->facture->dir_output.'/payments/'.$original_file;
2583 2583
 	}
2584 2584
 
2585 2585
 	// Wrapping for accounting exports
2586 2586
 	else if ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output))
2587 2587
 	{
2588
-		if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i',$original_file))
2588
+		if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i', $original_file))
2589 2589
 		{
2590
-			$accessallowed=1;
2590
+			$accessallowed = 1;
2591 2591
 		}
2592
-		$original_file=$conf->accounting->dir_output.'/'.$original_file;
2592
+		$original_file = $conf->accounting->dir_output.'/'.$original_file;
2593 2593
 	}
2594 2594
 
2595 2595
 	// Wrapping pour les expedition
2596 2596
 	else if ($modulepart == 'expedition' && !empty($conf->expedition->dir_output))
2597 2597
 	{
2598
-		if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i',$original_file))
2598
+		if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file))
2599 2599
 		{
2600
-			$accessallowed=1;
2600
+			$accessallowed = 1;
2601 2601
 		}
2602
-		$original_file=$conf->expedition->dir_output."/sending/".$original_file;
2602
+		$original_file = $conf->expedition->dir_output."/sending/".$original_file;
2603 2603
 	}
2604 2604
 	// Wrapping pour les bons de livraison
2605 2605
 	else if ($modulepart == 'livraison' && !empty($conf->expedition->dir_output))
2606 2606
 	{
2607
-		if ($fuser->rights->expedition->livraison->{$lire} || preg_match('/^specimen/i',$original_file))
2607
+		if ($fuser->rights->expedition->livraison->{$lire} || preg_match('/^specimen/i', $original_file))
2608 2608
 		{
2609
-			$accessallowed=1;
2609
+			$accessallowed = 1;
2610 2610
 		}
2611
-		$original_file=$conf->expedition->dir_output."/receipt/".$original_file;
2611
+		$original_file = $conf->expedition->dir_output."/receipt/".$original_file;
2612 2612
 	}
2613 2613
 
2614 2614
 	// Wrapping pour les actions
2615 2615
 	else if ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2616 2616
 	{
2617
-		if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i',$original_file))
2617
+		if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i', $original_file))
2618 2618
 		{
2619
-			$accessallowed=1;
2619
+			$accessallowed = 1;
2620 2620
 		}
2621
-		$original_file=$conf->agenda->dir_output.'/'.$original_file;
2621
+		$original_file = $conf->agenda->dir_output.'/'.$original_file;
2622 2622
 	}
2623 2623
 
2624 2624
 	// Wrapping pour les actions
2625 2625
 	else if ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp))
2626 2626
 	{
2627
-		if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i',$original_file))
2627
+		if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i', $original_file))
2628 2628
 		{
2629
-			$accessallowed=1;
2629
+			$accessallowed = 1;
2630 2630
 		}
2631 2631
 		$original_file = $conf->agenda->dir_temp."/".$original_file;
2632 2632
 	}
@@ -2635,65 +2635,65 @@  discard block
 block discarded – undo
2635 2635
 	else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
2636 2636
 	{
2637 2637
 		if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2638
-		if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i',$original_file))
2638
+		if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i', $original_file))
2639 2639
 		{
2640
-			$accessallowed=1;
2640
+			$accessallowed = 1;
2641 2641
 		}
2642
-		if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
2643
-		elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
2642
+		if (!empty($conf->product->enabled)) $original_file = $conf->product->multidir_output[$entity].'/'.$original_file;
2643
+		elseif (!empty($conf->service->enabled)) $original_file = $conf->service->multidir_output[$entity].'/'.$original_file;
2644 2644
 	}
2645 2645
 
2646 2646
 	// Wrapping pour les lots produits
2647 2647
 	else if ($modulepart == 'product_batch' || $modulepart == 'produitlot')
2648 2648
 	{
2649 2649
 		if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2650
-		if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i',$original_file))
2650
+		if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i', $original_file))
2651 2651
 		{
2652
-			$accessallowed=1;
2652
+			$accessallowed = 1;
2653 2653
 		}
2654
-		if (! empty($conf->productbatch->enabled)) $original_file=$conf->productbatch->multidir_output[$entity].'/'.$original_file;
2654
+		if (!empty($conf->productbatch->enabled)) $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file;
2655 2655
 	}
2656 2656
 
2657 2657
 	// Wrapping pour les contrats
2658 2658
 	else if ($modulepart == 'contract' && !empty($conf->contrat->dir_output))
2659 2659
 	{
2660
-		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2660
+		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file))
2661 2661
 		{
2662
-			$accessallowed=1;
2662
+			$accessallowed = 1;
2663 2663
 		}
2664
-		$original_file=$conf->contrat->dir_output.'/'.$original_file;
2664
+		$original_file = $conf->contrat->dir_output.'/'.$original_file;
2665 2665
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
2666 2666
 	}
2667 2667
 
2668 2668
 	// Wrapping pour les dons
2669 2669
 	else if ($modulepart == 'donation' && !empty($conf->don->dir_output))
2670 2670
 	{
2671
-		if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i',$original_file))
2671
+		if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i', $original_file))
2672 2672
 		{
2673
-			$accessallowed=1;
2673
+			$accessallowed = 1;
2674 2674
 		}
2675
-		$original_file=$conf->don->dir_output.'/'.$original_file;
2675
+		$original_file = $conf->don->dir_output.'/'.$original_file;
2676 2676
 	}
2677 2677
 
2678 2678
 	// Wrapping pour les dons
2679 2679
 	else if ($modulepart == 'dolresource' && !empty($conf->resource->dir_output))
2680 2680
 	{
2681
-		if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i',$original_file))
2681
+		if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i', $original_file))
2682 2682
 		{
2683
-			$accessallowed=1;
2683
+			$accessallowed = 1;
2684 2684
 		}
2685
-		$original_file=$conf->resource->dir_output.'/'.$original_file;
2685
+		$original_file = $conf->resource->dir_output.'/'.$original_file;
2686 2686
 	}
2687 2687
 
2688 2688
 	// Wrapping pour les remises de cheques
2689 2689
 	else if ($modulepart == 'remisecheque' && !empty($conf->banque->dir_output))
2690 2690
 	{
2691
-		if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i',$original_file))
2691
+		if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i', $original_file))
2692 2692
 		{
2693
-			$accessallowed=1;
2693
+			$accessallowed = 1;
2694 2694
 		}
2695 2695
 
2696
-		$original_file=$conf->bank->dir_output.'/checkdeposits/'.$original_file;		// original_file should contains relative path so include the get_exdir result
2696
+		$original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result
2697 2697
 	}
2698 2698
 
2699 2699
 	// Wrapping for bank
@@ -2701,9 +2701,9 @@  discard block
 block discarded – undo
2701 2701
 	{
2702 2702
 		if ($fuser->rights->banque->{$lire})
2703 2703
 		{
2704
-			$accessallowed=1;
2704
+			$accessallowed = 1;
2705 2705
 		}
2706
-		$original_file=$conf->bank->dir_output.'/'.$original_file;
2706
+		$original_file = $conf->bank->dir_output.'/'.$original_file;
2707 2707
 	}
2708 2708
 
2709 2709
 	// Wrapping for export module
@@ -2711,62 +2711,62 @@  discard block
 block discarded – undo
2711 2711
 	{
2712 2712
 		// Aucun test necessaire car on force le rep de download sur
2713 2713
 		// le rep export qui est propre a l'utilisateur
2714
-		$accessallowed=1;
2715
-		$original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
2714
+		$accessallowed = 1;
2715
+		$original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
2716 2716
 	}
2717 2717
 
2718 2718
 	// Wrapping for import module
2719 2719
 	else if ($modulepart == 'import' && !empty($conf->import->dir_temp))
2720 2720
 	{
2721
-		$accessallowed=1;
2722
-		$original_file=$conf->import->dir_temp.'/'.$original_file;
2721
+		$accessallowed = 1;
2722
+		$original_file = $conf->import->dir_temp.'/'.$original_file;
2723 2723
 	}
2724 2724
 
2725 2725
 	// Wrapping pour l'editeur wysiwyg
2726 2726
 	else if ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output))
2727 2727
 	{
2728
-		$accessallowed=1;
2729
-		$original_file=$conf->fckeditor->dir_output.'/'.$original_file;
2728
+		$accessallowed = 1;
2729
+		$original_file = $conf->fckeditor->dir_output.'/'.$original_file;
2730 2730
 	}
2731 2731
 
2732 2732
 	// Wrapping for backups
2733 2733
 	else if ($modulepart == 'systemtools' && !empty($conf->admin->dir_output))
2734 2734
 	{
2735
-		if ($fuser->admin) $accessallowed=1;
2736
-		$original_file=$conf->admin->dir_output.'/'.$original_file;
2735
+		if ($fuser->admin) $accessallowed = 1;
2736
+		$original_file = $conf->admin->dir_output.'/'.$original_file;
2737 2737
 	}
2738 2738
 
2739 2739
 	// Wrapping for upload file test
2740 2740
 	else if ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp))
2741 2741
 	{
2742
-		if ($fuser->admin) $accessallowed=1;
2743
-		$original_file=$conf->admin->dir_temp.'/'.$original_file;
2742
+		if ($fuser->admin) $accessallowed = 1;
2743
+		$original_file = $conf->admin->dir_temp.'/'.$original_file;
2744 2744
 	}
2745 2745
 
2746 2746
 	// Wrapping pour BitTorrent
2747 2747
 	else if ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output))
2748 2748
 	{
2749
-		$accessallowed=1;
2750
-		$dir='files';
2751
-		if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
2752
-		$original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
2749
+		$accessallowed = 1;
2750
+		$dir = 'files';
2751
+		if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir = 'torrents';
2752
+		$original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
2753 2753
 	}
2754 2754
 
2755 2755
 	// Wrapping pour Foundation module
2756 2756
 	else if ($modulepart == 'member' && !empty($conf->adherent->dir_output))
2757 2757
 	{
2758
-		if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i',$original_file))
2758
+		if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i', $original_file))
2759 2759
 		{
2760
-			$accessallowed=1;
2760
+			$accessallowed = 1;
2761 2761
 		}
2762
-		$original_file=$conf->adherent->dir_output.'/'.$original_file;
2762
+		$original_file = $conf->adherent->dir_output.'/'.$original_file;
2763 2763
 	}
2764 2764
 
2765 2765
 	// Wrapping for Scanner
2766 2766
 	else if ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
2767 2767
 	{
2768
-		$accessallowed=1;
2769
-		$original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2768
+		$accessallowed = 1;
2769
+		$original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
2770 2770
 	}
2771 2771
 
2772 2772
 	// GENERIC Wrapping
@@ -2776,89 +2776,89 @@  discard block
 block discarded – undo
2776 2776
 	// If modulepart=module				Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
2777 2777
 	else
2778 2778
 	{
2779
-		if (preg_match('/^specimen/i',$original_file))	$accessallowed=1;    // If link to a file called specimen. Test must be done before changing $original_file int full path.
2780
-		if ($fuser->admin) $accessallowed=1;    // If user is admin
2779
+		if (preg_match('/^specimen/i', $original_file))	$accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
2780
+		if ($fuser->admin) $accessallowed = 1; // If user is admin
2781 2781
 
2782 2782
 		// Define $accessallowed
2783
-		if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
2783
+		if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg))
2784 2784
 		{
2785 2785
 			if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
2786 2786
 			{
2787
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2787
+				dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2788 2788
 				exit;
2789 2789
 			}
2790
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2791
-			$original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
2790
+			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1;
2791
+			$original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
2792 2792
 		}
2793
-		else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
2793
+		else if (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg))
2794 2794
 		{
2795 2795
 			if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
2796 2796
 			{
2797
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2797
+				dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2798 2798
 				exit;
2799 2799
 			}
2800
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2801
-			$original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
2800
+			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1;
2801
+			$original_file = $conf->{$reg[1]}->dir_temp.'/'.$original_file;
2802 2802
 		}
2803
-		else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
2803
+		else if (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg))
2804 2804
 		{
2805 2805
 			if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
2806 2806
 			{
2807
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2807
+				dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2808 2808
 				exit;
2809 2809
 			}
2810
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
2811
-			$original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
2810
+			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1;
2811
+			$original_file = $conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
2812 2812
 		}
2813 2813
 		else if (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg))
2814 2814
 		{
2815 2815
 			if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
2816 2816
 			{
2817
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2817
+				dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2818 2818
 				exit;
2819 2819
 			}
2820 2820
 			if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file))
2821 2821
 			{
2822
-				$accessallowed=1;
2822
+				$accessallowed = 1;
2823 2823
 			}
2824
-			$original_file=$conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2824
+			$original_file = $conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2825 2825
 		}
2826 2826
 		else
2827 2827
 		{
2828 2828
 			if (empty($conf->$modulepart->dir_output))	// modulepart not supported
2829 2829
 			{
2830
-				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2830
+				dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
2831 2831
 				exit;
2832 2832
 			}
2833 2833
 
2834
-			$perm=GETPOST('perm');
2835
-			$subperm=GETPOST('subperm');
2834
+			$perm = GETPOST('perm');
2835
+			$subperm = GETPOST('subperm');
2836 2836
 			if ($perm || $subperm)
2837 2837
 			{
2838
-				if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
2839
-				$original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2838
+				if (($perm && !$subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed = 1;
2839
+				$original_file = $conf->$modulepart->dir_output.'/'.$original_file;
2840 2840
 			}
2841 2841
 			else
2842 2842
 			{
2843
-				if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed=1;
2844
-				$original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2843
+				if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed = 1;
2844
+				$original_file = $conf->$modulepart->dir_output.'/'.$original_file;
2845 2845
 			}
2846 2846
 		}
2847 2847
 
2848 2848
 		// For modules who wants to manage different levels of permissions for documents
2849 2849
 		$subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
2850
-		if (! empty($conf->global->$subPermCategoryConstName))
2850
+		if (!empty($conf->global->$subPermCategoryConstName))
2851 2851
 		{
2852 2852
 			$subPermCategory = $conf->global->$subPermCategoryConstName;
2853
-			if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download})))
2853
+			if (!empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download})))
2854 2854
 			{
2855
-				$accessallowed=1;
2855
+				$accessallowed = 1;
2856 2856
 			}
2857 2857
 		}
2858 2858
 
2859 2859
 		// Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
2860 2860
 		$sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
2861
-		if (! empty($conf->global->$sqlProtectConstName))	// If module want to define its own $sqlprotectagainstexternals
2861
+		if (!empty($conf->global->$sqlProtectConstName))	// If module want to define its own $sqlprotectagainstexternals
2862 2862
 		{
2863 2863
 			// Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2864 2864
 			eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
@@ -2884,8 +2884,8 @@  discard block
 block discarded – undo
2884 2884
  */
2885 2885
 function dol_filecache($directory, $filename, $object)
2886 2886
 {
2887
-	if (! dol_is_dir($directory)) dol_mkdir($directory);
2888
-	$cachefile = $directory . $filename;
2887
+	if (!dol_is_dir($directory)) dol_mkdir($directory);
2888
+	$cachefile = $directory.$filename;
2889 2889
 	file_put_contents($cachefile, serialize($object), LOCK_EX);
2890 2890
 	@chmod($cachefile, 0644);
2891 2891
 }
@@ -2901,8 +2901,8 @@  discard block
 block discarded – undo
2901 2901
 function dol_cache_refresh($directory, $filename, $cachetime)
2902 2902
 {
2903 2903
 	$now = dol_now();
2904
-	$cachefile = $directory . $filename;
2905
-	$refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile);
2904
+	$cachefile = $directory.$filename;
2905
+	$refresh = !file_exists($cachefile) || ($now - $cachetime) > dol_filemtime($cachefile);
2906 2906
 	return $refresh;
2907 2907
 }
2908 2908
 
@@ -2915,7 +2915,7 @@  discard block
 block discarded – undo
2915 2915
  */
2916 2916
 function dol_readcachefile($directory, $filename)
2917 2917
 {
2918
-	$cachefile = $directory . $filename;
2918
+	$cachefile = $directory.$filename;
2919 2919
 	$object = unserialize(file_get_contents($cachefile));
2920 2920
 	return $object;
2921 2921
 }
Please login to merge, or discard this patch.
Braces   +512 added lines, -266 removed lines patch added patch discarded remove patch
@@ -98,16 +98,21 @@  discard block
 block discarded – undo
98 98
 	// $hookmanager->resArray may contain array stacked by other modules
99 99
 	if (empty($reshook))
100 100
 	{
101
-		if (! is_dir($newpath)) return array();
101
+		if (! is_dir($newpath)) {
102
+		    return array();
103
+		}
102 104
 
103 105
 		if ($dir = opendir($newpath))
104 106
 		{
105 107
 			$filedate='';
106 108
 			$filesize='';
107 109
 
108
-			while (false !== ($file = readdir($dir)))        // $file is always a basename (into directory $newpath)
110
+			while (false !== ($file = readdir($dir))) {
111
+			    // $file is always a basename (into directory $newpath)
109 112
 			{
110
-				if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure data is stored in utf8 in memory
113
+				if (! utf8_check($file)) $file=utf8_encode($file);
114
+			}
115
+			// To be sure data is stored in utf8 in memory
111 116
 				$fullpathfile=($newpath?$newpath.'/':'').$file;
112 117
 
113 118
 				$qualified=1;
@@ -117,8 +122,9 @@  discard block
 block discarded – undo
117 122
 				if (is_array($excludefilter))
118 123
 				{
119 124
 					$excludefilterarray=array_merge($excludefilterarray,$excludefilter);
125
+				} else if ($excludefilter) {
126
+				    $excludefilterarray[]=$excludefilter;
120 127
 				}
121
-				else if ($excludefilter) $excludefilterarray[]=$excludefilter;
122 128
 				// Check if file is qualified
123 129
 				foreach($excludefilterarray as $filt)
124 130
 				{
@@ -137,12 +143,18 @@  discard block
 block discarded – undo
137 143
 						// Add entry into file_list array
138 144
 						if (($types=="directories") || ($types=="all"))
139 145
 						{
140
-							if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
141
-							if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
146
+							if ($loaddate || $sortcriteria == 'date') {
147
+							    $filedate=dol_filemtime($path."/".$file);
148
+							}
149
+							if ($loadsize || $sortcriteria == 'size') {
150
+							    $filesize=dol_filesize($path."/".$file);
151
+							}
142 152
 
143
-							if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into all $path, only into $file part
153
+							if (! $filter || preg_match('/'.$filter.'/i',$file)) {
154
+							    // We do not search key $filter into all $path, only into $file part
144 155
 							{
145 156
 								preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
157
+							}
146 158
 								$level1name=(isset($reg[1])?$reg[1]:'');
147 159
 								$file_list[] = array(
148 160
 										"name" => $file,
@@ -166,16 +178,21 @@  discard block
 block discarded – undo
166 178
 								$file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename!=''?$relativename.'/':'').$file, $donotfollowsymlinks));
167 179
 							}
168 180
 						}
169
-					}
170
-					else if (! $isdir && (($types == "files") || ($types == "all")))
181
+					} else if (! $isdir && (($types == "files") || ($types == "all")))
171 182
 					{
172 183
 						// Add file into file_list array
173
-						if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
174
-						if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
184
+						if ($loaddate || $sortcriteria == 'date') {
185
+						    $filedate=dol_filemtime($path."/".$file);
186
+						}
187
+						if ($loadsize || $sortcriteria == 'size') {
188
+						    $filesize=dol_filesize($path."/".$file);
189
+						}
175 190
 
176
-						if (! $filter || preg_match('/'.$filter.'/i',$file))	// We do not search key $filter into $path, only into $file
191
+						if (! $filter || preg_match('/'.$filter.'/i',$file)) {
192
+						    // We do not search key $filter into $path, only into $file
177 193
 						{
178 194
 							preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
195
+						}
179 196
 							$level1name=(isset($reg[1])?$reg[1]:'');
180 197
 							$file_list[] = array(
181 198
 									"name" => $file,
@@ -202,12 +219,16 @@  discard block
 block discarded – undo
202 219
 					$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
203 220
 				}
204 221
 				// Sort the data
205
-				if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
222
+				if ($sortorder) {
223
+				    array_multisort($myarray, $sortorder, $file_list);
224
+				}
206 225
 			}
207 226
 		}
208 227
 	}
209 228
 
210
-	if (is_object($hookmanager) && is_array($hookmanager->resArray)) $file_list = array_merge($file_list, $hookmanager->resArray);
229
+	if (is_object($hookmanager) && is_array($hookmanager->resArray)) {
230
+	    $file_list = array_merge($file_list, $hookmanager->resArray);
231
+	}
211 232
 
212 233
 	return $file_list;
213 234
 }
@@ -232,7 +253,9 @@  discard block
 block discarded – undo
232 253
 
233 254
 	$sql =" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,";
234 255
 	$sql.=" acl, position, share";
235
-	if ($mode) $sql.=", description";
256
+	if ($mode) {
257
+	    $sql.=", description";
258
+	}
236 259
 	$sql.=" FROM ".MAIN_DB_PREFIX."ecm_files";
237 260
 	$sql.=" WHERE filepath = '".$db->escape($path)."'";
238 261
 	$sql.=" AND entity = ".$conf->entity;
@@ -280,12 +303,13 @@  discard block
 block discarded – undo
280 303
 				$myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
281 304
 			}
282 305
 			// Sort the data
283
-			if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
306
+			if ($sortorder) {
307
+			    array_multisort($myarray, $sortorder, $file_list);
308
+			}
284 309
 		}
285 310
 
286 311
 		return $file_list;
287
-	}
288
-	else
312
+	} else
289 313
 	{
290 314
 		dol_print_error($db);
291 315
 		return array();
@@ -313,8 +337,11 @@  discard block
 block discarded – undo
313 337
 		global $object;
314 338
 		if (! empty($object->id))
315 339
 		{
316
-			if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
317
-			else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
340
+			if (! empty($conf->product->enabled)) {
341
+			    $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
342
+			} else {
343
+			    $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos";
344
+			}
318 345
 
319 346
 			$relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dirold);
320 347
 			$relativedirold = preg_replace('/^[\\/]/','',$relativedirold);
@@ -347,16 +374,21 @@  discard block
 block discarded – undo
347 374
 			}
348 375
 		}
349 376
 
350
-		if (! $found)    // This happen in transition toward version 6, or if files were added manually into os dir.
377
+		if (! $found) {
378
+		    // This happen in transition toward version 6, or if files were added manually into os dir.
351 379
 		{
352
-			$filearray[$key]['position']='999999';     // File not indexed are at end. So if we add a file, it will not replace an existing position
380
+			$filearray[$key]['position']='999999';
381
+		}
382
+		// File not indexed are at end. So if we add a file, it will not replace an existing position
353 383
 			$filearray[$key]['cover']=0;
354 384
 			$filearray[$key]['acl']='';
355 385
 
356 386
 			$rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filearray[$key]['fullname']);
357
-			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
387
+			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) {
388
+			    // If not a tmp file
358 389
 			{
359 390
 				dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it");
391
+			}
360 392
 				include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
361 393
 				$ecmfile=new EcmFiles($db);
362 394
 
@@ -377,13 +409,11 @@  discard block
 block discarded – undo
377 409
 				if ($result < 0)
378 410
 				{
379 411
 					setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
380
-				}
381
-				else
412
+				} else
382 413
 				{
383 414
 					$filearray[$key]['rowid']=$result;
384 415
 				}
385
-			}
386
-			else
416
+			} else
387 417
 			{
388 418
 				$filearray[$key]['rowid']=0;     // Should not happened
389 419
 			}
@@ -408,22 +438,27 @@  discard block
 block discarded – undo
408 438
 
409 439
 	$sortorder=strtoupper($sortorder);
410 440
 
411
-	if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
412
-	else { $retup=1; $retdown=-1; }
441
+	if ($sortorder == 'ASC') { $retup=-1; $retdown=1; } else { $retup=1; $retdown=-1; }
413 442
 
414 443
 	if ($sortfield == 'name')
415 444
 	{
416
-		if ($a->name == $b->name) return 0;
445
+		if ($a->name == $b->name) {
446
+		    return 0;
447
+		}
417 448
 		return ($a->name < $b->name) ? $retup : $retdown;
418 449
 	}
419 450
 	if ($sortfield == 'date')
420 451
 	{
421
-		if ($a->date == $b->date) return 0;
452
+		if ($a->date == $b->date) {
453
+		    return 0;
454
+		}
422 455
 		return ($a->date < $b->date) ? $retup : $retdown;
423 456
 	}
424 457
 	if ($sortfield == 'size')
425 458
 	{
426
-		if ($a->size == $b->size) return 0;
459
+		if ($a->size == $b->size) {
460
+		    return 0;
461
+		}
427 462
 		return ($a->size < $b->size) ? $retup : $retdown;
428 463
 	}
429 464
 }
@@ -438,9 +473,12 @@  discard block
 block discarded – undo
438 473
 function dol_is_dir($folder)
439 474
 {
440 475
 	$newfolder=dol_osencode($folder);
441
-	if (is_dir($newfolder)) return true;
442
-	else return false;
443
-}
476
+	if (is_dir($newfolder)) {
477
+	    return true;
478
+	} else {
479
+	    return false;
480
+	}
481
+	}
444 482
 
445 483
 /**
446 484
  * Return if path is a file
@@ -477,7 +515,9 @@  discard block
 block discarded – undo
477 515
 	$tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
478 516
 	foreach($tmpprot as $prot)
479 517
 	{
480
-		if (preg_match('/^'.$prot.':/i',$url)) return true;
518
+		if (preg_match('/^'.$prot.':/i',$url)) {
519
+		    return true;
520
+		}
481 521
 	}
482 522
 	return false;
483 523
 }
@@ -499,15 +539,21 @@  discard block
 block discarded – undo
499 539
 		{
500 540
 			$name_array[] = $name;
501 541
 		}
502
-		foreach($name_array as $temp) $folder_content .= $temp;
542
+		foreach($name_array as $temp) {
543
+		    $folder_content .= $temp;
544
+		}
503 545
 
504 546
 		closedir($handle);
505 547
 
506
-		if ($folder_content == "...") return true;
507
-		else return false;
548
+		if ($folder_content == "...") {
549
+		    return true;
550
+		} else {
551
+		    return false;
552
+		}
553
+	} else {
554
+		return true;
508 555
 	}
509
-	else
510
-	return true; // Dir does not exists
556
+	// Dir does not exists
511 557
 }
512 558
 
513 559
 /**
@@ -530,11 +576,12 @@  discard block
 block discarded – undo
530 576
 		{
531 577
 			$line=fgets($fp);
532 578
 			// We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
533
-			if (! $line === false) $nb++;
579
+			if (! $line === false) {
580
+			    $nb++;
581
+			}
534 582
 		}
535 583
 		fclose($fp);
536
-	}
537
-	else
584
+	} else
538 585
 	{
539 586
 		$nb=-1;
540 587
 	}
@@ -584,11 +631,17 @@  discard block
 block discarded – undo
584 631
 
585 632
 	dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase);
586 633
 
587
-	if (empty($srcfile)) return -1;
588
-	if (empty($destfile)) $destfile=$srcfile;
634
+	if (empty($srcfile)) {
635
+	    return -1;
636
+	}
637
+	if (empty($destfile)) {
638
+	    $destfile=$srcfile;
639
+	}
589 640
 
590 641
 	$destexists=dol_is_file($destfile);
591
-	if (($destfile != $srcfile) && $destexists) return 0;
642
+	if (($destfile != $srcfile) && $destexists) {
643
+	    return 0;
644
+	}
592 645
 
593 646
 	$tmpdestfile=$destfile.'.tmp';
594 647
 
@@ -625,10 +678,14 @@  discard block
 block discarded – undo
625 678
 		dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING);
626 679
 		return -3;
627 680
 	}
628
-	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
629
-	if (empty($newmask))	// This should no happen
681
+	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) {
682
+	    $newmask=$conf->global->MAIN_UMASK;
683
+	}
684
+	if (empty($newmask)) {
685
+	    // This should no happen
630 686
 	{
631 687
 		dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING);
688
+	}
632 689
 		$newmask='0664';
633 690
 	}
634 691
 
@@ -669,10 +726,14 @@  discard block
 block discarded – undo
669 726
 
670 727
 	dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
671 728
 
672
-	if (empty($srcfile) || empty($destfile)) return -1;
729
+	if (empty($srcfile) || empty($destfile)) {
730
+	    return -1;
731
+	}
673 732
 
674 733
 	$destexists=dol_is_file($destfile);
675
-	if (! $overwriteifexists && $destexists) return 0;
734
+	if (! $overwriteifexists && $destexists) {
735
+	    return 0;
736
+	}
676 737
 
677 738
 	$newpathofsrcfile=dol_osencode($srcfile);
678 739
 	$newpathofdestfile=dol_osencode($destfile);
@@ -696,10 +757,14 @@  discard block
 block discarded – undo
696 757
 		dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
697 758
 		return -3;
698 759
 	}
699
-	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
700
-	if (empty($newmask))	// This should no happen
760
+	if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) {
761
+	    $newmask=$conf->global->MAIN_UMASK;
762
+	}
763
+	if (empty($newmask)) {
764
+	    // This should no happen
701 765
 	{
702 766
 		dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
767
+	}
703 768
 		$newmask='0664';
704 769
 	}
705 770
 
@@ -727,7 +792,9 @@  discard block
 block discarded – undo
727 792
 
728 793
 	dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
729 794
 
730
-	if (empty($srcfile) || empty($destfile)) return -1;
795
+	if (empty($srcfile) || empty($destfile)) {
796
+	    return -1;
797
+	}
731 798
 
732 799
 	$destexists=dol_is_dir($destfile);
733 800
 	//if (! $overwriteifexists && $destexists) return 0;	// The overwriteifexists is for files only, so propagated to dol_copy only.
@@ -737,7 +804,9 @@  discard block
 block discarded – undo
737 804
 		// We must set mask just before creating dir, becaause it can be set differently by dol_copy
738 805
 		umask(0);
739 806
 		$dirmaskdec=octdec($newmask);
740
-		if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
807
+		if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) {
808
+		    $dirmaskdec=octdec($conf->global->MAIN_UMASK);
809
+		}
741 810
 		$dirmaskdec |= octdec('0200');  // Set w bit required to be able to create content for recursive subdirs files
742 811
 		dol_mkdir($destfile, '', decoct($dirmaskdec));
743 812
 	}
@@ -757,8 +826,7 @@  discard block
 block discarded – undo
757 826
 				{
758 827
 					//var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists");
759 828
 					$tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement);
760
-				}
761
-				else
829
+				} else
762 830
 				{
763 831
 					$newfile = $file;
764 832
 					// Replace destination filename with a new one
@@ -775,17 +843,17 @@  discard block
 block discarded – undo
775 843
 				if ($result > 0 && $tmpresult >= 0)
776 844
 				{
777 845
 					// Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass
778
-				}
779
-				else
846
+				} else
780 847
 				{
781 848
 					$result=$tmpresult;
782 849
 				}
783
-				if ($result < 0) break;
850
+				if ($result < 0) {
851
+				    break;
852
+				}
784 853
 			}
785 854
 		}
786 855
 		closedir($dir_handle);
787
-	}
788
-	else
856
+	} else
789 857
 	{
790 858
 		// Source directory does not exists
791 859
 		$result = -2;
@@ -852,8 +920,9 @@  discard block
 block discarded – undo
852 920
 				// We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
853 921
 				dol_delete_file($destfile);
854 922
 				$result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
923
+			} else {
924
+			    dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
855 925
 			}
856
-			else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
857 926
 		}
858 927
 
859 928
 		// Move ok
@@ -862,9 +931,11 @@  discard block
 block discarded – undo
862 931
 			// Rename entry into ecm database
863 932
 			$rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $srcfile);
864 933
 			$rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $destfile);
865
-			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter))     // If not a tmp file
934
+			if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) {
935
+			    // If not a tmp file
866 936
 			{
867 937
 				$rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
938
+			}
868 939
 				$rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
869 940
 				//var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);
870 941
 
@@ -873,16 +944,20 @@  discard block
 block discarded – undo
873 944
 
874 945
 				$ecmfiletarget=new EcmFiles($db);
875 946
 				$resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
876
-				if ($resultecmtarget > 0)   // An entry for target name already exists for target, we delete it, a new one will be created.
947
+				if ($resultecmtarget > 0) {
948
+				    // An entry for target name already exists for target, we delete it, a new one will be created.
877 949
 				{
878 950
 					$ecmfiletarget->delete($user);
879 951
 				}
952
+				}
880 953
 
881 954
 				$ecmfile=new EcmFiles($db);
882 955
 				$resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
883
-				if ($resultecm > 0)   // If an entry was found for src file, we use it to move entry
956
+				if ($resultecm > 0) {
957
+				    // If an entry was found for src file, we use it to move entry
884 958
 				{
885 959
 					$filename = basename($rel_filetorenameafter);
960
+				}
886 961
 					$rel_dir = dirname($rel_filetorenameafter);
887 962
 					$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
888 963
 					$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
@@ -890,10 +965,11 @@  discard block
 block discarded – undo
890 965
 					$ecmfile->filepath = $rel_dir;
891 966
 					$ecmfile->filename = $filename;
892 967
 					$resultecm = $ecmfile->update($user);
893
-				}
894
-				elseif ($resultecm == 0)   // If no entry were found for src files, create/update target file
968
+				} elseif ($resultecm == 0) {
969
+				    // If no entry were found for src files, create/update target file
895 970
 				{
896 971
 					$filename = basename($rel_filetorenameafter);
972
+				}
897 973
 					$rel_dir = dirname($rel_filetorenameafter);
898 974
 					$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
899 975
 					$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
@@ -910,18 +986,22 @@  discard block
 block discarded – undo
910 986
 					{
911 987
 						setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
912 988
 					}
913
-				}
914
-				elseif ($resultecm < 0)
989
+				} elseif ($resultecm < 0)
915 990
 				{
916 991
 					setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
917 992
 				}
918 993
 
919
-				if ($resultecm > 0) $result=true;
920
-				else $result = false;
994
+				if ($resultecm > 0) {
995
+				    $result=true;
996
+				} else {
997
+				    $result = false;
998
+				}
921 999
 			}
922 1000
 		}
923 1001
 
924
-		if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
1002
+		if (empty($newmask)) {
1003
+		    $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
1004
+		}
925 1005
 		$newmaskdec=octdec($newmask);
926 1006
 		// Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
927 1007
 		// to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
@@ -965,9 +1045,11 @@  discard block
 block discarded – undo
965 1045
 		}
966 1046
 		$antivir=new AntiVir($db);
967 1047
 		$result = $antivir->dol_avscan_file($src_file);
968
-		if ($result < 0)	// If virus or error, we stop here
1048
+		if ($result < 0) {
1049
+		    // If virus or error, we stop here
969 1050
 		{
970 1051
 			$reterrors=$antivir->errors;
1052
+		}
971 1053
 			return $reterrors;
972 1054
 		}
973 1055
 	}
@@ -1075,13 +1157,17 @@  discard block
 block discarded – undo
1075 1157
 		}
1076 1158
 	}
1077 1159
 
1078
-	if ($reshook < 0)	// At least one blocking error returned by one hook
1160
+	if ($reshook < 0) {
1161
+	    // At least one blocking error returned by one hook
1079 1162
 	{
1080 1163
 		$errmsg = join(',', $hookmanager->errors);
1081
-		if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks';	// Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1082
-		return $errmsg;
1083 1164
 	}
1084
-	elseif (empty($reshook))
1165
+		if (empty($errmsg)) {
1166
+		    $errmsg = 'ErrorReturnedBySomeHooks';
1167
+		}
1168
+		// Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
1169
+		return $errmsg;
1170
+	} elseif (empty($reshook))
1085 1171
 	{
1086 1172
 		// The file functions must be in OS filesystem encoding.
1087 1173
 		$src_file_osencoded=dol_osencode($src_file);
@@ -1108,11 +1194,12 @@  discard block
 block discarded – undo
1108 1194
 		$return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
1109 1195
 		if ($return)
1110 1196
 		{
1111
-			if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1197
+			if (! empty($conf->global->MAIN_UMASK)) {
1198
+			    @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
1199
+			}
1112 1200
 			dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
1113 1201
 			return 1;	// Success
1114
-		}
1115
-		else
1202
+		} else
1116 1203
 		{
1117 1204
 			dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
1118 1205
 			return -3;	// Unknown error
@@ -1167,12 +1254,13 @@  discard block
 block discarded – undo
1167 1254
 		$reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
1168 1255
 	}
1169 1256
 
1170
-	if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
1257
+	if (empty($nohook) && $reshook != 0) {
1258
+	    // reshook = 0 to do standard actions, 1 = ok, -1 = ko
1171 1259
 	{
1172 1260
 		if ($reshook < 0) return false;
1173
-		return true;
1174 1261
 	}
1175
-	else
1262
+		return true;
1263
+	} else
1176 1264
 	{
1177 1265
 		$error=0;
1178 1266
 
@@ -1188,21 +1276,28 @@  discard block
 block discarded – undo
1188 1276
 			{
1189 1277
 				foreach ($listofdir as $filename)
1190 1278
 				{
1191
-					if ($nophperrors) $ok=@unlink($filename);
1192
-					else $ok=unlink($filename);
1279
+					if ($nophperrors) {
1280
+					    $ok=@unlink($filename);
1281
+					} else {
1282
+					    $ok=unlink($filename);
1283
+					}
1193 1284
 					if ($ok)
1194 1285
 					{
1195 1286
 						dol_syslog("Removed file ".$filename, LOG_DEBUG);
1196 1287
 
1197 1288
 						// Delete entry into ecm database
1198 1289
 						$rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filename);
1199
-						if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete))     // If not a tmp file
1290
+						if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) {
1291
+						    // If not a tmp file
1200 1292
 						{
1201 1293
 							$rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
1294
+						}
1202 1295
 
1203
-							if (is_object($db) && $indexdatabase)		// $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1296
+							if (is_object($db) && $indexdatabase) {
1297
+							    // $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
1204 1298
 							{
1205 1299
 								dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
1300
+							}
1206 1301
 								include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1207 1302
 								$ecmfile=new EcmFiles($db);
1208 1303
 								$result = $ecmfile->fetch(0, '', $rel_filetodelete);
@@ -1216,21 +1311,28 @@  discard block
 block discarded – undo
1216 1311
 								}
1217 1312
 							}
1218 1313
 						}
1314
+					} else {
1315
+					    dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1219 1316
 					}
1220
-					else dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
1221 1317
 					// TODO Failure to remove can be because file was already removed or because of permission
1222 1318
 					// If error because it does not exists, we should return true, and we should return false if this is a permission problem
1223 1319
 				}
1320
+			} else {
1321
+			    dol_syslog("No files to delete found", LOG_DEBUG);
1224 1322
 			}
1225
-			else dol_syslog("No files to delete found", LOG_DEBUG);
1226
-		}
1227
-		else
1323
+		} else
1228 1324
 		{
1229 1325
 			$ok=false;
1230
-			if ($nophperrors) $ok=@unlink($file_osencoded);
1231
-			else $ok=unlink($file_osencoded);
1232
-			if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
1233
-			else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
1326
+			if ($nophperrors) {
1327
+			    $ok=@unlink($file_osencoded);
1328
+			} else {
1329
+			    $ok=unlink($file_osencoded);
1330
+			}
1331
+			if ($ok) {
1332
+			    dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
1333
+			} else {
1334
+			    dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
1335
+			}
1234 1336
 		}
1235 1337
 
1236 1338
 		return $ok;
@@ -1280,19 +1382,23 @@  discard block
 block discarded – undo
1280 1382
 		{
1281 1383
 			while (false !== ($item = readdir($handle)))
1282 1384
 			{
1283
-				if (! utf8_check($item)) $item=utf8_encode($item);  // should be useless
1385
+				if (! utf8_check($item)) {
1386
+				    $item=utf8_encode($item);
1387
+				}
1388
+				// should be useless
1284 1389
 
1285 1390
 				if ($item != "." && $item != "..")
1286 1391
 				{
1287 1392
 					if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item")))
1288 1393
 					{
1289 1394
 						$count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted);
1290
-					}
1291
-					else
1395
+					} else
1292 1396
 					{
1293 1397
 						$result=dol_delete_file("$dir/$item", 1, $nophperrors);
1294 1398
 						$count++;
1295
-						if ($result) $countdeleted++;
1399
+						if ($result) {
1400
+						    $countdeleted++;
1401
+						}
1296 1402
 						//else print 'Error on '.$item."\n";
1297 1403
 					}
1298 1404
 				}
@@ -1303,7 +1409,9 @@  discard block
 block discarded – undo
1303 1409
 			{
1304 1410
 				$result=dol_delete_dir($dir, $nophperrors);
1305 1411
 				$count++;
1306
-				if ($result) $countdeleted++;
1412
+				if ($result) {
1413
+				    $countdeleted++;
1414
+				}
1307 1415
 				//else print 'Error on '.$dir."\n";
1308 1416
 			}
1309 1417
 		}
@@ -1328,15 +1436,25 @@  discard block
 block discarded – undo
1328 1436
 	// Define parent dir of elements
1329 1437
 	$element = $object->element;
1330 1438
 
1331
-	if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->commande->dir_output;
1332
-	elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->facture->dir_output;
1333
-	elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
1334
-	elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1335
-	elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1336
-	elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1337
-	else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1439
+	if ($object->element == 'order_supplier') {
1440
+	    $dir = $conf->fournisseur->commande->dir_output;
1441
+	} elseif ($object->element == 'invoice_supplier') {
1442
+	    $dir = $conf->fournisseur->facture->dir_output;
1443
+	} elseif ($object->element == 'project') {
1444
+	    $dir = $conf->projet->dir_output;
1445
+	} elseif ($object->element == 'shipping') {
1446
+	    $dir = $conf->expedition->dir_output.'/sending';
1447
+	} elseif ($object->element == 'delivery') {
1448
+	    $dir = $conf->expedition->dir_output.'/receipt';
1449
+	} elseif ($object->element == 'fichinter') {
1450
+	    $dir = $conf->ficheinter->dir_output;
1451
+	} else {
1452
+	    $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1453
+	}
1338 1454
 
1339
-	if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
1455
+	if (empty($dir)) {
1456
+	    return 'ErrorObjectNoSupportedByFunction';
1457
+	}
1340 1458
 
1341 1459
 	$refsan = dol_sanitizeFileName($object->ref);
1342 1460
 	$dir = $dir . "/" . $refsan ;
@@ -1369,8 +1487,7 @@  discard block
 block discarded – undo
1369 1487
 			$object->error=$langs->trans("ErrorFailedToDeleteFile",$filepreviewold);
1370 1488
 			return 0;
1371 1489
 		}
1372
-	}
1373
-	else
1490
+	} else
1374 1491
 	{
1375 1492
 		$multiple = $filepreviewold . ".";
1376 1493
 		for ($i = 0; $i < 20; $i++)
@@ -1404,18 +1521,29 @@  discard block
 block discarded – undo
1404 1521
 	global $conf;
1405 1522
 
1406 1523
 	// Create meta file
1407
-	if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0;	// By default, no metafile.
1524
+	if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) {
1525
+	    return 0;
1526
+	}
1527
+	// By default, no metafile.
1408 1528
 
1409 1529
 	// Define parent dir of elements
1410 1530
 	$element=$object->element;
1411 1531
 
1412
-	if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->dir_output.'/commande';
1413
-	elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->dir_output.'/facture';
1414
-	elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
1415
-	elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
1416
-	elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
1417
-	elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
1418
-	else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1532
+	if ($object->element == 'order_supplier') {
1533
+	    $dir = $conf->fournisseur->dir_output.'/commande';
1534
+	} elseif ($object->element == 'invoice_supplier') {
1535
+	    $dir = $conf->fournisseur->dir_output.'/facture';
1536
+	} elseif ($object->element == 'project') {
1537
+	    $dir = $conf->projet->dir_output;
1538
+	} elseif ($object->element == 'shipping') {
1539
+	    $dir = $conf->expedition->dir_output.'/sending';
1540
+	} elseif ($object->element == 'delivery') {
1541
+	    $dir = $conf->expedition->dir_output.'/receipt';
1542
+	} elseif ($object->element == 'fichinter') {
1543
+	    $dir = $conf->ficheinter->dir_output;
1544
+	} else {
1545
+	    $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
1546
+	}
1419 1547
 
1420 1548
 	if ($dir)
1421 1549
 	{
@@ -1455,12 +1583,12 @@  discard block
 block discarded – undo
1455 1583
 		$fp = fopen($file,"w");
1456 1584
 		fputs($fp,$meta);
1457 1585
 		fclose($fp);
1458
-		if (! empty($conf->global->MAIN_UMASK))
1459
-		@chmod($file, octdec($conf->global->MAIN_UMASK));
1586
+		if (! empty($conf->global->MAIN_UMASK)) {
1587
+				@chmod($file, octdec($conf->global->MAIN_UMASK));
1588
+		}
1460 1589
 
1461 1590
 		return 1;
1462
-	}
1463
-	else
1591
+	} else
1464 1592
 	{
1465 1593
 		dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
1466 1594
 	}
@@ -1522,9 +1650,11 @@  discard block
 block discarded – undo
1522 1650
 
1523 1651
 	$res = 0;
1524 1652
 
1525
-	if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
1653
+	if (! empty($_FILES[$varfiles])) {
1654
+	    // For view $_FILES[$varfiles]['error']
1526 1655
 	{
1527 1656
 		dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
1657
+	}
1528 1658
 		if (dol_mkdir($upload_dir) >= 0)
1529 1659
 		{
1530 1660
 			$TFile = $_FILES[$varfiles];
@@ -1558,9 +1688,11 @@  discard block
 block discarded – undo
1558 1688
 
1559 1689
 				$resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles);
1560 1690
 
1561
-				if (is_numeric($resupload) && $resupload > 0)   // $resupload can be 'ErrorFileAlreadyExists'
1691
+				if (is_numeric($resupload) && $resupload > 0) {
1692
+				    // $resupload can be 'ErrorFileAlreadyExists'
1562 1693
 				{
1563 1694
 					global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
1695
+				}
1564 1696
 
1565 1697
 					include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1566 1698
 
@@ -1600,19 +1732,20 @@  discard block
 block discarded – undo
1600 1732
 					}
1601 1733
 
1602 1734
 					$nbok++;
1603
-				}
1604
-				else
1735
+				} else
1605 1736
 				{
1606 1737
 					$langs->load("errors");
1607
-					if ($resupload < 0)	// Unknown error
1738
+					if ($resupload < 0) {
1739
+					    // Unknown error
1608 1740
 					{
1609 1741
 						setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
1610 1742
 					}
1611
-					else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
1743
+					} else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload)) {
1744
+					    // Files infected by a virus
1612 1745
 					{
1613 1746
 						setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
1614 1747
 					}
1615
-					else	// Known error
1748
+					} else	// Known error
1616 1749
 					{
1617 1750
 						setEventMessages($langs->trans($resupload), null, 'errors');
1618 1751
 					}
@@ -1639,8 +1772,7 @@  discard block
 block discarded – undo
1639 1772
 		} else {
1640 1773
 			setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
1641 1774
 		}
1642
-	}
1643
-	else
1775
+	} else
1644 1776
 	{
1645 1777
 		$langs->load("errors");
1646 1778
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
@@ -1671,16 +1803,27 @@  discard block
 block discarded – undo
1671 1803
 	$listofnames=array();
1672 1804
 	$listofmimes=array();
1673 1805
 	$keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
1674
-	if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
1675
-	if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
1676
-	if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
1806
+	if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) {
1807
+	    $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
1808
+	}
1809
+	if (! empty($_SESSION["listofnames".$keytoavoidconflict])) {
1810
+	    $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
1811
+	}
1812
+	if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) {
1813
+	    $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
1814
+	}
1677 1815
 
1678 1816
 	if ($keytodelete >= 0)
1679 1817
 	{
1680 1818
 		$pathtodelete=$listofpaths[$keytodelete];
1681 1819
 		$filetodelete=$listofnames[$keytodelete];
1682
-		if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);  // The delete of ecm database is inside the function dol_delete_file
1683
-		else $result=0;
1820
+		if (empty($donotdeletefile)) {
1821
+		    $result = dol_delete_file($pathtodelete,1);
1822
+		}
1823
+		// The delete of ecm database is inside the function dol_delete_file
1824
+		else {
1825
+		    $result=0;
1826
+		}
1684 1827
 		if ($result >= 0)
1685 1828
 		{
1686 1829
 			if (empty($donotdeletefile))
@@ -1720,9 +1863,11 @@  discard block
 block discarded – undo
1720 1863
 
1721 1864
 	$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
1722 1865
 
1723
-	if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
1866
+	if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
1867
+	    // If not a tmp dir
1724 1868
 	{
1725 1869
 		$filename = basename($file);
1870
+	}
1726 1871
 		$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
1727 1872
 		$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
1728 1873
 
@@ -1785,8 +1930,12 @@  discard block
 block discarded – undo
1785 1930
 		$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'ecm_files';
1786 1931
 		$sql.= ' WHERE entity = '.$conf->entity;
1787 1932
 		$sql.= " AND filepath = '" . $db->escape($rel_dir) . "'";
1788
-		if ($file) $sql.= " AND filename = '" . $db->escape($file) . "'";
1789
-		if ($mode) $sql.= " AND gen_or_uploaded = '" . $db->escape($mode) . "'";
1933
+		if ($file) {
1934
+		    $sql.= " AND filename = '" . $db->escape($file) . "'";
1935
+		}
1936
+		if ($mode) {
1937
+		    $sql.= " AND gen_or_uploaded = '" . $db->escape($mode) . "'";
1938
+		}
1790 1939
 
1791 1940
 		$resql = $db->query($sql);
1792 1941
 		if (!$resql)
@@ -1834,32 +1983,33 @@  discard block
 block discarded – undo
1834 1983
 			$ret = $image->setImageFormat($ext);
1835 1984
 			if ($ret)
1836 1985
 			{
1837
-				if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
1986
+				if (empty($fileoutput)) {
1987
+				    $fileoutput=$fileinput.".".$ext;
1988
+				}
1838 1989
 
1839 1990
 				$count = $image->getNumberImages();
1840 1991
 
1841 1992
 				if (! dol_is_file($fileoutput) || is_writeable($fileoutput))
1842 1993
 				{
1843 1994
 					$ret = $image->writeImages($fileoutput, true);
1844
-				}
1845
-				else
1995
+				} else
1846 1996
 				{
1847 1997
 					dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
1848 1998
 				}
1849
-				if ($ret) return $count;
1850
-				else return -3;
1851
-			}
1852
-			else
1999
+				if ($ret) {
2000
+				    return $count;
2001
+				} else {
2002
+				    return -3;
2003
+				}
2004
+			} else
1853 2005
 			{
1854 2006
 				return -2;
1855 2007
 			}
1856
-		}
1857
-		else
2008
+		} else
1858 2009
 		{
1859 2010
 			return -1;
1860 2011
 		}
1861
-	}
1862
-	else
2012
+	} else
1863 2013
 	{
1864 2014
 		return 0;
1865 2015
 	}
@@ -1881,9 +2031,7 @@  discard block
 block discarded – undo
1881 2031
 	try
1882 2032
 	{
1883 2033
 		$data = implode("", file(dol_osencode($inputfile)));
1884
-		if ($mode == 'gz')     { $foundhandler=1; $compressdata = gzencode($data, 9); }
1885
-		elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
1886
-		elseif ($mode == 'zip')
2034
+		if ($mode == 'gz')     { $foundhandler=1; $compressdata = gzencode($data, 9); } elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); } elseif ($mode == 'zip')
1887 2035
 		{
1888 2036
 			if (defined('ODTPHP_PATHTOPCLZIP'))
1889 2037
 			{
@@ -1903,14 +2051,12 @@  discard block
 block discarded – undo
1903 2051
 			fwrite($fp, $compressdata);
1904 2052
 			fclose($fp);
1905 2053
 			return 1;
1906
-		}
1907
-		else
2054
+		} else
1908 2055
 		{
1909 2056
 			dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
1910 2057
 			return -2;
1911 2058
 		}
1912
-	}
1913
-	catch (Exception $e)
2059
+	} catch (Exception $e)
1914 2060
 	{
1915 2061
 		global $langs, $errormsg;
1916 2062
 		$langs->load("errors");
@@ -1938,8 +2084,9 @@  discard block
 block discarded – undo
1938 2084
 		$archive = new PclZip($inputfile);
1939 2085
 		$result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
1940 2086
 		//var_dump($result);
1941
-		if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
1942
-		else
2087
+		if (! is_array($result) && $result <= 0) {
2088
+		    return array('error'=>$archive->errorInfo(true));
2089
+		} else
1943 2090
 		{
1944 2091
 			$ok=1; $errmsg='';
1945 2092
 			// Loop on each file to check result for unzipping file
@@ -1954,8 +2101,11 @@  discard block
 block discarded – undo
1954 2101
 				}
1955 2102
 			}
1956 2103
 
1957
-			if ($ok) return array();
1958
-			else return array('error'=>$errmsg);
2104
+			if ($ok) {
2105
+			    return array();
2106
+			} else {
2107
+			    return array('error'=>$errmsg);
2108
+			}
1959 2109
 		}
1960 2110
 	}
1961 2111
 
@@ -1969,8 +2119,7 @@  discard block
 block discarded – undo
1969 2119
 			$zip->extractTo($outputdir.'/');
1970 2120
 			$zip->close();
1971 2121
 			return array();
1972
-		}
1973
-		else
2122
+		} else
1974 2123
 		{
1975 2124
 			return array('error'=>'ErrUnzipFails');
1976 2125
 		}
@@ -2004,9 +2153,7 @@  discard block
 block discarded – undo
2004 2153
 
2005 2154
 	try
2006 2155
 	{
2007
-		if ($mode == 'gz')     { $foundhandler=0; }
2008
-		elseif ($mode == 'bz') { $foundhandler=0; }
2009
-		elseif ($mode == 'zip')
2156
+		if ($mode == 'gz')     { $foundhandler=0; } elseif ($mode == 'bz') { $foundhandler=0; } elseif ($mode == 'zip')
2010 2157
 		{
2011 2158
 			/*if (defined('ODTPHP_PATHTOPCLZIP'))
2012 2159
             {
@@ -2059,13 +2206,11 @@  discard block
 block discarded – undo
2059 2206
 		{
2060 2207
 			dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
2061 2208
 			return -2;
2062
-		}
2063
-		else
2209
+		} else
2064 2210
 		{
2065 2211
 			return 0;
2066 2212
 		}
2067
-	}
2068
-	catch (Exception $e)
2213
+	} catch (Exception $e)
2069 2214
 	{
2070 2215
 		global $langs, $errormsg;
2071 2216
 		$langs->load("errors");
@@ -2111,16 +2256,25 @@  discard block
 block discarded – undo
2111 2256
 	global $conf, $db, $user;
2112 2257
 	global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
2113 2258
 
2114
-	if (! is_object($fuser)) $fuser=$user;
2259
+	if (! is_object($fuser)) {
2260
+	    $fuser=$user;
2261
+	}
2115 2262
 
2116
-	if (empty($modulepart)) return 'ErrorBadParameter';
2263
+	if (empty($modulepart)) {
2264
+	    return 'ErrorBadParameter';
2265
+	}
2117 2266
 	if (empty($entity))
2118 2267
 	{
2119
-		if (empty($conf->multicompany->enabled)) $entity=1;
2120
-		else $entity=0;
2268
+		if (empty($conf->multicompany->enabled)) {
2269
+		    $entity=1;
2270
+		} else {
2271
+		    $entity=0;
2272
+		}
2121 2273
 	}
2122 2274
 	// Fix modulepart
2123
-	if ($modulepart == 'users') $modulepart='user';
2275
+	if ($modulepart == 'users') {
2276
+	    $modulepart='user';
2277
+	}
2124 2278
 
2125 2279
 	dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
2126 2280
 	// We define $accessallowed and $sqlprotectagainstexternals
@@ -2129,7 +2283,9 @@  discard block
 block discarded – undo
2129 2283
 	$ret=array();
2130 2284
 
2131 2285
 	// Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
2132
-	if (empty($refname)) $refname=basename(dirname($original_file)."/");
2286
+	if (empty($refname)) {
2287
+	    $refname=basename(dirname($original_file)."/");
2288
+	}
2133 2289
 
2134 2290
 	$relative_original_file = $original_file;
2135 2291
 
@@ -2143,7 +2299,9 @@  discard block
 block discarded – undo
2143 2299
 	// Wrapping for miscellaneous medias files
2144 2300
 	if ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
2145 2301
 	{
2146
-		if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2302
+		if (empty($entity) || empty($conf->medias->multidir_output[$entity])) {
2303
+		    return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2304
+		}
2147 2305
 		$accessallowed=1;
2148 2306
 		$original_file=$conf->medias->multidir_output[$entity].'/'.$original_file;
2149 2307
 	}
@@ -2184,132 +2342,176 @@  discard block
 block discarded – undo
2184 2342
 	// Wrapping pour les apercu factures
2185 2343
 	elseif ($modulepart == 'apercufacture' && !empty($conf->facture->dir_output))
2186 2344
 	{
2187
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2345
+		if ($fuser->rights->facture->{$lire}) {
2346
+		    $accessallowed=1;
2347
+		}
2188 2348
 		$original_file=$conf->facture->dir_output.'/'.$original_file;
2189 2349
 	}
2190 2350
 	// Wrapping pour les apercu propal
2191 2351
 	elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity]))
2192 2352
 	{
2193
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2353
+		if ($fuser->rights->propale->{$lire}) {
2354
+		    $accessallowed=1;
2355
+		}
2194 2356
 		$original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
2195 2357
 	}
2196 2358
 	// Wrapping pour les apercu commande
2197 2359
 	elseif ($modulepart == 'apercucommande' && !empty($conf->commande->dir_output))
2198 2360
 	{
2199
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2361
+		if ($fuser->rights->commande->{$lire}) {
2362
+		    $accessallowed=1;
2363
+		}
2200 2364
 		$original_file=$conf->commande->dir_output.'/'.$original_file;
2201 2365
 	}
2202 2366
 	// Wrapping pour les apercu intervention
2203 2367
 	elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output))
2204 2368
 	{
2205
-		if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1;
2369
+		if ($fuser->rights->ficheinter->{$lire}) {
2370
+		    $accessallowed=1;
2371
+		}
2206 2372
 		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
2207 2373
 	}
2208 2374
 	// Wrapping pour les apercu conat
2209 2375
 	elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output))
2210 2376
 	{
2211
-		if ($fuser->rights->contrat->{$lire}) $accessallowed=1;
2377
+		if ($fuser->rights->contrat->{$lire}) {
2378
+		    $accessallowed=1;
2379
+		}
2212 2380
 		$original_file=$conf->contrat->dir_output.'/'.$original_file;
2213 2381
 	}
2214 2382
 	// Wrapping pour les apercu supplier proposal
2215 2383
 	elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
2216 2384
 	{
2217
-		if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1;
2385
+		if ($fuser->rights->supplier_proposal->{$lire}) {
2386
+		    $accessallowed=1;
2387
+		}
2218 2388
 		$original_file=$conf->supplier_proposal->dir_output.'/'.$original_file;
2219 2389
 	}
2220 2390
 	// Wrapping pour les apercu supplier order
2221 2391
 	elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
2222 2392
 	{
2223
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2393
+		if ($fuser->rights->fournisseur->commande->{$lire}) {
2394
+		    $accessallowed=1;
2395
+		}
2224 2396
 		$original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
2225 2397
 	}
2226 2398
 	// Wrapping pour les apercu supplier invoice
2227 2399
 	elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
2228 2400
 	{
2229
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2401
+		if ($fuser->rights->fournisseur->facture->{$lire}) {
2402
+		    $accessallowed=1;
2403
+		}
2230 2404
 		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
2231 2405
 	}
2232 2406
 	// Wrapping pour les apercu supplier invoice
2233 2407
 	elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output))
2234 2408
 	{
2235
-		if ($fuser->rights->expensereport->{$lire}) $accessallowed=1;
2409
+		if ($fuser->rights->expensereport->{$lire}) {
2410
+		    $accessallowed=1;
2411
+		}
2236 2412
 		$original_file=$conf->expensereport->dir_output.'/'.$original_file;
2237 2413
 	}
2238 2414
 	// Wrapping pour les images des stats propales
2239 2415
 	elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity]))
2240 2416
 	{
2241
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
2417
+		if ($fuser->rights->propale->{$lire}) {
2418
+		    $accessallowed=1;
2419
+		}
2242 2420
 		$original_file=$conf->propal->multidir_temp[$entity].'/'.$original_file;
2243 2421
 	}
2244 2422
 	// Wrapping pour les images des stats commandes
2245 2423
 	elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
2246 2424
 	{
2247
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
2425
+		if ($fuser->rights->commande->{$lire}) {
2426
+		    $accessallowed=1;
2427
+		}
2248 2428
 		$original_file=$conf->commande->dir_temp.'/'.$original_file;
2249
-	}
2250
-	elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
2429
+	} elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
2251 2430
 	{
2252
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
2431
+		if ($fuser->rights->fournisseur->commande->{$lire}) {
2432
+		    $accessallowed=1;
2433
+		}
2253 2434
 		$original_file=$conf->fournisseur->commande->dir_temp.'/'.$original_file;
2254 2435
 	}
2255 2436
 	// Wrapping pour les images des stats factures
2256 2437
 	elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
2257 2438
 	{
2258
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
2439
+		if ($fuser->rights->facture->{$lire}) {
2440
+		    $accessallowed=1;
2441
+		}
2259 2442
 		$original_file=$conf->facture->dir_temp.'/'.$original_file;
2260
-	}
2261
-	elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
2443
+	} elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
2262 2444
 	{
2263
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
2445
+		if ($fuser->rights->fournisseur->facture->{$lire}) {
2446
+		    $accessallowed=1;
2447
+		}
2264 2448
 		$original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file;
2265 2449
 	}
2266 2450
 	// Wrapping pour les images des stats expeditions
2267 2451
 	elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
2268 2452
 	{
2269
-		if ($fuser->rights->expedition->{$lire}) $accessallowed=1;
2453
+		if ($fuser->rights->expedition->{$lire}) {
2454
+		    $accessallowed=1;
2455
+		}
2270 2456
 		$original_file=$conf->expedition->dir_temp.'/'.$original_file;
2271 2457
 	}
2272 2458
 	// Wrapping pour les images des stats expeditions
2273 2459
 	elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
2274 2460
 	{
2275
-		if ($fuser->rights->deplacement->{$lire}) $accessallowed=1;
2461
+		if ($fuser->rights->deplacement->{$lire}) {
2462
+		    $accessallowed=1;
2463
+		}
2276 2464
 		$original_file=$conf->deplacement->dir_temp.'/'.$original_file;
2277 2465
 	}
2278 2466
 	// Wrapping pour les images des stats expeditions
2279 2467
 	elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
2280 2468
 	{
2281
-		if ($fuser->rights->adherent->{$lire}) $accessallowed=1;
2469
+		if ($fuser->rights->adherent->{$lire}) {
2470
+		    $accessallowed=1;
2471
+		}
2282 2472
 		$original_file=$conf->adherent->dir_temp.'/'.$original_file;
2283 2473
 	}
2284 2474
 	// Wrapping pour les images des stats produits
2285 2475
 	elseif (preg_match('/^productstats_/i',$modulepart) && !empty($conf->product->dir_temp))
2286 2476
 	{
2287
-		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed=1;
2477
+		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) {
2478
+		    $accessallowed=1;
2479
+		}
2288 2480
 		$original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
2289 2481
 	}
2290 2482
 	// Wrapping for taxes
2291 2483
 	elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
2292 2484
 	{
2293
-		if ($fuser->rights->tax->charges->{$lire}) $accessallowed=1;
2485
+		if ($fuser->rights->tax->charges->{$lire}) {
2486
+		    $accessallowed=1;
2487
+		}
2294 2488
 		$original_file=$conf->tax->dir_output.'/'.$original_file;
2295 2489
 	}
2296 2490
 	// Wrapping for events
2297 2491
 	elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
2298 2492
 	{
2299
-		if ($fuser->rights->agenda->myactions->{$read}) $accessallowed=1;
2493
+		if ($fuser->rights->agenda->myactions->{$read}) {
2494
+		    $accessallowed=1;
2495
+		}
2300 2496
 		$original_file=$conf->agenda->dir_output.'/'.$original_file;
2301 2497
 	}
2302 2498
 	// Wrapping for categories
2303 2499
 	elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
2304 2500
 	{
2305
-		if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2306
-		if ($fuser->rights->categorie->{$lire}) $accessallowed=1;
2501
+		if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) {
2502
+		    return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2503
+		}
2504
+		if ($fuser->rights->categorie->{$lire}) {
2505
+		    $accessallowed=1;
2506
+		}
2307 2507
 		$original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
2308 2508
 	}
2309 2509
 	// Wrapping pour les prelevements
2310 2510
 	elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
2311 2511
 	{
2312
-		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i',$original_file)) $accessallowed=1;
2512
+		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i',$original_file)) {
2513
+		    $accessallowed=1;
2514
+		}
2313 2515
 		$original_file=$conf->prelevement->dir_output.'/'.$original_file;
2314 2516
 	}
2315 2517
 	// Wrapping pour les graph energie
@@ -2372,7 +2574,9 @@  discard block
 block discarded – undo
2372 2574
 	// Wrapping for third parties
2373 2575
 	else if (($modulepart == 'company' || $modulepart == 'societe') && !empty($conf->societe->dir_output))
2374 2576
 	{
2375
-		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2577
+		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
2578
+		    return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2579
+		}
2376 2580
 		if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i',$original_file))
2377 2581
 		{
2378 2582
 			$accessallowed=1;
@@ -2384,7 +2588,9 @@  discard block
 block discarded – undo
2384 2588
 	// Wrapping for contact
2385 2589
 	else if ($modulepart == 'contact' && !empty($conf->societe->dir_output))
2386 2590
 	{
2387
-		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2591
+		if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
2592
+		    return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2593
+		}
2388 2594
 		if ($fuser->rights->societe->{$lire})
2389 2595
 		{
2390 2596
 			$accessallowed=1;
@@ -2410,64 +2616,56 @@  discard block
 block discarded – undo
2410 2616
 			$accessallowed=1;
2411 2617
 		}
2412 2618
 		$original_file=$conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
2413
-	}
2414
-	else if ($modulepart == 'massfilesarea_orders')
2619
+	} else if ($modulepart == 'massfilesarea_orders')
2415 2620
 	{
2416 2621
 		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2417 2622
 		{
2418 2623
 			$accessallowed=1;
2419 2624
 		}
2420 2625
 		$original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2421
-	}
2422
-	else if ($modulepart == 'massfilesarea_invoices')
2626
+	} else if ($modulepart == 'massfilesarea_invoices')
2423 2627
 	{
2424 2628
 		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2425 2629
 		{
2426 2630
 			$accessallowed=1;
2427 2631
 		}
2428 2632
 		$original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2429
-	}
2430
-	else if ($modulepart == 'massfilesarea_expensereport')
2633
+	} else if ($modulepart == 'massfilesarea_expensereport')
2431 2634
 	{
2432 2635
 		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2433 2636
 		{
2434 2637
 			$accessallowed=1;
2435 2638
 		}
2436 2639
 		$original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2437
-	}
2438
-	else if ($modulepart == 'massfilesarea_interventions')
2640
+	} else if ($modulepart == 'massfilesarea_interventions')
2439 2641
 	{
2440 2642
 		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file))
2441 2643
 		{
2442 2644
 			$accessallowed=1;
2443 2645
 		}
2444 2646
 		$original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2445
-	}
2446
-	else if ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
2647
+	} else if ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
2447 2648
 	{
2448 2649
 		if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i',$original_file))
2449 2650
 		{
2450 2651
 			$accessallowed=1;
2451 2652
 		}
2452 2653
 		$original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2453
-	}
2454
-	else if ($modulepart == 'massfilesarea_supplier_order')
2654
+	} else if ($modulepart == 'massfilesarea_supplier_order')
2455 2655
 	{
2456 2656
 		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file))
2457 2657
 		{
2458 2658
 			$accessallowed=1;
2459 2659
 		}
2460 2660
 		$original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2461
-	}
2462
-	else if ($modulepart == 'massfilesarea_supplier_invoice')
2661
+	} else if ($modulepart == 'massfilesarea_supplier_invoice')
2463 2662
 	{
2464 2663
 		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file))
2465 2664
 		{
2466 2665
 			$accessallowed=1;
2467 2666
 		}
2468 2667
 		$original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2469
-	}
2470
-	else if ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output))
2668
+	} else if ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output))
2471 2669
 	{
2472 2670
 		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i',$original_file))
2473 2671
 		{
@@ -2528,8 +2726,7 @@  discard block
 block discarded – undo
2528 2726
 		}
2529 2727
 		$original_file=$conf->projet->dir_output.'/'.$original_file;
2530 2728
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
2531
-	}
2532
-	else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
2729
+	} else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
2533 2730
 	{
2534 2731
 		if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i',$original_file))
2535 2732
 		{
@@ -2578,8 +2775,11 @@  discard block
 block discarded – undo
2578 2775
 		{
2579 2776
 			$accessallowed=1;
2580 2777
 		}
2581
-		if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2582
-		else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
2778
+		if ($fuser->societe_id > 0) {
2779
+		    $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
2780
+		} else {
2781
+		    $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
2782
+		}
2583 2783
 	}
2584 2784
 
2585 2785
 	// Wrapping for accounting exports
@@ -2634,24 +2834,33 @@  discard block
 block discarded – undo
2634 2834
 	// Wrapping pour les produits et services
2635 2835
 	else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
2636 2836
 	{
2637
-		if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2837
+		if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) {
2838
+		    return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2839
+		}
2638 2840
 		if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i',$original_file))
2639 2841
 		{
2640 2842
 			$accessallowed=1;
2641 2843
 		}
2642
-		if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
2643
-		elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
2844
+		if (! empty($conf->product->enabled)) {
2845
+		    $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
2846
+		} elseif (! empty($conf->service->enabled)) {
2847
+		    $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
2848
+		}
2644 2849
 	}
2645 2850
 
2646 2851
 	// Wrapping pour les lots produits
2647 2852
 	else if ($modulepart == 'product_batch' || $modulepart == 'produitlot')
2648 2853
 	{
2649
-		if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2854
+		if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) {
2855
+		    return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
2856
+		}
2650 2857
 		if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i',$original_file))
2651 2858
 		{
2652 2859
 			$accessallowed=1;
2653 2860
 		}
2654
-		if (! empty($conf->productbatch->enabled)) $original_file=$conf->productbatch->multidir_output[$entity].'/'.$original_file;
2861
+		if (! empty($conf->productbatch->enabled)) {
2862
+		    $original_file=$conf->productbatch->multidir_output[$entity].'/'.$original_file;
2863
+		}
2655 2864
 	}
2656 2865
 
2657 2866
 	// Wrapping pour les contrats
@@ -2732,14 +2941,18 @@  discard block
 block discarded – undo
2732 2941
 	// Wrapping for backups
2733 2942
 	else if ($modulepart == 'systemtools' && !empty($conf->admin->dir_output))
2734 2943
 	{
2735
-		if ($fuser->admin) $accessallowed=1;
2944
+		if ($fuser->admin) {
2945
+		    $accessallowed=1;
2946
+		}
2736 2947
 		$original_file=$conf->admin->dir_output.'/'.$original_file;
2737 2948
 	}
2738 2949
 
2739 2950
 	// Wrapping for upload file test
2740 2951
 	else if ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp))
2741 2952
 	{
2742
-		if ($fuser->admin) $accessallowed=1;
2953
+		if ($fuser->admin) {
2954
+		    $accessallowed=1;
2955
+		}
2743 2956
 		$original_file=$conf->admin->dir_temp.'/'.$original_file;
2744 2957
 	}
2745 2958
 
@@ -2748,7 +2961,9 @@  discard block
 block discarded – undo
2748 2961
 	{
2749 2962
 		$accessallowed=1;
2750 2963
 		$dir='files';
2751
-		if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
2964
+		if (dol_mimetype($original_file) == 'application/x-bittorrent') {
2965
+		    $dir='torrents';
2966
+		}
2752 2967
 		$original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
2753 2968
 	}
2754 2969
 
@@ -2776,45 +2991,62 @@  discard block
 block discarded – undo
2776 2991
 	// If modulepart=module				Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
2777 2992
 	else
2778 2993
 	{
2779
-		if (preg_match('/^specimen/i',$original_file))	$accessallowed=1;    // If link to a file called specimen. Test must be done before changing $original_file int full path.
2780
-		if ($fuser->admin) $accessallowed=1;    // If user is admin
2994
+		if (preg_match('/^specimen/i',$original_file)) {
2995
+		    $accessallowed=1;
2996
+		}
2997
+		// If link to a file called specimen. Test must be done before changing $original_file int full path.
2998
+		if ($fuser->admin) {
2999
+		    $accessallowed=1;
3000
+		}
3001
+		// If user is admin
2781 3002
 
2782 3003
 		// Define $accessallowed
2783 3004
 		if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
2784 3005
 		{
2785
-			if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
3006
+			if (empty($conf->{$reg[1]}->dir_temp)) {
3007
+			    // modulepart not supported
2786 3008
 			{
2787 3009
 				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3010
+			}
2788 3011
 				exit;
2789 3012
 			}
2790
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
3013
+			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
3014
+			    $accessallowed=1;
3015
+			}
2791 3016
 			$original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
2792
-		}
2793
-		else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
3017
+		} else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
2794 3018
 		{
2795
-			if (empty($conf->{$reg[1]}->dir_temp))	// modulepart not supported
3019
+			if (empty($conf->{$reg[1]}->dir_temp)) {
3020
+			    // modulepart not supported
2796 3021
 			{
2797 3022
 				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3023
+			}
2798 3024
 				exit;
2799 3025
 			}
2800
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
3026
+			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
3027
+			    $accessallowed=1;
3028
+			}
2801 3029
 			$original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
2802
-		}
2803
-		else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
3030
+		} else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
2804 3031
 		{
2805
-			if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
3032
+			if (empty($conf->{$reg[1]}->dir_output)) {
3033
+			    // modulepart not supported
2806 3034
 			{
2807 3035
 				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3036
+			}
2808 3037
 				exit;
2809 3038
 			}
2810
-			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1;
3039
+			if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
3040
+			    $accessallowed=1;
3041
+			}
2811 3042
 			$original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
2812
-		}
2813
-		else if (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg))
3043
+		} else if (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg))
2814 3044
 		{
2815
-			if (empty($conf->{$reg[1]}->dir_output))	// modulepart not supported
3045
+			if (empty($conf->{$reg[1]}->dir_output)) {
3046
+			    // modulepart not supported
2816 3047
 			{
2817 3048
 				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3049
+			}
2818 3050
 				exit;
2819 3051
 			}
2820 3052
 			if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file))
@@ -2822,12 +3054,13 @@  discard block
 block discarded – undo
2822 3054
 				$accessallowed=1;
2823 3055
 			}
2824 3056
 			$original_file=$conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
2825
-		}
2826
-		else
3057
+		} else
2827 3058
 		{
2828
-			if (empty($conf->$modulepart->dir_output))	// modulepart not supported
3059
+			if (empty($conf->$modulepart->dir_output)) {
3060
+			    // modulepart not supported
2829 3061
 			{
2830 3062
 				dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
3063
+			}
2831 3064
 				exit;
2832 3065
 			}
2833 3066
 
@@ -2835,12 +3068,15 @@  discard block
 block discarded – undo
2835 3068
 			$subperm=GETPOST('subperm');
2836 3069
 			if ($perm || $subperm)
2837 3070
 			{
2838
-				if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
3071
+				if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) {
3072
+				    $accessallowed=1;
3073
+				}
2839 3074
 				$original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2840
-			}
2841
-			else
3075
+			} else
2842 3076
 			{
2843
-				if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed=1;
3077
+				if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) {
3078
+				    $accessallowed=1;
3079
+				}
2844 3080
 				$original_file=$conf->$modulepart->dir_output.'/'.$original_file;
2845 3081
 			}
2846 3082
 		}
@@ -2858,11 +3094,13 @@  discard block
 block discarded – undo
2858 3094
 
2859 3095
 		// Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
2860 3096
 		$sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
2861
-		if (! empty($conf->global->$sqlProtectConstName))	// If module want to define its own $sqlprotectagainstexternals
3097
+		if (! empty($conf->global->$sqlProtectConstName)) {
3098
+		    // If module want to define its own $sqlprotectagainstexternals
2862 3099
 		{
2863 3100
 			// Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
2864 3101
 			eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
2865 3102
 		}
3103
+		}
2866 3104
 	}
2867 3105
 
2868 3106
 	$ret = array(
@@ -2884,7 +3122,9 @@  discard block
 block discarded – undo
2884 3122
  */
2885 3123
 function dol_filecache($directory, $filename, $object)
2886 3124
 {
2887
-	if (! dol_is_dir($directory)) dol_mkdir($directory);
3125
+	if (! dol_is_dir($directory)) {
3126
+	    dol_mkdir($directory);
3127
+	}
2888 3128
 	$cachefile = $directory . $filename;
2889 3129
 	file_put_contents($cachefile, serialize($object), LOCK_EX);
2890 3130
 	@chmod($cachefile, 0644);
@@ -2938,9 +3178,11 @@  discard block
 block discarded – undo
2938 3178
 
2939 3179
 	$exclude = 'install';
2940 3180
 
2941
-	foreach ($dir->md5file as $file)    // $file is a simpleXMLElement
3181
+	foreach ($dir->md5file as $file) {
3182
+	    // $file is a simpleXMLElement
2942 3183
 	{
2943 3184
 		$filename = $path.$file['name'];
3185
+	}
2944 3186
 		$file_list['insignature'][] = $filename;
2945 3187
 		$expectedmd5 = (string) $file;
2946 3188
 
@@ -2949,27 +3191,31 @@  discard block
 block discarded – undo
2949 3191
 		if (!file_exists($pathref.'/'.$filename))
2950 3192
 		{
2951 3193
 			$file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5);
2952
-		}
2953
-		else
3194
+		} else
2954 3195
 		{
2955 3196
 			$md5_local = md5_file($pathref.'/'.$filename);
2956 3197
 
2957
-			if ($conffile == '/etc/dolibarr/conf.php' && $filename == '/filefunc.inc.php')	// For install with deb or rpm, we ignore test on filefunc.inc.php that was modified by package
3198
+			if ($conffile == '/etc/dolibarr/conf.php' && $filename == '/filefunc.inc.php') {
3199
+			    // For install with deb or rpm, we ignore test on filefunc.inc.php that was modified by package
2958 3200
 			{
2959 3201
 				$checksumconcat[] = $expectedmd5;
2960 3202
 			}
2961
-			else
3203
+			} else
2962 3204
 			{
2963
-				if ($md5_local != $expectedmd5) $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'md5'=>(string) $md5_local);
3205
+				if ($md5_local != $expectedmd5) {
3206
+				    $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'md5'=>(string) $md5_local);
3207
+				}
2964 3208
 				$checksumconcat[] = $md5_local;
2965 3209
 			}
2966 3210
 		}
2967 3211
 	}
2968 3212
 
2969
-	foreach ($dir->dir as $subdir)			// $subdir['name'] is  '' or '/accountancy/admin' for example
3213
+	foreach ($dir->dir as $subdir) {
3214
+	    // $subdir['name'] is  '' or '/accountancy/admin' for example
2970 3215
 	{
2971 3216
 		getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
2972 3217
 	}
3218
+	}
2973 3219
 
2974 3220
 	return $file_list;
2975 3221
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/expedition.lib.php 3 patches
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -34,29 +34,29 @@  discard block
 block discarded – undo
34 34
  */
35 35
 function expedition_prepare_head(Expedition $object)
36 36
 {
37
-	global $langs, $conf, $user;
38
-	if (! empty($conf->expedition->enabled)) $langs->load("sendings");
39
-	$langs->load("orders");
37
+    global $langs, $conf, $user;
38
+    if (! empty($conf->expedition->enabled)) $langs->load("sendings");
39
+    $langs->load("orders");
40 40
 
41
-	$h = 0;
42
-	$head = array();
43
-	$h = 0;
44
-	
45
-	$head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
46
-	$head[$h][1] = $langs->trans("Setup");
47
-	$h++;
48
-	
49
-	$head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
50
-	$head[$h][1] = $langs->trans("Shipment");
51
-	$hselected=$h;
52
-	$h++;
53
-	
54
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
55
-	{
56
-		$head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
57
-		$head[$h][1] = $langs->trans("Receivings");
58
-		$h++;
59
-	}
41
+    $h = 0;
42
+    $head = array();
43
+    $h = 0;
44
+	
45
+    $head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
46
+    $head[$h][1] = $langs->trans("Setup");
47
+    $h++;
48
+	
49
+    $head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
50
+    $head[$h][1] = $langs->trans("Shipment");
51
+    $hselected=$h;
52
+    $h++;
53
+	
54
+    if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
55
+    {
56
+        $head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
57
+        $head[$h][1] = $langs->trans("Receivings");
58
+        $h++;
59
+    }
60 60
 	
61 61
 
62 62
     complete_head_from_modules($conf,$langs,$object,$head,$h,'order','remove');
@@ -71,72 +71,72 @@  discard block
 block discarded – undo
71 71
  */
72 72
 function expedition_admin_prepare_head()
73 73
 {
74
-	global $langs, $conf, $user;
75
-	$langs->load("sendings");
74
+    global $langs, $conf, $user;
75
+    $langs->load("sendings");
76 76
 
77
-	$h = 0;
78
-	$head = array();
79
-	
80
-	$head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
81
-	$head[$h][1] = $langs->trans("Setup");
82
-	$head[$h][2] = 'general';
83
-	$h++;
84
-	
85
-	
86
-	if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
87
-	{
88
-		$head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
89
-		$head[$h][1] = $langs->trans("Shipment");
90
-		$head[$h][2] = 'shipment';
91
-		$h++;
92
-	}
93
-	
94
-	
95
-	if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
96
-	{
97
-	$head[$h][0] = DOL_URL_ROOT.'/admin/expedition_extrafields.php';
98
-	$head[$h][1] = $langs->trans("ExtraFields");
99
-	$head[$h][2] = 'attributes_shipment';
100
-	$h++;
101
-	}
102
-	
103
-	if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
104
-	{
105
-	$head[$h][0] = DOL_URL_ROOT.'/admin/expeditiondet_extrafields.php';
106
-	$head[$h][1] = $langs->trans("ExtraFieldsLines");
107
-	$head[$h][2] = 'attributeslines_shipment';
108
-	$h++;
109
-	}
110
-	
111
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
112
-	{
113
-		$head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
114
-		$head[$h][1] = $langs->trans("Receivings");
115
-		$head[$h][2] = 'receivings';
116
-		$h++;
117
-	}
118
-	
119
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
120
-	{
121
-		$head[$h][0] = DOL_URL_ROOT.'/admin/livraison_extrafields.php';
122
-		$head[$h][1] = $langs->trans("ExtraFields");
123
-		$head[$h][2] = 'attributes_receivings';
124
-		$h++;
125
-	}
126
-	
127
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
128
-	{
129
-		$head[$h][0] = DOL_URL_ROOT.'/admin/livraisondet_extrafields.php';
130
-		$head[$h][1] = $langs->trans("ExtraFieldsLines");
131
-		$head[$h][2] = 'attributeslines_receivings';
132
-		$h++;
133
-	}
134
-	
135
-	
136
-	
137
-	complete_head_from_modules($conf,$langs,null,$head,$h,'expedition_admin','remove');
77
+    $h = 0;
78
+    $head = array();
79
+	
80
+    $head[$h][0] = DOL_URL_ROOT."/admin/confexped.php";
81
+    $head[$h][1] = $langs->trans("Setup");
82
+    $head[$h][2] = 'general';
83
+    $h++;
84
+	
85
+	
86
+    if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
87
+    {
88
+        $head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
89
+        $head[$h][1] = $langs->trans("Shipment");
90
+        $head[$h][2] = 'shipment';
91
+        $h++;
92
+    }
93
+	
94
+	
95
+    if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
96
+    {
97
+    $head[$h][0] = DOL_URL_ROOT.'/admin/expedition_extrafields.php';
98
+    $head[$h][1] = $langs->trans("ExtraFields");
99
+    $head[$h][2] = 'attributes_shipment';
100
+    $h++;
101
+    }
102
+	
103
+    if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
104
+    {
105
+    $head[$h][0] = DOL_URL_ROOT.'/admin/expeditiondet_extrafields.php';
106
+    $head[$h][1] = $langs->trans("ExtraFieldsLines");
107
+    $head[$h][2] = 'attributeslines_shipment';
108
+    $h++;
109
+    }
110
+	
111
+    if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
112
+    {
113
+        $head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
114
+        $head[$h][1] = $langs->trans("Receivings");
115
+        $head[$h][2] = 'receivings';
116
+        $h++;
117
+    }
118
+	
119
+    if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
120
+    {
121
+        $head[$h][0] = DOL_URL_ROOT.'/admin/livraison_extrafields.php';
122
+        $head[$h][1] = $langs->trans("ExtraFields");
123
+        $head[$h][2] = 'attributes_receivings';
124
+        $h++;
125
+    }
126
+	
127
+    if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
128
+    {
129
+        $head[$h][0] = DOL_URL_ROOT.'/admin/livraisondet_extrafields.php';
130
+        $head[$h][1] = $langs->trans("ExtraFieldsLines");
131
+        $head[$h][2] = 'attributeslines_receivings';
132
+        $h++;
133
+    }
134
+	
135
+	
136
+	
137
+    complete_head_from_modules($conf,$langs,null,$head,$h,'expedition_admin','remove');
138 138
 
139
-	return $head;
139
+    return $head;
140 140
 }
141 141
 
142 142
 
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 function expedition_prepare_head(Expedition $object)
36 36
 {
37 37
 	global $langs, $conf, $user;
38
-	if (! empty($conf->expedition->enabled)) $langs->load("sendings");
38
+	if (!empty($conf->expedition->enabled)) $langs->load("sendings");
39 39
 	$langs->load("orders");
40 40
 
41 41
 	$h = 0;
@@ -48,10 +48,10 @@  discard block
 block discarded – undo
48 48
 	
49 49
 	$head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
50 50
 	$head[$h][1] = $langs->trans("Shipment");
51
-	$hselected=$h;
51
+	$hselected = $h;
52 52
 	$h++;
53 53
 	
54
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
54
+	if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
55 55
 	{
56 56
 		$head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
57 57
 		$head[$h][1] = $langs->trans("Receivings");
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 	}
60 60
 	
61 61
 
62
-    complete_head_from_modules($conf,$langs,$object,$head,$h,'order','remove');
62
+    complete_head_from_modules($conf, $langs, $object, $head, $h, 'order', 'remove');
63 63
 
64 64
     return $head;
65 65
 }
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 	$h++;
84 84
 	
85 85
 	
86
-	if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
86
+	if (!empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
87 87
 	{
88 88
 		$head[$h][0] = DOL_URL_ROOT."/admin/expedition.php";
89 89
 		$head[$h][1] = $langs->trans("Shipment");
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 	}
93 93
 	
94 94
 	
95
-	if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
95
+	if (!empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
96 96
 	{
97 97
 	$head[$h][0] = DOL_URL_ROOT.'/admin/expedition_extrafields.php';
98 98
 	$head[$h][1] = $langs->trans("ExtraFields");
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	$h++;
101 101
 	}
102 102
 	
103
-	if (! empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
103
+	if (!empty($conf->global->MAIN_SUBMODULE_EXPEDITION))
104 104
 	{
105 105
 	$head[$h][0] = DOL_URL_ROOT.'/admin/expeditiondet_extrafields.php';
106 106
 	$head[$h][1] = $langs->trans("ExtraFieldsLines");
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	$h++;
109 109
 	}
110 110
 	
111
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
111
+	if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
112 112
 	{
113 113
 		$head[$h][0] = DOL_URL_ROOT."/admin/livraison.php";
114 114
 		$head[$h][1] = $langs->trans("Receivings");
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 		$h++;
117 117
 	}
118 118
 	
119
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
119
+	if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
120 120
 	{
121 121
 		$head[$h][0] = DOL_URL_ROOT.'/admin/livraison_extrafields.php';
122 122
 		$head[$h][1] = $langs->trans("ExtraFields");
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 		$h++;
125 125
 	}
126 126
 	
127
-	if (! empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
127
+	if (!empty($conf->global->MAIN_SUBMODULE_LIVRAISON))
128 128
 	{
129 129
 		$head[$h][0] = DOL_URL_ROOT.'/admin/livraisondet_extrafields.php';
130 130
 		$head[$h][1] = $langs->trans("ExtraFieldsLines");
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 	
135 135
 	
136 136
 	
137
-	complete_head_from_modules($conf,$langs,null,$head,$h,'expedition_admin','remove');
137
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'expedition_admin', 'remove');
138 138
 
139 139
 	return $head;
140 140
 }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,9 @@
 block discarded – undo
35 35
 function expedition_prepare_head(Expedition $object)
36 36
 {
37 37
 	global $langs, $conf, $user;
38
-	if (! empty($conf->expedition->enabled)) $langs->load("sendings");
38
+	if (! empty($conf->expedition->enabled)) {
39
+	    $langs->load("sendings");
40
+	}
39 41
 	$langs->load("orders");
40 42
 
41 43
 	$h = 0;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/fourn.lib.php 3 patches
Indentation   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -33,25 +33,25 @@  discard block
 block discarded – undo
33 33
  */
34 34
 function facturefourn_prepare_head($object)
35 35
 {
36
-	global $db, $langs, $conf;
37
-
38
-	$h = 0;
39
-	$head = array();
40
-
41
-	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id;
42
-	$head[$h][1] = $langs->trans('Card');
43
-	$head[$h][2] = 'card';
44
-	$h++;
45
-
46
-	if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
47
-	{
48
-	    $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
49
-	    $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id;
50
-		$head[$h][1] = $langs->trans('ContactsAddresses');
51
-		if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
52
-		$head[$h][2] = 'contact';
53
-		$h++;
54
-	}
36
+    global $db, $langs, $conf;
37
+
38
+    $h = 0;
39
+    $head = array();
40
+
41
+    $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id;
42
+    $head[$h][1] = $langs->trans('Card');
43
+    $head[$h][2] = 'card';
44
+    $h++;
45
+
46
+    if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
47
+    {
48
+        $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
49
+        $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id;
50
+        $head[$h][1] = $langs->trans('ContactsAddresses');
51
+        if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
52
+        $head[$h][2] = 'contact';
53
+        $h++;
54
+    }
55 55
 
56 56
     // Show more tabs from modules
57 57
     // Entries must be declared in modules descriptor with line
@@ -61,31 +61,31 @@  discard block
 block discarded – undo
61 61
 
62 62
     if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
63 63
     {
64
-    	$nbNote = 0;
64
+        $nbNote = 0;
65 65
         if(!empty($object->note_private)) $nbNote++;
66
-		if(!empty($object->note_public)) $nbNote++;
67
-    	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id;
68
-    	$head[$h][1] = $langs->trans('Notes');
69
-		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
70
-    	$head[$h][2] = 'note';
71
-    	$h++;
66
+        if(!empty($object->note_public)) $nbNote++;
67
+        $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id;
68
+        $head[$h][1] = $langs->trans('Notes');
69
+        if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
70
+        $head[$h][2] = 'note';
71
+        $h++;
72 72
     }
73 73
 
74
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
74
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
75 75
     require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
76
-	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$object->ref;
77
-	$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
76
+    $upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$object->ref;
77
+    $nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
78 78
     $nbLinks=Link::count($db, $object->element, $object->id);
79
-	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id;
80
-	$head[$h][1] = $langs->trans('Documents');
81
-	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
82
-	$head[$h][2] = 'documents';
83
-	$h++;
79
+    $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id;
80
+    $head[$h][1] = $langs->trans('Documents');
81
+    if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
82
+    $head[$h][2] = 'documents';
83
+    $h++;
84 84
 
85
-	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/info.php?facid='.$object->id;
86
-	$head[$h][1] = $langs->trans('Info');
87
-	$head[$h][2] = 'info';
88
-	$h++;
85
+    $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/info.php?facid='.$object->id;
86
+    $head[$h][1] = $langs->trans('Info');
87
+    $head[$h][2] = 'info';
88
+    $h++;
89 89
 
90 90
     complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_invoice','remove');
91 91
 
@@ -101,36 +101,36 @@  discard block
 block discarded – undo
101 101
  */
102 102
 function ordersupplier_prepare_head($object)
103 103
 {
104
-	global $db, $langs, $conf, $user;
105
-
106
-	$h = 0;
107
-	$head = array();
108
-
109
-	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id;
110
-	$head[$h][1] = $langs->trans("OrderCard");
111
-	$head[$h][2] = 'card';
112
-	$h++;
113
-
114
-	if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
115
-	{
116
-	    $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
117
-	    $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/contact.php?id='.$object->id;
118
-		$head[$h][1] = $langs->trans('ContactsAddresses');
119
-		if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
120
-		$head[$h][2] = 'contact';
121
-		$h++;
122
-	}
123
-
124
-	if (! empty($conf->stock->enabled) && (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)))
125
-	{
126
-		$langs->load("stocks");
127
-		$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id;
128
-		$head[$h][1] = $langs->trans("OrderDispatch");
129
-		$head[$h][2] = 'dispatch';
130
-		$h++;
131
-	}
132
-
133
-	// Show more tabs from modules
104
+    global $db, $langs, $conf, $user;
105
+
106
+    $h = 0;
107
+    $head = array();
108
+
109
+    $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id;
110
+    $head[$h][1] = $langs->trans("OrderCard");
111
+    $head[$h][2] = 'card';
112
+    $h++;
113
+
114
+    if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
115
+    {
116
+        $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
117
+        $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/contact.php?id='.$object->id;
118
+        $head[$h][1] = $langs->trans('ContactsAddresses');
119
+        if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
120
+        $head[$h][2] = 'contact';
121
+        $h++;
122
+    }
123
+
124
+    if (! empty($conf->stock->enabled) && (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)))
125
+    {
126
+        $langs->load("stocks");
127
+        $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id;
128
+        $head[$h][1] = $langs->trans("OrderDispatch");
129
+        $head[$h][2] = 'dispatch';
130
+        $h++;
131
+    }
132
+
133
+    // Show more tabs from modules
134 134
     // Entries must be declared in modules descriptor with line
135 135
     // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
136 136
     // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to remove a tab
@@ -138,38 +138,38 @@  discard block
 block discarded – undo
138 138
 
139 139
     if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
140 140
     {
141
-    	$nbNote = 0;
141
+        $nbNote = 0;
142 142
         if(!empty($object->note_private)) $nbNote++;
143
-		if(!empty($object->note_public)) $nbNote++;
144
-    	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/note.php?id='.$object->id;
145
-    	$head[$h][1] = $langs->trans("Notes");
146
-		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
147
-    	$head[$h][2] = 'note';
148
-    	$h++;
143
+        if(!empty($object->note_public)) $nbNote++;
144
+        $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/note.php?id='.$object->id;
145
+        $head[$h][1] = $langs->trans("Notes");
146
+        if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
147
+        $head[$h][2] = 'note';
148
+        $h++;
149 149
     }
150 150
 
151
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
151
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
152 152
     require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
153
-	$upload_dir = $conf->fournisseur->dir_output . "/commande/" . dol_sanitizeFileName($object->ref);
154
-	$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
153
+    $upload_dir = $conf->fournisseur->dir_output . "/commande/" . dol_sanitizeFileName($object->ref);
154
+    $nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
155 155
     $nbLinks=Link::count($db, $object->element, $object->id);
156
-	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/document.php?id='.$object->id;
157
-	$head[$h][1] = $langs->trans('Documents');
158
-	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
159
-	$head[$h][2] = 'documents';
160
-	$h++;
161
-
162
-	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/info.php?id='.$object->id;
163
-	$head[$h][1].= $langs->trans("Events");
164
-	if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) ))
165
-	{
166
-	    $head[$h][1].= '/';
167
-	    $head[$h][1].= $langs->trans("Agenda");
168
-	}
169
-	$head[$h][2] = 'info';
170
-	$h++;
171
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_order', 'remove');
172
-	return $head;
156
+    $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/document.php?id='.$object->id;
157
+    $head[$h][1] = $langs->trans('Documents');
158
+    if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
159
+    $head[$h][2] = 'documents';
160
+    $h++;
161
+
162
+    $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/info.php?id='.$object->id;
163
+    $head[$h][1].= $langs->trans("Events");
164
+    if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) ))
165
+    {
166
+        $head[$h][1].= '/';
167
+        $head[$h][1].= $langs->trans("Agenda");
168
+    }
169
+    $head[$h][2] = 'info';
170
+    $h++;
171
+    complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_order', 'remove');
172
+    return $head;
173 173
 }
174 174
 
175 175
 /**
@@ -179,53 +179,53 @@  discard block
 block discarded – undo
179 179
  */
180 180
 function supplierorder_admin_prepare_head()
181 181
 {
182
-	global $langs, $conf, $user;
182
+    global $langs, $conf, $user;
183 183
 
184
-	$h = 0;
185
-	$head = array();
184
+    $h = 0;
185
+    $head = array();
186 186
 
187
-	$head[$h][0] = DOL_URL_ROOT."/admin/supplier_order.php";
188
-	$head[$h][1] = $langs->trans("SupplierOrder");
189
-	$head[$h][2] = 'order';
190
-	$h++;
187
+    $head[$h][0] = DOL_URL_ROOT."/admin/supplier_order.php";
188
+    $head[$h][1] = $langs->trans("SupplierOrder");
189
+    $head[$h][2] = 'order';
190
+    $h++;
191 191
 
192
-	$head[$h][0] = DOL_URL_ROOT."/admin/supplier_invoice.php";
193
-	$head[$h][1] = $langs->trans("SuppliersInvoice");
194
-	$head[$h][2] = 'invoice';
195
-	$h++;
192
+    $head[$h][0] = DOL_URL_ROOT."/admin/supplier_invoice.php";
193
+    $head[$h][1] = $langs->trans("SuppliersInvoice");
194
+    $head[$h][2] = 'invoice';
195
+    $h++;
196 196
 
197
-	$head[$h][0] = DOL_URL_ROOT."/admin/supplier_payment.php";
198
-	$head[$h][1] = $langs->trans("SuppliersPayment");
199
-	$head[$h][2] = 'supplierpayment';
200
-	$h++;
197
+    $head[$h][0] = DOL_URL_ROOT."/admin/supplier_payment.php";
198
+    $head[$h][1] = $langs->trans("SuppliersPayment");
199
+    $head[$h][2] = 'supplierpayment';
200
+    $h++;
201 201
 
202
-	complete_head_from_modules($conf,$langs,null,$head,$h,'supplierorder_admin');
202
+    complete_head_from_modules($conf,$langs,null,$head,$h,'supplierorder_admin');
203 203
 
204
-	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierorder_extrafields.php';
205
-	$head[$h][1] = $langs->trans("ExtraFieldsSupplierOrders");
206
-	$head[$h][2] = 'supplierorder';
207
-	$h++;
204
+    $head[$h][0] = DOL_URL_ROOT.'/admin/supplierorder_extrafields.php';
205
+    $head[$h][1] = $langs->trans("ExtraFieldsSupplierOrders");
206
+    $head[$h][2] = 'supplierorder';
207
+    $h++;
208 208
 
209
-	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierorderdet_extrafields.php';
210
-	$head[$h][1] = $langs->trans("ExtraFieldsSupplierOrdersLines");
211
-	$head[$h][2] = 'supplierorderdet';
212
-	$h++;
209
+    $head[$h][0] = DOL_URL_ROOT.'/admin/supplierorderdet_extrafields.php';
210
+    $head[$h][1] = $langs->trans("ExtraFieldsSupplierOrdersLines");
211
+    $head[$h][2] = 'supplierorderdet';
212
+    $h++;
213 213
 
214 214
 
215 215
 
216
-	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoice_extrafields.php';
217
-	$head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoices");
218
-	$head[$h][2] = 'supplierinvoice';
219
-	$h++;
216
+    $head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoice_extrafields.php';
217
+    $head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoices");
218
+    $head[$h][2] = 'supplierinvoice';
219
+    $h++;
220 220
 
221
-	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoicedet_extrafields.php';
222
-	$head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoicesLines");
223
-	$head[$h][2] = 'supplierinvoicedet';
224
-	$h++;
221
+    $head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoicedet_extrafields.php';
222
+    $head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoicesLines");
223
+    $head[$h][2] = 'supplierinvoicedet';
224
+    $h++;
225 225
 
226
-	complete_head_from_modules($conf,$langs,null,$head,$h,'supplierorder_admin','remove');
226
+    complete_head_from_modules($conf,$langs,null,$head,$h,'supplierorder_admin','remove');
227 227
 
228
-	return $head;
228
+    return $head;
229 229
 }
230 230
 
231 231
 
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -45,10 +45,10 @@  discard block
 block discarded – undo
45 45
 
46 46
 	if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
47 47
 	{
48
-	    $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
48
+	    $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
49 49
 	    $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id;
50 50
 		$head[$h][1] = $langs->trans('ContactsAddresses');
51
-		if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
51
+		if ($nbContact > 0) $head[$h][1] .= ' <span class="badge">'.$nbContact.'</span>';
52 52
 		$head[$h][2] = 'contact';
53 53
 		$h++;
54 54
 	}
@@ -57,28 +57,28 @@  discard block
 block discarded – undo
57 57
     // Entries must be declared in modules descriptor with line
58 58
     // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
59 59
     // $this->tabs = array('entity:-tabname);   												to remove a tab
60
-    complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_invoice');
60
+    complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice');
61 61
 
62 62
     if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
63 63
     {
64 64
     	$nbNote = 0;
65
-        if(!empty($object->note_private)) $nbNote++;
66
-		if(!empty($object->note_public)) $nbNote++;
65
+        if (!empty($object->note_private)) $nbNote++;
66
+		if (!empty($object->note_public)) $nbNote++;
67 67
     	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id;
68 68
     	$head[$h][1] = $langs->trans('Notes');
69
-		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
69
+		if ($nbNote > 0) $head[$h][1] .= ' <span class="badge">'.$nbNote.'</span>';
70 70
     	$head[$h][2] = 'note';
71 71
     	$h++;
72 72
     }
73 73
 
74 74
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
75 75
     require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
76
-	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$object->ref;
77
-	$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
78
-    $nbLinks=Link::count($db, $object->element, $object->id);
76
+	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object->ref;
77
+	$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
78
+    $nbLinks = Link::count($db, $object->element, $object->id);
79 79
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id;
80 80
 	$head[$h][1] = $langs->trans('Documents');
81
-	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
81
+	if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ' <span class="badge">'.($nbFiles + $nbLinks).'</span>';
82 82
 	$head[$h][2] = 'documents';
83 83
 	$h++;
84 84
 
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	$head[$h][2] = 'info';
88 88
 	$h++;
89 89
 
90
-    complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_invoice','remove');
90
+    complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice', 'remove');
91 91
 
92 92
     return $head;
93 93
 }
@@ -113,15 +113,15 @@  discard block
 block discarded – undo
113 113
 
114 114
 	if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
115 115
 	{
116
-	    $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
116
+	    $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
117 117
 	    $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/contact.php?id='.$object->id;
118 118
 		$head[$h][1] = $langs->trans('ContactsAddresses');
119
-		if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
119
+		if ($nbContact > 0) $head[$h][1] .= ' <span class="badge">'.$nbContact.'</span>';
120 120
 		$head[$h][2] = 'contact';
121 121
 		$h++;
122 122
 	}
123 123
 
124
-	if (! empty($conf->stock->enabled) && (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)))
124
+	if (!empty($conf->stock->enabled) && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)))
125 125
 	{
126 126
 		$langs->load("stocks");
127 127
 		$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id;
@@ -134,41 +134,41 @@  discard block
 block discarded – undo
134 134
     // Entries must be declared in modules descriptor with line
135 135
     // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
136 136
     // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to remove a tab
137
-    complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_order');
137
+    complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_order');
138 138
 
139 139
     if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
140 140
     {
141 141
     	$nbNote = 0;
142
-        if(!empty($object->note_private)) $nbNote++;
143
-		if(!empty($object->note_public)) $nbNote++;
142
+        if (!empty($object->note_private)) $nbNote++;
143
+		if (!empty($object->note_public)) $nbNote++;
144 144
     	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/note.php?id='.$object->id;
145 145
     	$head[$h][1] = $langs->trans("Notes");
146
-		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
146
+		if ($nbNote > 0) $head[$h][1] .= ' <span class="badge">'.$nbNote.'</span>';
147 147
     	$head[$h][2] = 'note';
148 148
     	$h++;
149 149
     }
150 150
 
151 151
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
152 152
     require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
153
-	$upload_dir = $conf->fournisseur->dir_output . "/commande/" . dol_sanitizeFileName($object->ref);
154
-	$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
155
-    $nbLinks=Link::count($db, $object->element, $object->id);
153
+	$upload_dir = $conf->fournisseur->dir_output."/commande/".dol_sanitizeFileName($object->ref);
154
+	$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
155
+    $nbLinks = Link::count($db, $object->element, $object->id);
156 156
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/document.php?id='.$object->id;
157 157
 	$head[$h][1] = $langs->trans('Documents');
158
-	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
158
+	if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ' <span class="badge">'.($nbFiles + $nbLinks).'</span>';
159 159
 	$head[$h][2] = 'documents';
160 160
 	$h++;
161 161
 
162 162
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/info.php?id='.$object->id;
163
-	$head[$h][1].= $langs->trans("Events");
164
-	if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) ))
163
+	$head[$h][1] .= $langs->trans("Events");
164
+	if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read)))
165 165
 	{
166
-	    $head[$h][1].= '/';
167
-	    $head[$h][1].= $langs->trans("Agenda");
166
+	    $head[$h][1] .= '/';
167
+	    $head[$h][1] .= $langs->trans("Agenda");
168 168
 	}
169 169
 	$head[$h][2] = 'info';
170 170
 	$h++;
171
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'supplier_order', 'remove');
171
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_order', 'remove');
172 172
 	return $head;
173 173
 }
174 174
 
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	$head[$h][2] = 'supplierpayment';
200 200
 	$h++;
201 201
 
202
-	complete_head_from_modules($conf,$langs,null,$head,$h,'supplierorder_admin');
202
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'supplierorder_admin');
203 203
 
204 204
 	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierorder_extrafields.php';
205 205
 	$head[$h][1] = $langs->trans("ExtraFieldsSupplierOrders");
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	$head[$h][2] = 'supplierinvoicedet';
224 224
 	$h++;
225 225
 
226
-	complete_head_from_modules($conf,$langs,null,$head,$h,'supplierorder_admin','remove');
226
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'supplierorder_admin', 'remove');
227 227
 
228 228
 	return $head;
229 229
 }
Please login to merge, or discard this patch.
Braces   +30 added lines, -10 removed lines patch added patch discarded remove patch
@@ -48,7 +48,9 @@  discard block
 block discarded – undo
48 48
 	    $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
49 49
 	    $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id;
50 50
 		$head[$h][1] = $langs->trans('ContactsAddresses');
51
-		if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
51
+		if ($nbContact > 0) {
52
+		    $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
53
+		}
52 54
 		$head[$h][2] = 'contact';
53 55
 		$h++;
54 56
 	}
@@ -62,11 +64,17 @@  discard block
 block discarded – undo
62 64
     if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
63 65
     {
64 66
     	$nbNote = 0;
65
-        if(!empty($object->note_private)) $nbNote++;
66
-		if(!empty($object->note_public)) $nbNote++;
67
+        if(!empty($object->note_private)) {
68
+            $nbNote++;
69
+        }
70
+		if(!empty($object->note_public)) {
71
+		    $nbNote++;
72
+		}
67 73
     	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id;
68 74
     	$head[$h][1] = $langs->trans('Notes');
69
-		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
75
+		if ($nbNote > 0) {
76
+		    $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
77
+		}
70 78
     	$head[$h][2] = 'note';
71 79
     	$h++;
72 80
     }
@@ -78,7 +86,9 @@  discard block
 block discarded – undo
78 86
     $nbLinks=Link::count($db, $object->element, $object->id);
79 87
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id;
80 88
 	$head[$h][1] = $langs->trans('Documents');
81
-	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
89
+	if (($nbFiles+$nbLinks) > 0) {
90
+	    $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
91
+	}
82 92
 	$head[$h][2] = 'documents';
83 93
 	$h++;
84 94
 
@@ -116,7 +126,9 @@  discard block
 block discarded – undo
116 126
 	    $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
117 127
 	    $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/contact.php?id='.$object->id;
118 128
 		$head[$h][1] = $langs->trans('ContactsAddresses');
119
-		if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
129
+		if ($nbContact > 0) {
130
+		    $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
131
+		}
120 132
 		$head[$h][2] = 'contact';
121 133
 		$h++;
122 134
 	}
@@ -139,11 +151,17 @@  discard block
 block discarded – undo
139 151
     if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
140 152
     {
141 153
     	$nbNote = 0;
142
-        if(!empty($object->note_private)) $nbNote++;
143
-		if(!empty($object->note_public)) $nbNote++;
154
+        if(!empty($object->note_private)) {
155
+            $nbNote++;
156
+        }
157
+		if(!empty($object->note_public)) {
158
+		    $nbNote++;
159
+		}
144 160
     	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/note.php?id='.$object->id;
145 161
     	$head[$h][1] = $langs->trans("Notes");
146
-		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
162
+		if ($nbNote > 0) {
163
+		    $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
164
+		}
147 165
     	$head[$h][2] = 'note';
148 166
     	$h++;
149 167
     }
@@ -155,7 +173,9 @@  discard block
 block discarded – undo
155 173
     $nbLinks=Link::count($db, $object->element, $object->id);
156 174
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/commande/document.php?id='.$object->id;
157 175
 	$head[$h][1] = $langs->trans('Documents');
158
-	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
176
+	if (($nbFiles+$nbLinks) > 0) {
177
+	    $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
178
+	}
159 179
 	$head[$h][2] = 'documents';
160 180
 	$h++;
161 181
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/parsemd.lib.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -29,15 +29,15 @@
 block discarded – undo
29 29
  * @param   string    $replaceimagepath     Replace path to image with another path. Exemple: ('doc/'=>'xxx/aaa/')
30 30
  * @return	string                          Parsed content
31 31
  */
32
-function dolMd2Html($content, $parser='parsedown',$replaceimagepath=null)
32
+function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null)
33 33
 {
34 34
     if (is_array($replaceimagepath))
35 35
     {
36
-        foreach($replaceimagepath as $key => $val)
36
+        foreach ($replaceimagepath as $key => $val)
37 37
         {
38 38
             $keytoreplace = ']('.$key;
39 39
             $valafter = ']('.$val;
40
-            $content = preg_replace('/'.preg_quote($keytoreplace,'/').'/m', $valafter, $content);
40
+            $content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content);
41 41
         }
42 42
     }
43 43
     if ($parser == 'parsedown')
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -45,8 +45,7 @@
 block discarded – undo
45 45
         include_once DOL_DOCUMENT_ROOT.'/includes/parsedown/Parsedown.php';
46 46
         $Parsedown = new Parsedown();
47 47
         $content = $Parsedown->text($content);
48
-    }
49
-    else
48
+    } else
50 49
     {
51 50
         $content = nl2br($content);
52 51
     }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/pdf.lib.php 3 patches
Indentation   +1604 added lines, -1604 removed lines patch added patch discarded remove patch
@@ -41,34 +41,34 @@  discard block
 block discarded – undo
41 41
  */
42 42
 function pdf_getFormat(Translate $outputlangs = null)
43 43
 {
44
-	global $conf,$db;
45
-
46
-	// Default value if setup was not done and/or entry into c_paper_format not defined
47
-	$width=210; $height=297; $unit='mm';
48
-
49
-	if (empty($conf->global->MAIN_PDF_FORMAT))
50
-	{
51
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
52
-		$pdfformat=dol_getDefaultFormat($outputlangs);
53
-	}
54
-	else $pdfformat=$conf->global->MAIN_PDF_FORMAT;
55
-
56
-	$sql="SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format";
57
-	$sql.=" WHERE code = '".$pdfformat."'";
58
-	$resql=$db->query($sql);
59
-	if ($resql)
60
-	{
61
-		$obj=$db->fetch_object($resql);
62
-		if ($obj)
63
-		{
64
-			$width=(int) $obj->width;
65
-			$height=(int) $obj->height;
66
-			$unit=$obj->unit;
67
-		}
68
-	}
69
-
70
-	//print "pdfformat=".$pdfformat." width=".$width." height=".$height." unit=".$unit;
71
-	return array('width'=>$width,'height'=>$height,'unit'=>$unit);
44
+    global $conf,$db;
45
+
46
+    // Default value if setup was not done and/or entry into c_paper_format not defined
47
+    $width=210; $height=297; $unit='mm';
48
+
49
+    if (empty($conf->global->MAIN_PDF_FORMAT))
50
+    {
51
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
52
+        $pdfformat=dol_getDefaultFormat($outputlangs);
53
+    }
54
+    else $pdfformat=$conf->global->MAIN_PDF_FORMAT;
55
+
56
+    $sql="SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format";
57
+    $sql.=" WHERE code = '".$pdfformat."'";
58
+    $resql=$db->query($sql);
59
+    if ($resql)
60
+    {
61
+        $obj=$db->fetch_object($resql);
62
+        if ($obj)
63
+        {
64
+            $width=(int) $obj->width;
65
+            $height=(int) $obj->height;
66
+            $unit=$obj->unit;
67
+        }
68
+    }
69
+
70
+    //print "pdfformat=".$pdfformat." width=".$width." height=".$height." unit=".$unit;
71
+    return array('width'=>$width,'height'=>$height,'unit'=>$unit);
72 72
 }
73 73
 
74 74
 /**
@@ -81,64 +81,64 @@  discard block
 block discarded – undo
81 81
  */
82 82
 function pdf_getInstance($format='',$metric='mm',$pagetype='P')
83 83
 {
84
-	global $conf;
85
-
86
-	// Define constant for TCPDF
87
-	if (! defined('K_TCPDF_EXTERNAL_CONFIG'))
88
-	{
89
-		define('K_TCPDF_EXTERNAL_CONFIG',1);	// this avoid using tcpdf_config file
90
-		define('K_PATH_CACHE', DOL_DATA_ROOT.'/admin/temp/');
91
-		define('K_PATH_URL_CACHE', DOL_DATA_ROOT.'/admin/temp/');
92
-		dol_mkdir(K_PATH_CACHE);
93
-		define('K_BLANK_IMAGE', '_blank.png');
94
-		define('PDF_PAGE_FORMAT', 'A4');
95
-		define('PDF_PAGE_ORIENTATION', 'P');
96
-		define('PDF_CREATOR', 'TCPDF');
97
-		define('PDF_AUTHOR', 'TCPDF');
98
-		define('PDF_HEADER_TITLE', 'TCPDF Example');
99
-		define('PDF_HEADER_STRING', "by Dolibarr ERP CRM");
100
-		define('PDF_UNIT', 'mm');
101
-		define('PDF_MARGIN_HEADER', 5);
102
-		define('PDF_MARGIN_FOOTER', 10);
103
-		define('PDF_MARGIN_TOP', 27);
104
-		define('PDF_MARGIN_BOTTOM', 25);
105
-		define('PDF_MARGIN_LEFT', 15);
106
-		define('PDF_MARGIN_RIGHT', 15);
107
-		define('PDF_FONT_NAME_MAIN', 'helvetica');
108
-		define('PDF_FONT_SIZE_MAIN', 10);
109
-		define('PDF_FONT_NAME_DATA', 'helvetica');
110
-		define('PDF_FONT_SIZE_DATA', 8);
111
-		define('PDF_FONT_MONOSPACED', 'courier');
112
-		define('PDF_IMAGE_SCALE_RATIO', 1.25);
113
-		define('HEAD_MAGNIFICATION', 1.1);
114
-		define('K_CELL_HEIGHT_RATIO', 1.25);
115
-		define('K_TITLE_MAGNIFICATION', 1.3);
116
-		define('K_SMALL_RATIO', 2/3);
117
-		define('K_THAI_TOPCHARS', true);
118
-		define('K_TCPDF_CALLS_IN_HTML', true);
119
-		define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
120
-	}
121
-
122
-	// Load TCPDF
123
-	require_once TCPDF_PATH.'tcpdf.php';
124
-
125
-	// We need to instantiate tcpdi object (instead of tcpdf) to use merging features. But we can disable it (this will break all merge features).
126
-	if (empty($conf->global->MAIN_DISABLE_TCPDI)) require_once TCPDI_PATH.'tcpdi.php';
127
-
128
-	//$arrayformat=pdf_getFormat();
129
-	//$format=array($arrayformat['width'],$arrayformat['height']);
130
-	//$metric=$arrayformat['unit'];
131
-
132
-	$pdfa=false;											// PDF-1.3
133
-	if (! empty($conf->global->PDF_USE_1A)) $pdfa=true;		// PDF1/A
134
-
135
-	if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
136
-	else $pdf = new TCPDF($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
137
-
138
-	// Protection and encryption of pdf
139
-	if (! empty($conf->global->PDF_SECURITY_ENCRYPTION))
140
-	{
141
-		/* Permission supported by TCPDF
84
+    global $conf;
85
+
86
+    // Define constant for TCPDF
87
+    if (! defined('K_TCPDF_EXTERNAL_CONFIG'))
88
+    {
89
+        define('K_TCPDF_EXTERNAL_CONFIG',1);	// this avoid using tcpdf_config file
90
+        define('K_PATH_CACHE', DOL_DATA_ROOT.'/admin/temp/');
91
+        define('K_PATH_URL_CACHE', DOL_DATA_ROOT.'/admin/temp/');
92
+        dol_mkdir(K_PATH_CACHE);
93
+        define('K_BLANK_IMAGE', '_blank.png');
94
+        define('PDF_PAGE_FORMAT', 'A4');
95
+        define('PDF_PAGE_ORIENTATION', 'P');
96
+        define('PDF_CREATOR', 'TCPDF');
97
+        define('PDF_AUTHOR', 'TCPDF');
98
+        define('PDF_HEADER_TITLE', 'TCPDF Example');
99
+        define('PDF_HEADER_STRING', "by Dolibarr ERP CRM");
100
+        define('PDF_UNIT', 'mm');
101
+        define('PDF_MARGIN_HEADER', 5);
102
+        define('PDF_MARGIN_FOOTER', 10);
103
+        define('PDF_MARGIN_TOP', 27);
104
+        define('PDF_MARGIN_BOTTOM', 25);
105
+        define('PDF_MARGIN_LEFT', 15);
106
+        define('PDF_MARGIN_RIGHT', 15);
107
+        define('PDF_FONT_NAME_MAIN', 'helvetica');
108
+        define('PDF_FONT_SIZE_MAIN', 10);
109
+        define('PDF_FONT_NAME_DATA', 'helvetica');
110
+        define('PDF_FONT_SIZE_DATA', 8);
111
+        define('PDF_FONT_MONOSPACED', 'courier');
112
+        define('PDF_IMAGE_SCALE_RATIO', 1.25);
113
+        define('HEAD_MAGNIFICATION', 1.1);
114
+        define('K_CELL_HEIGHT_RATIO', 1.25);
115
+        define('K_TITLE_MAGNIFICATION', 1.3);
116
+        define('K_SMALL_RATIO', 2/3);
117
+        define('K_THAI_TOPCHARS', true);
118
+        define('K_TCPDF_CALLS_IN_HTML', true);
119
+        define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
120
+    }
121
+
122
+    // Load TCPDF
123
+    require_once TCPDF_PATH.'tcpdf.php';
124
+
125
+    // We need to instantiate tcpdi object (instead of tcpdf) to use merging features. But we can disable it (this will break all merge features).
126
+    if (empty($conf->global->MAIN_DISABLE_TCPDI)) require_once TCPDI_PATH.'tcpdi.php';
127
+
128
+    //$arrayformat=pdf_getFormat();
129
+    //$format=array($arrayformat['width'],$arrayformat['height']);
130
+    //$metric=$arrayformat['unit'];
131
+
132
+    $pdfa=false;											// PDF-1.3
133
+    if (! empty($conf->global->PDF_USE_1A)) $pdfa=true;		// PDF1/A
134
+
135
+    if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
136
+    else $pdf = new TCPDF($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
137
+
138
+    // Protection and encryption of pdf
139
+    if (! empty($conf->global->PDF_SECURITY_ENCRYPTION))
140
+    {
141
+        /* Permission supported by TCPDF
142 142
 		- print : Print the document;
143 143
 		- modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';
144 144
 		- copy : Copy or otherwise extract text and graphics from the document;
@@ -150,26 +150,26 @@  discard block
 block discarded – undo
150 150
 		- owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.
151 151
 		*/
152 152
 
153
-		// For TCPDF, we specify permission we want to block
154
-		$pdfrights = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS, true):array('modify','copy')); // Json format in llx_const
153
+        // For TCPDF, we specify permission we want to block
154
+        $pdfrights = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS, true):array('modify','copy')); // Json format in llx_const
155 155
 
156
-		// Password for the end user
157
-		$pdfuserpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_USERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_USERPASS:'');
156
+        // Password for the end user
157
+        $pdfuserpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_USERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_USERPASS:'');
158 158
 
159
-		// Password of the owner, created randomly if not defined
160
-		$pdfownerpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS:null);
159
+        // Password of the owner, created randomly if not defined
160
+        $pdfownerpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS:null);
161 161
 
162
-		// For encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit
163
-		$encstrength = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH)?$conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH:0);
162
+        // For encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit
163
+        $encstrength = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH)?$conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH:0);
164 164
 
165
-		// Array of recipients containing public-key certificates ('c') and permissions ('p').
166
-		// For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
167
-		$pubkeys = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS, true):null); // Json format in llx_const
165
+        // Array of recipients containing public-key certificates ('c') and permissions ('p').
166
+        // For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
167
+        $pubkeys = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS, true):null); // Json format in llx_const
168 168
 
169
-		$pdf->SetProtection($pdfrights,$pdfuserpass,$pdfownerpass,$encstrength,$pubkeys);
170
-	}
169
+        $pdf->SetProtection($pdfrights,$pdfuserpass,$pdfownerpass,$encstrength,$pubkeys);
170
+    }
171 171
 
172
-	return $pdf;
172
+    return $pdf;
173 173
 }
174 174
 
175 175
 /**
@@ -181,15 +181,15 @@  discard block
 block discarded – undo
181 181
  */
182 182
 function pdf_getEncryption(&$pdf, $pathoffile)
183 183
 {
184
-	$isencrypted = false;
184
+    $isencrypted = false;
185 185
 
186
-	$pdfparser = $pdf->_getPdfParser($pathoffile);
187
-	$data = $pdfparser->getParsedData();
188
-	if (isset($data[0]['trailer'][1]['/Encrypt'])) {
189
-		$isencrypted = true;
190
-	}
186
+    $pdfparser = $pdf->_getPdfParser($pathoffile);
187
+    $data = $pdfparser->getParsedData();
188
+    if (isset($data[0]['trailer'][1]['/Encrypt'])) {
189
+        $isencrypted = true;
190
+    }
191 191
 
192
-	return $isencrypted;
192
+    return $isencrypted;
193 193
 }
194 194
 
195 195
 /**
@@ -200,19 +200,19 @@  discard block
 block discarded – undo
200 200
  */
201 201
 function pdf_getPDFFont($outputlangs)
202 202
 {
203
-	global $conf;
204
-
205
-	if (! empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT;
206
-
207
-	$font='Helvetica'; // By default, for FPDI, or ISO language on TCPDF
208
-	if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
209
-	{
210
-		if ($outputlangs->trans('FONTFORPDF')!='FONTFORPDF')
211
-		{
212
-			$font=$outputlangs->trans('FONTFORPDF');
213
-		}
214
-	}
215
-	return $font;
203
+    global $conf;
204
+
205
+    if (! empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT;
206
+
207
+    $font='Helvetica'; // By default, for FPDI, or ISO language on TCPDF
208
+    if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
209
+    {
210
+        if ($outputlangs->trans('FONTFORPDF')!='FONTFORPDF')
211
+        {
212
+            $font=$outputlangs->trans('FONTFORPDF');
213
+        }
214
+    }
215
+    return $font;
216 216
 }
217 217
 
218 218
 /**
@@ -223,15 +223,15 @@  discard block
 block discarded – undo
223 223
  */
224 224
 function pdf_getPDFFontSize($outputlangs)
225 225
 {
226
-	$size=10;                   // By default, for FPDI or ISO language on TCPDF
227
-	if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
228
-	{
229
-		if ($outputlangs->trans('FONTSIZEFORPDF')!='FONTSIZEFORPDF')
230
-		{
231
-			$size = (int) $outputlangs->trans('FONTSIZEFORPDF');
232
-		}
233
-	}
234
-	return $size;
226
+    $size=10;                   // By default, for FPDI or ISO language on TCPDF
227
+    if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
228
+    {
229
+        if ($outputlangs->trans('FONTSIZEFORPDF')!='FONTSIZEFORPDF')
230
+        {
231
+            $size = (int) $outputlangs->trans('FONTSIZEFORPDF');
232
+        }
233
+    }
234
+    return $size;
235 235
 }
236 236
 
237 237
 
@@ -244,18 +244,18 @@  discard block
 block discarded – undo
244 244
  */
245 245
 function pdf_getHeightForLogo($logo, $url = false)
246 246
 {
247
-	global $conf;
248
-	$height=(empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT)?22:$conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT);
249
-	$maxwidth=130;
250
-	include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
251
-	$tmp=dol_getImageSize($logo, $url);
252
-	if ($tmp['height'])
253
-	{
254
-		$width=round($height*$tmp['width']/$tmp['height']);
255
-		if ($width > $maxwidth) $height=$height*$maxwidth/$width;
256
-	}
257
-	//print $tmp['width'].' '.$tmp['height'].' '.$width; exit;
258
-	return $height;
247
+    global $conf;
248
+    $height=(empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT)?22:$conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT);
249
+    $maxwidth=130;
250
+    include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
251
+    $tmp=dol_getImageSize($logo, $url);
252
+    if ($tmp['height'])
253
+    {
254
+        $width=round($height*$tmp['width']/$tmp['height']);
255
+        if ($width > $maxwidth) $height=$height*$maxwidth/$width;
256
+    }
257
+    //print $tmp['width'].' '.$tmp['height'].' '.$width; exit;
258
+    return $height;
259 259
 }
260 260
 
261 261
 /**
@@ -287,22 +287,22 @@  discard block
 block discarded – undo
287 287
     else
288 288
     {
289 289
         for ($page=$start_page; $page <= $end_page; ++$page) {
290
-        	$pdf->setPage($page);
291
-        	$tmpm=$pdf->getMargins();
292
-        	$tMargin = $tmpm['top'];
293
-        	if ($page == $start_page) {
294
-        		// first page
295
-        		$height = $pdf->getPageHeight() - $start_y - $pdf->getBreakMargin();
296
-        	} elseif ($page == $end_page) {
297
-        		// last page
298
-        		$height = $end_y - $tMargin;
299
-        	} else {
300
-        		$height = $pdf->getPageHeight() - $tMargin - $pdf->getBreakMargin();
301
-        	}
290
+            $pdf->setPage($page);
291
+            $tmpm=$pdf->getMargins();
292
+            $tMargin = $tmpm['top'];
293
+            if ($page == $start_page) {
294
+                // first page
295
+                $height = $pdf->getPageHeight() - $start_y - $pdf->getBreakMargin();
296
+            } elseif ($page == $end_page) {
297
+                // last page
298
+                $height = $end_y - $tMargin;
299
+            } else {
300
+                $height = $pdf->getPageHeight() - $tMargin - $pdf->getBreakMargin();
301
+            }
302 302
         }
303
-	}
304
-	// restore previous object
305
-	$pdf = $pdf->rollbackTransaction();
303
+    }
304
+    // restore previous object
305
+    $pdf = $pdf->rollbackTransaction();
306 306
 
307 307
     return $height;
308 308
 }
@@ -320,21 +320,21 @@  discard block
 block discarded – undo
320 320
 {
321 321
     global $conf;
322 322
 
323
-	// Recipient name
324
-	$socname = '';
325
-
326
-	if ($thirdparty instanceof Societe) {
327
-		$socname .= $thirdparty->name;
328
-		if (($includealias || ! empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) {
329
-		    $socname .= "\n".$thirdparty->name_alias;
330
-		}
331
-	} elseif ($thirdparty instanceof Contact) {
332
-		$socname = $thirdparty->socname;
333
-	} else {
334
-		throw new InvalidArgumentException('Parameter 1 $thirdparty is not a Societe nor Contact');
335
-	}
336
-
337
-	return $outputlangs->convToOutputCharset($socname);
323
+    // Recipient name
324
+    $socname = '';
325
+
326
+    if ($thirdparty instanceof Societe) {
327
+        $socname .= $thirdparty->name;
328
+        if (($includealias || ! empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) {
329
+            $socname .= "\n".$thirdparty->name_alias;
330
+        }
331
+    } elseif ($thirdparty instanceof Contact) {
332
+        $socname = $thirdparty->socname;
333
+    } else {
334
+        throw new InvalidArgumentException('Parameter 1 $thirdparty is not a Societe nor Contact');
335
+    }
336
+
337
+    return $outputlangs->convToOutputCharset($socname);
338 338
 }
339 339
 
340 340
 
@@ -352,240 +352,240 @@  discard block
 block discarded – undo
352 352
  */
353 353
 function pdf_build_address($outputlangs,$sourcecompany,$targetcompany='',$targetcontact='',$usecontact=0,$mode='source',$object=null)
354 354
 {
355
-	global $conf, $hookmanager;
356
-
357
-	if ($mode == 'source' && ! is_object($sourcecompany)) return -1;
358
-	if ($mode == 'target' && ! is_object($targetcompany)) return -1;
359
-
360
-	if (! empty($sourcecompany->state_id) && empty($sourcecompany->departement)) $sourcecompany->departement=getState($sourcecompany->state_id); //TODO deprecated
361
-	if (! empty($sourcecompany->state_id) && empty($sourcecompany->state))       $sourcecompany->state=getState($sourcecompany->state_id);
362
-	if (! empty($sourcecompany->state_id) && !isset($sourcecompany->departement_id))   $sourcecompany->departement_id=getState($sourcecompany->state_id,'2');
363
-	if (! empty($targetcompany->state_id) && empty($targetcompany->departement)) $targetcompany->departement=getState($targetcompany->state_id); //TODO deprecated
364
-	if (! empty($targetcompany->state_id) && empty($targetcompany->state))       $targetcompany->state=getState($targetcompany->state_id);
365
-	if (! empty($targetcompany->state_id) && !isset($targetcompany->departement_id))   $targetcompany->departement_id=getState($targetcompany->state_id,'2');
366
-
367
-	$reshook=0;
368
-	$stringaddress = '';
369
-	if (is_object($hookmanager))
370
-	{
371
-		$parameters = array('sourcecompany'=>&$sourcecompany,'targetcompany'=>&$targetcompany,'targetcontact'=>$targetcontact,'outputlangs'=>$outputlangs,'mode'=>$mode,'usecontact'=>$usecontact);
372
-		$action='';
373
-		$reshook = $hookmanager->executeHooks('pdf_build_address',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
374
-		$stringaddress.=$hookmanager->resPrint;
375
-	}
376
-	if (empty($reshook))
377
-	{
378
-    	if ($mode == 'source')
379
-    	{
380
-    		$withCountry = 0;
381
-    		if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1;
382
-
383
-    		$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n";
384
-
385
-    		if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS))
386
-    		{
387
-    			// Phone
388
-    			if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
389
-    			// Fax
390
-    			if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
391
-    			// EMail
392
-    			if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
393
-    			// Web
394
-    			if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
395
-    		}
396
-    		// Intra VAT
397
-    		if (! empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS))
398
-    		{
399
-    			if ($sourcecompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
400
-    		}
401
-    		// Professionnal Ids
402
-    		if (! empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof1))
403
-    		{
404
-    			$tmp=$outputlangs->transcountrynoentities("ProfId1",$sourcecompany->country_code);
405
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
406
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1);
407
-    		}
408
-    		if (! empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof2))
409
-    		{
410
-    			$tmp=$outputlangs->transcountrynoentities("ProfId2",$sourcecompany->country_code);
411
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
412
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2);
413
-    		}
414
-    		if (! empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof3))
415
-    		{
416
-    			$tmp=$outputlangs->transcountrynoentities("ProfId3",$sourcecompany->country_code);
417
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
418
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3);
419
-    		}
420
-    		if (! empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof4))
421
-    		{
422
-    			$tmp=$outputlangs->transcountrynoentities("ProfId4",$sourcecompany->country_code);
423
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
424
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4);
425
-    		}
426
-    		if (! empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof5))
427
-    		{
428
-    			$tmp=$outputlangs->transcountrynoentities("ProfId5",$sourcecompany->country_code);
429
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
430
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5);
431
-    		}
432
-    		if (! empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof6))
433
-    		{
434
-    			$tmp=$outputlangs->transcountrynoentities("ProfId6",$sourcecompany->country_code);
435
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
436
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6);
437
-    		}
438
-    	}
439
-
440
-    	if ($mode == 'target' || preg_match('/targetwithdetails/',$mode))
441
-    	{
442
-    		if ($usecontact)
443
-    		{
444
-    			$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs,1));
445
-
446
-    			if (!empty($targetcontact->address)) {
447
-    				$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcontact));
448
-    			} else {
449
-    				$companytouseforaddress = $targetcompany;
450
-
451
-					// Contact on a thirdparty that is a different thirdparty than the thirdparty of object
452
-					if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id)
453
-					{
454
-						$targetcontact->fetch_thirdparty();
455
-						$companytouseforaddress = $targetcontact->thirdparty;
456
-					}
457
-
458
-					$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress));
459
-				}
460
-    			// Country
461
-    			if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) {
462
-    				$stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code));
463
-    			}
464
-    			else if (empty($targetcontact->country_code) && !empty($targetcompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
465
-    				$stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
466
-    			}
467
-
468
-    			if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
469
-    			{
470
-    				// Phone
471
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
472
-    			    {
473
-        				if (! empty($targetcontact->phone_pro) || ! empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
474
-        				if (! empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
475
-        				if (! empty($targetcontact->phone_pro) && ! empty($targetcontact->phone_mobile)) $stringaddress .= " / ";
476
-        				if (! empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
477
-    			    }
478
-    				// Fax
479
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
480
-    			    {
355
+    global $conf, $hookmanager;
356
+
357
+    if ($mode == 'source' && ! is_object($sourcecompany)) return -1;
358
+    if ($mode == 'target' && ! is_object($targetcompany)) return -1;
359
+
360
+    if (! empty($sourcecompany->state_id) && empty($sourcecompany->departement)) $sourcecompany->departement=getState($sourcecompany->state_id); //TODO deprecated
361
+    if (! empty($sourcecompany->state_id) && empty($sourcecompany->state))       $sourcecompany->state=getState($sourcecompany->state_id);
362
+    if (! empty($sourcecompany->state_id) && !isset($sourcecompany->departement_id))   $sourcecompany->departement_id=getState($sourcecompany->state_id,'2');
363
+    if (! empty($targetcompany->state_id) && empty($targetcompany->departement)) $targetcompany->departement=getState($targetcompany->state_id); //TODO deprecated
364
+    if (! empty($targetcompany->state_id) && empty($targetcompany->state))       $targetcompany->state=getState($targetcompany->state_id);
365
+    if (! empty($targetcompany->state_id) && !isset($targetcompany->departement_id))   $targetcompany->departement_id=getState($targetcompany->state_id,'2');
366
+
367
+    $reshook=0;
368
+    $stringaddress = '';
369
+    if (is_object($hookmanager))
370
+    {
371
+        $parameters = array('sourcecompany'=>&$sourcecompany,'targetcompany'=>&$targetcompany,'targetcontact'=>$targetcontact,'outputlangs'=>$outputlangs,'mode'=>$mode,'usecontact'=>$usecontact);
372
+        $action='';
373
+        $reshook = $hookmanager->executeHooks('pdf_build_address',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
374
+        $stringaddress.=$hookmanager->resPrint;
375
+    }
376
+    if (empty($reshook))
377
+    {
378
+        if ($mode == 'source')
379
+        {
380
+            $withCountry = 0;
381
+            if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1;
382
+
383
+            $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n";
384
+
385
+            if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS))
386
+            {
387
+                // Phone
388
+                if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
389
+                // Fax
390
+                if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
391
+                // EMail
392
+                if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
393
+                // Web
394
+                if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
395
+            }
396
+            // Intra VAT
397
+            if (! empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS))
398
+            {
399
+                if ($sourcecompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
400
+            }
401
+            // Professionnal Ids
402
+            if (! empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof1))
403
+            {
404
+                $tmp=$outputlangs->transcountrynoentities("ProfId1",$sourcecompany->country_code);
405
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
406
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1);
407
+            }
408
+            if (! empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof2))
409
+            {
410
+                $tmp=$outputlangs->transcountrynoentities("ProfId2",$sourcecompany->country_code);
411
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
412
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2);
413
+            }
414
+            if (! empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof3))
415
+            {
416
+                $tmp=$outputlangs->transcountrynoentities("ProfId3",$sourcecompany->country_code);
417
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
418
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3);
419
+            }
420
+            if (! empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof4))
421
+            {
422
+                $tmp=$outputlangs->transcountrynoentities("ProfId4",$sourcecompany->country_code);
423
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
424
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4);
425
+            }
426
+            if (! empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof5))
427
+            {
428
+                $tmp=$outputlangs->transcountrynoentities("ProfId5",$sourcecompany->country_code);
429
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
430
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5);
431
+            }
432
+            if (! empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof6))
433
+            {
434
+                $tmp=$outputlangs->transcountrynoentities("ProfId6",$sourcecompany->country_code);
435
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
436
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6);
437
+            }
438
+        }
439
+
440
+        if ($mode == 'target' || preg_match('/targetwithdetails/',$mode))
441
+        {
442
+            if ($usecontact)
443
+            {
444
+                $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs,1));
445
+
446
+                if (!empty($targetcontact->address)) {
447
+                    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcontact));
448
+                } else {
449
+                    $companytouseforaddress = $targetcompany;
450
+
451
+                    // Contact on a thirdparty that is a different thirdparty than the thirdparty of object
452
+                    if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id)
453
+                    {
454
+                        $targetcontact->fetch_thirdparty();
455
+                        $companytouseforaddress = $targetcontact->thirdparty;
456
+                    }
457
+
458
+                    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress));
459
+                }
460
+                // Country
461
+                if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) {
462
+                    $stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code));
463
+                }
464
+                else if (empty($targetcontact->country_code) && !empty($targetcompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
465
+                    $stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
466
+                }
467
+
468
+                if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
469
+                {
470
+                    // Phone
471
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
472
+                    {
473
+                        if (! empty($targetcontact->phone_pro) || ! empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
474
+                        if (! empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
475
+                        if (! empty($targetcontact->phone_pro) && ! empty($targetcontact->phone_mobile)) $stringaddress .= " / ";
476
+                        if (! empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
477
+                    }
478
+                    // Fax
479
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
480
+                    {
481 481
                         if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
482
-    			    }
483
-    				// EMail
484
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
485
-    			    {
482
+                    }
483
+                    // EMail
484
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
485
+                    {
486 486
                         if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
487
-    			    }
488
-    				// Web
489
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
490
-    			    {
487
+                    }
488
+                    // Web
489
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
490
+                    {
491 491
                         if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
492
-    			    }
493
-    			}
494
-    		}
495
-    		else
496
-    		{
497
-    			$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcompany));
498
-    			// Country
499
-    			if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
500
-
501
-    			if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
502
-    			{
503
-    				// Phone
504
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
505
-    			    {
506
-    			    	if (! empty($targetcompany->phone) || ! empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
507
-	    				if (! empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
508
-    					if (! empty($targetcompany->phone) && ! empty($targetcompany->phone_mobile)) $stringaddress .= " / ";
509
-    					if (! empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
510
-    			    }
511
-    				// Fax
512
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
513
-    			    {
514
-    			    	if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
515
-    			    }
516
-    				// EMail
517
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
518
-    			    {
519
-    			    	if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
520
-    			    }
521
-    				// Web
522
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
523
-    			    {
524
-    			    	if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
525
-    			    }
526
-    			}
527
-    		}
528
-
529
-    		// Intra VAT
530
-    		if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS))
531
-    		{
532
-    			if ($targetcompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
533
-    		}
534
-
535
-    		// Professionnal Ids
536
-    		if (! empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && ! empty($targetcompany->idprof1))
537
-    		{
538
-    			$tmp=$outputlangs->transcountrynoentities("ProfId1",$targetcompany->country_code);
539
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
540
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1);
541
-    		}
542
-    		if (! empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && ! empty($targetcompany->idprof2))
543
-    		{
544
-    			$tmp=$outputlangs->transcountrynoentities("ProfId2",$targetcompany->country_code);
545
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
546
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2);
547
-    		}
548
-    		if (! empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && ! empty($targetcompany->idprof3))
549
-    		{
550
-    			$tmp=$outputlangs->transcountrynoentities("ProfId3",$targetcompany->country_code);
551
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
552
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3);
553
-    		}
554
-    		if (! empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && ! empty($targetcompany->idprof4))
555
-    		{
556
-    			$tmp=$outputlangs->transcountrynoentities("ProfId4",$targetcompany->country_code);
557
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
558
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4);
559
-    		}
560
-    		if (! empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && ! empty($targetcompany->idprof5))
561
-    		{
562
-    		    $tmp=$outputlangs->transcountrynoentities("ProfId5",$targetcompany->country_code);
563
-    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
564
-    		    $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5);
565
-    		}
566
-    		if (! empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && ! empty($targetcompany->idprof6))
567
-    		{
568
-    		    $tmp=$outputlangs->transcountrynoentities("ProfId6",$targetcompany->country_code);
569
-    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
570
-    		    $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6);
571
-    		}
572
-
573
-    		// Public note
574
-    		if (! empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS))
575
-    		{
576
-    		    if ($mode == 'source' && ! empty($sourcecompany->note_public))
577
-        		{
578
-        		    $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($sourcecompany->note_public);
579
-        		}
580
-        		if (($mode == 'target' || preg_match('/targetwithdetails/',$mode)) && ! empty($targetcompany->note_public))
581
-        		{
582
-        		    $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($targetcompany->note_public);
583
-        		}
584
-    		}
585
-    	}
586
-	}
587
-
588
-	return $stringaddress;
492
+                    }
493
+                }
494
+            }
495
+            else
496
+            {
497
+                $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcompany));
498
+                // Country
499
+                if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
500
+
501
+                if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
502
+                {
503
+                    // Phone
504
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
505
+                    {
506
+                        if (! empty($targetcompany->phone) || ! empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
507
+                        if (! empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
508
+                        if (! empty($targetcompany->phone) && ! empty($targetcompany->phone_mobile)) $stringaddress .= " / ";
509
+                        if (! empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
510
+                    }
511
+                    // Fax
512
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
513
+                    {
514
+                        if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
515
+                    }
516
+                    // EMail
517
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
518
+                    {
519
+                        if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
520
+                    }
521
+                    // Web
522
+                    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
523
+                    {
524
+                        if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
525
+                    }
526
+                }
527
+            }
528
+
529
+            // Intra VAT
530
+            if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS))
531
+            {
532
+                if ($targetcompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
533
+            }
534
+
535
+            // Professionnal Ids
536
+            if (! empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && ! empty($targetcompany->idprof1))
537
+            {
538
+                $tmp=$outputlangs->transcountrynoentities("ProfId1",$targetcompany->country_code);
539
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
540
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1);
541
+            }
542
+            if (! empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && ! empty($targetcompany->idprof2))
543
+            {
544
+                $tmp=$outputlangs->transcountrynoentities("ProfId2",$targetcompany->country_code);
545
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
546
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2);
547
+            }
548
+            if (! empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && ! empty($targetcompany->idprof3))
549
+            {
550
+                $tmp=$outputlangs->transcountrynoentities("ProfId3",$targetcompany->country_code);
551
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
552
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3);
553
+            }
554
+            if (! empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && ! empty($targetcompany->idprof4))
555
+            {
556
+                $tmp=$outputlangs->transcountrynoentities("ProfId4",$targetcompany->country_code);
557
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
558
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4);
559
+            }
560
+            if (! empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && ! empty($targetcompany->idprof5))
561
+            {
562
+                $tmp=$outputlangs->transcountrynoentities("ProfId5",$targetcompany->country_code);
563
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
564
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5);
565
+            }
566
+            if (! empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && ! empty($targetcompany->idprof6))
567
+            {
568
+                $tmp=$outputlangs->transcountrynoentities("ProfId6",$targetcompany->country_code);
569
+                if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
570
+                $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6);
571
+            }
572
+
573
+            // Public note
574
+            if (! empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS))
575
+            {
576
+                if ($mode == 'source' && ! empty($sourcecompany->note_public))
577
+                {
578
+                    $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($sourcecompany->note_public);
579
+                }
580
+                if (($mode == 'target' || preg_match('/targetwithdetails/',$mode)) && ! empty($targetcompany->note_public))
581
+                {
582
+                    $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($targetcompany->note_public);
583
+                }
584
+            }
585
+        }
586
+    }
587
+
588
+    return $stringaddress;
589 589
 }
590 590
 
591 591
 
@@ -599,15 +599,15 @@  discard block
 block discarded – undo
599 599
  */
600 600
 function pdf_pagehead(&$pdf,$outputlangs,$page_height)
601 601
 {
602
-	global $conf;
603
-
604
-	// Add a background image on document
605
-	if (! empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF))		// Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
606
-	{
607
-		$pdf->SetAutoPageBreak(0,0);	// Disable auto pagebreak before adding image
608
-		$pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_X:0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y:0), 0, $page_height);
609
-		$pdf->SetAutoPageBreak(1,0);	// Restore pagebreak
610
-	}
602
+    global $conf;
603
+
604
+    // Add a background image on document
605
+    if (! empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF))		// Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
606
+    {
607
+        $pdf->SetAutoPageBreak(0,0);	// Disable auto pagebreak before adding image
608
+        $pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_X:0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y:0), 0, $page_height);
609
+        $pdf->SetAutoPageBreak(1,0);	// Restore pagebreak
610
+    }
611 611
 }
612 612
 
613 613
 
@@ -642,38 +642,38 @@  discard block
 block discarded – undo
642 642
  */
643 643
 function pdf_watermark(&$pdf, $outputlangs, $h, $w, $unit, $text)
644 644
 {
645
-	global $langs, $mysoc, $user;
646
-
647
-	// Print Draft Watermark
648
-	if ($unit=='pt') $k=1;
649
-	elseif ($unit=='mm') $k=72/25.4;
650
-	elseif ($unit=='cm') $k=72/2.54;
651
-	elseif ($unit=='in') $k=72;
652
-
653
-	// Make substitution
654
-	$substitutionarray=pdf_getSubstitutionArray($outputlangs, null, null);
655
-	complete_substitutions_array($substitutionarray, $outputlangs, null);
656
-	$text=make_substitutions($text, $substitutionarray, $outputlangs);
657
-	$text=$outputlangs->convToOutputCharset($text);
658
-
659
-	$savx=$pdf->getX(); $savy=$pdf->getY();
660
-
661
-	$watermark_angle=atan($h/$w)/2;
662
-	$watermark_x_pos=0;
663
-	$watermark_y_pos=$h/3;
664
-	$watermark_x=$w/2;
665
-	$watermark_y=$h/3;
666
-	$pdf->SetFont('','B',40);
667
-	$pdf->SetTextColor(255,192,203);
668
-	//rotate
669
-	$pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',cos($watermark_angle),sin($watermark_angle),-sin($watermark_angle),cos($watermark_angle),$watermark_x*$k,($h-$watermark_y)*$k,-$watermark_x*$k,-($h-$watermark_y)*$k));
670
-	//print watermark
671
-	$pdf->SetXY($watermark_x_pos,$watermark_y_pos);
672
-	$pdf->Cell($w-20,25,$outputlangs->convToOutputCharset($text),"",2,"C",0);
673
-	//antirotate
674
-	$pdf->_out('Q');
675
-
676
-	$pdf->SetXY($savx,$savy);
645
+    global $langs, $mysoc, $user;
646
+
647
+    // Print Draft Watermark
648
+    if ($unit=='pt') $k=1;
649
+    elseif ($unit=='mm') $k=72/25.4;
650
+    elseif ($unit=='cm') $k=72/2.54;
651
+    elseif ($unit=='in') $k=72;
652
+
653
+    // Make substitution
654
+    $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, null);
655
+    complete_substitutions_array($substitutionarray, $outputlangs, null);
656
+    $text=make_substitutions($text, $substitutionarray, $outputlangs);
657
+    $text=$outputlangs->convToOutputCharset($text);
658
+
659
+    $savx=$pdf->getX(); $savy=$pdf->getY();
660
+
661
+    $watermark_angle=atan($h/$w)/2;
662
+    $watermark_x_pos=0;
663
+    $watermark_y_pos=$h/3;
664
+    $watermark_x=$w/2;
665
+    $watermark_y=$h/3;
666
+    $pdf->SetFont('','B',40);
667
+    $pdf->SetTextColor(255,192,203);
668
+    //rotate
669
+    $pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',cos($watermark_angle),sin($watermark_angle),-sin($watermark_angle),cos($watermark_angle),$watermark_x*$k,($h-$watermark_y)*$k,-$watermark_x*$k,-($h-$watermark_y)*$k));
670
+    //print watermark
671
+    $pdf->SetXY($watermark_x_pos,$watermark_y_pos);
672
+    $pdf->Cell($w-20,25,$outputlangs->convToOutputCharset($text),"",2,"C",0);
673
+    //antirotate
674
+    $pdf->_out('Q');
675
+
676
+    $pdf->SetXY($savx,$savy);
677 677
 }
678 678
 
679 679
 
@@ -691,167 +691,167 @@  discard block
 block discarded – undo
691 691
  */
692 692
 function pdf_bank(&$pdf,$outputlangs,$curx,$cury,$account,$onlynumber=0,$default_font_size=10)
693 693
 {
694
-	global $mysoc, $conf;
695
-
696
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php';
697
-
698
-	$diffsizetitle=(empty($conf->global->PDF_DIFFSIZE_TITLE)?3:$conf->global->PDF_DIFFSIZE_TITLE);
699
-	$diffsizecontent=(empty($conf->global->PDF_DIFFSIZE_CONTENT)?4:$conf->global->PDF_DIFFSIZE_CONTENT);
700
-	$pdf->SetXY($curx, $cury);
701
-
702
-	if (empty($onlynumber))
703
-	{
704
-		$pdf->SetFont('','B',$default_font_size - $diffsizetitle);
705
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0);
706
-		$cury+=4;
707
-	}
708
-
709
-	$outputlangs->load("banks");
710
-
711
-	// Use correct name of bank id according to country
712
-	$bickey="BICNumber";
713
-	if ($account->getCountryCode() == 'IN') $bickey="SWIFT";
714
-
715
-	// Get format of bank account according to its country
716
-	$usedetailedbban=$account->useDetailedBBAN();
717
-
718
-	//$onlynumber=0; $usedetailedbban=1; // For tests
719
-	if ($usedetailedbban)
720
-	{
721
-		$savcurx=$curx;
722
-
723
-		if (empty($onlynumber))
724
-		{
725
-			$pdf->SetFont('','',$default_font_size - $diffsizecontent);
726
-			$pdf->SetXY($curx, $cury);
727
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
728
-			$cury+=3;
729
-		}
730
-
731
-		if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN))    // Note that some countries still need bank number, BIC/IBAN not enougth for them
732
-		{
733
-		    // Note:
734
-		    // bank = code_banque (FR), sort code (GB, IR. Example: 12-34-56)
735
-		    // desk = code guichet (FR), used only when $usedetailedbban = 1
736
-		    // number = account number
737
-		    // key = check control key used only when $usedetailedbban = 1
738
-    		if (empty($onlynumber)) $pdf->line($curx+1, $cury+1, $curx+1, $cury+6);
739
-
740
-
741
-			foreach ($account->getFieldsToShow() as $val)
742
-			{
743
-				$pdf->SetXY($curx, $cury+4);
744
-				$pdf->SetFont('','',$default_font_size - 3);
745
-
746
-				if ($val == 'BankCode') {
747
-					// Bank code
748
-					$tmplength = 18;
749
-					$content = $account->code_banque;
750
-				} elseif ($val == 'DeskCode') {
751
-					// Desk
752
-					$tmplength = 18;
753
-					$content = $account->code_guichet;
754
-				} elseif ($val == 'BankAccountNumber') {
755
-					// Number
756
-					$tmplength = 24;
757
-					$content = $account->number;
758
-				} elseif ($val == 'BankAccountNumberKey') {
759
-					// Key
760
-					$tmplength = 15;
761
-					$content = $account->cle_rib;
762
-				}elseif ($val == 'IBAN' || $val == 'BIC') {
763
-					// Key
764
-					$tmplength = 0;
765
-					$content = '';
766
-				} else {
767
-					dol_print_error($account->db, 'Unexpected value for getFieldsToShow: '.$val);
768
-					break;
769
-				}
770
-
771
-				$pdf->MultiCell($tmplength, 3, $outputlangs->convToOutputCharset($content), 0, 'C', 0);
772
-				$pdf->SetXY($curx, $cury + 1);
773
-				$curx += $tmplength;
774
-				$pdf->SetFont('', 'B', $default_font_size - $diffsizecontent);
775
-				$pdf->MultiCell($tmplength, 3, $outputlangs->transnoentities($val), 0, 'C', 0);
776
-				if (empty($onlynumber)) {
777
-					$pdf->line($curx, $cury + 1, $curx, $cury + 7);
778
-				}
779
-    		}
780
-
781
-    		$curx=$savcurx;
782
-    		$cury+=8;
783
-		}
784
-	}
785
-	else
786
-	{
787
-		$pdf->SetFont('','B',$default_font_size - $diffsizecontent);
788
-		$pdf->SetXY($curx, $cury);
789
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
790
-		$cury+=3;
791
-
792
-		$pdf->SetFont('','B',$default_font_size - $diffsizecontent);
793
-		$pdf->SetXY($curx, $cury);
794
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': ' . $outputlangs->convToOutputCharset($account->number), 0, 'L', 0);
795
-		$cury+=3;
796
-
797
-		if ($diffsizecontent <= 2) $cury+=1;
798
-	}
799
-
800
-	$pdf->SetFont('','',$default_font_size - $diffsizecontent);
801
-
802
-	if (empty($onlynumber) && ! empty($account->domiciliation))
803
-	{
804
-		$pdf->SetXY($curx, $cury);
805
-		$val=$outputlangs->transnoentities("Residence").': ' . $outputlangs->convToOutputCharset($account->domiciliation);
806
-		$pdf->MultiCell(100, 3, $val, 0, 'L', 0);
807
-		//$nboflines=dol_nboflines_bis($val,120);
808
-		//$cury+=($nboflines*3)+2;
809
-		$tmpy=$pdf->getStringHeight(100, $val);
810
-		$cury+=$tmpy;
811
-	}
812
-
813
-	if (! empty($account->proprio))
814
-	{
815
-		$pdf->SetXY($curx, $cury);
816
-		$val=$outputlangs->transnoentities("BankAccountOwner").': ' . $outputlangs->convToOutputCharset($account->proprio);
817
-		$pdf->MultiCell(100, 3, $val, 0, 'L', 0);
818
-		$tmpy=$pdf->getStringHeight(100, $val);
819
-		$cury+=$tmpy;
820
-		$cur+=1;
821
-	}
822
-
823
-	else if (! $usedetailedbban) $cury+=1;
824
-
825
-	// Use correct name of bank id according to country
826
-	$ibankey = FormBank::getIBANLabel($account);
827
-
828
-	if (! empty($account->iban))
829
-	{
830
-		//Remove whitespaces to ensure we are dealing with the format we expect
831
-		$ibanDisplay_temp = str_replace(' ', '', $outputlangs->convToOutputCharset($account->iban));
832
-		$ibanDisplay = "";
833
-
834
-		$nbIbanDisplay_temp = dol_strlen($ibanDisplay_temp);
835
-		for ($i = 0; $i < $nbIbanDisplay_temp; $i++)
836
-		{
837
-			$ibanDisplay .= $ibanDisplay_temp[$i];
838
-			if($i%4 == 3 && $i > 0)	$ibanDisplay .= " ";
839
-		}
840
-
841
-		$pdf->SetFont('','B',$default_font_size - 3);
842
-		$pdf->SetXY($curx, $cury);
843
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities($ibankey).': ' . $ibanDisplay, 0, 'L', 0);
844
-		$cury+=3;
845
-	}
846
-
847
-	if (! empty($account->bic))
848
-	{
849
-		$pdf->SetFont('','B',$default_font_size - 3);
850
-		$pdf->SetXY($curx, $cury);
851
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': ' . $outputlangs->convToOutputCharset($account->bic), 0, 'L', 0);
852
-	}
853
-
854
-	return $pdf->getY();
694
+    global $mysoc, $conf;
695
+
696
+    require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php';
697
+
698
+    $diffsizetitle=(empty($conf->global->PDF_DIFFSIZE_TITLE)?3:$conf->global->PDF_DIFFSIZE_TITLE);
699
+    $diffsizecontent=(empty($conf->global->PDF_DIFFSIZE_CONTENT)?4:$conf->global->PDF_DIFFSIZE_CONTENT);
700
+    $pdf->SetXY($curx, $cury);
701
+
702
+    if (empty($onlynumber))
703
+    {
704
+        $pdf->SetFont('','B',$default_font_size - $diffsizetitle);
705
+        $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0);
706
+        $cury+=4;
707
+    }
708
+
709
+    $outputlangs->load("banks");
710
+
711
+    // Use correct name of bank id according to country
712
+    $bickey="BICNumber";
713
+    if ($account->getCountryCode() == 'IN') $bickey="SWIFT";
714
+
715
+    // Get format of bank account according to its country
716
+    $usedetailedbban=$account->useDetailedBBAN();
717
+
718
+    //$onlynumber=0; $usedetailedbban=1; // For tests
719
+    if ($usedetailedbban)
720
+    {
721
+        $savcurx=$curx;
722
+
723
+        if (empty($onlynumber))
724
+        {
725
+            $pdf->SetFont('','',$default_font_size - $diffsizecontent);
726
+            $pdf->SetXY($curx, $cury);
727
+            $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
728
+            $cury+=3;
729
+        }
730
+
731
+        if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN))    // Note that some countries still need bank number, BIC/IBAN not enougth for them
732
+        {
733
+            // Note:
734
+            // bank = code_banque (FR), sort code (GB, IR. Example: 12-34-56)
735
+            // desk = code guichet (FR), used only when $usedetailedbban = 1
736
+            // number = account number
737
+            // key = check control key used only when $usedetailedbban = 1
738
+            if (empty($onlynumber)) $pdf->line($curx+1, $cury+1, $curx+1, $cury+6);
739
+
740
+
741
+            foreach ($account->getFieldsToShow() as $val)
742
+            {
743
+                $pdf->SetXY($curx, $cury+4);
744
+                $pdf->SetFont('','',$default_font_size - 3);
745
+
746
+                if ($val == 'BankCode') {
747
+                    // Bank code
748
+                    $tmplength = 18;
749
+                    $content = $account->code_banque;
750
+                } elseif ($val == 'DeskCode') {
751
+                    // Desk
752
+                    $tmplength = 18;
753
+                    $content = $account->code_guichet;
754
+                } elseif ($val == 'BankAccountNumber') {
755
+                    // Number
756
+                    $tmplength = 24;
757
+                    $content = $account->number;
758
+                } elseif ($val == 'BankAccountNumberKey') {
759
+                    // Key
760
+                    $tmplength = 15;
761
+                    $content = $account->cle_rib;
762
+                }elseif ($val == 'IBAN' || $val == 'BIC') {
763
+                    // Key
764
+                    $tmplength = 0;
765
+                    $content = '';
766
+                } else {
767
+                    dol_print_error($account->db, 'Unexpected value for getFieldsToShow: '.$val);
768
+                    break;
769
+                }
770
+
771
+                $pdf->MultiCell($tmplength, 3, $outputlangs->convToOutputCharset($content), 0, 'C', 0);
772
+                $pdf->SetXY($curx, $cury + 1);
773
+                $curx += $tmplength;
774
+                $pdf->SetFont('', 'B', $default_font_size - $diffsizecontent);
775
+                $pdf->MultiCell($tmplength, 3, $outputlangs->transnoentities($val), 0, 'C', 0);
776
+                if (empty($onlynumber)) {
777
+                    $pdf->line($curx, $cury + 1, $curx, $cury + 7);
778
+                }
779
+            }
780
+
781
+            $curx=$savcurx;
782
+            $cury+=8;
783
+        }
784
+    }
785
+    else
786
+    {
787
+        $pdf->SetFont('','B',$default_font_size - $diffsizecontent);
788
+        $pdf->SetXY($curx, $cury);
789
+        $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
790
+        $cury+=3;
791
+
792
+        $pdf->SetFont('','B',$default_font_size - $diffsizecontent);
793
+        $pdf->SetXY($curx, $cury);
794
+        $pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': ' . $outputlangs->convToOutputCharset($account->number), 0, 'L', 0);
795
+        $cury+=3;
796
+
797
+        if ($diffsizecontent <= 2) $cury+=1;
798
+    }
799
+
800
+    $pdf->SetFont('','',$default_font_size - $diffsizecontent);
801
+
802
+    if (empty($onlynumber) && ! empty($account->domiciliation))
803
+    {
804
+        $pdf->SetXY($curx, $cury);
805
+        $val=$outputlangs->transnoentities("Residence").': ' . $outputlangs->convToOutputCharset($account->domiciliation);
806
+        $pdf->MultiCell(100, 3, $val, 0, 'L', 0);
807
+        //$nboflines=dol_nboflines_bis($val,120);
808
+        //$cury+=($nboflines*3)+2;
809
+        $tmpy=$pdf->getStringHeight(100, $val);
810
+        $cury+=$tmpy;
811
+    }
812
+
813
+    if (! empty($account->proprio))
814
+    {
815
+        $pdf->SetXY($curx, $cury);
816
+        $val=$outputlangs->transnoentities("BankAccountOwner").': ' . $outputlangs->convToOutputCharset($account->proprio);
817
+        $pdf->MultiCell(100, 3, $val, 0, 'L', 0);
818
+        $tmpy=$pdf->getStringHeight(100, $val);
819
+        $cury+=$tmpy;
820
+        $cur+=1;
821
+    }
822
+
823
+    else if (! $usedetailedbban) $cury+=1;
824
+
825
+    // Use correct name of bank id according to country
826
+    $ibankey = FormBank::getIBANLabel($account);
827
+
828
+    if (! empty($account->iban))
829
+    {
830
+        //Remove whitespaces to ensure we are dealing with the format we expect
831
+        $ibanDisplay_temp = str_replace(' ', '', $outputlangs->convToOutputCharset($account->iban));
832
+        $ibanDisplay = "";
833
+
834
+        $nbIbanDisplay_temp = dol_strlen($ibanDisplay_temp);
835
+        for ($i = 0; $i < $nbIbanDisplay_temp; $i++)
836
+        {
837
+            $ibanDisplay .= $ibanDisplay_temp[$i];
838
+            if($i%4 == 3 && $i > 0)	$ibanDisplay .= " ";
839
+        }
840
+
841
+        $pdf->SetFont('','B',$default_font_size - 3);
842
+        $pdf->SetXY($curx, $cury);
843
+        $pdf->MultiCell(100, 3, $outputlangs->transnoentities($ibankey).': ' . $ibanDisplay, 0, 'L', 0);
844
+        $cury+=3;
845
+    }
846
+
847
+    if (! empty($account->bic))
848
+    {
849
+        $pdf->SetFont('','B',$default_font_size - 3);
850
+        $pdf->SetXY($curx, $cury);
851
+        $pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': ' . $outputlangs->convToOutputCharset($account->bic), 0, 'L', 0);
852
+    }
853
+
854
+    return $pdf->getY();
855 855
 }
856 856
 
857 857
 /**
@@ -871,235 +871,235 @@  discard block
 block discarded – undo
871 871
  */
872 872
 function pdf_pagefoot(&$pdf,$outputlangs,$paramfreetext,$fromcompany,$marge_basse,$marge_gauche,$page_hauteur,$object,$showdetails=0,$hidefreetext=0)
873 873
 {
874
-	global $conf,$user,$mysoc;
875
-
876
-	$outputlangs->load("dict");
877
-	$line='';
878
-
879
-	$dims=$pdf->getPageDimensions();
880
-
881
-	// Line of free text
882
-	if (empty($hidefreetext) && ! empty($conf->global->$paramfreetext))
883
-	{
884
-		$substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object);
885
-		// More substitution keys
886
-		$substitutionarray['__FROM_NAME__']=$fromcompany->name;
887
-		$substitutionarray['__FROM_EMAIL__']=$fromcompany->email;
888
-		complete_substitutions_array($substitutionarray, $outputlangs, $object);
889
-		$newfreetext=make_substitutions($conf->global->$paramfreetext, $substitutionarray, $outputlangs);
890
-
891
-		// Make a change into HTML code to allow to include images from medias directory.
892
-		// <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
893
-		// become
894
-		// <img alt="" src="'.DOL_DATA_ROOT.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
895
-		$newfreetext=preg_replace('/(<img.*src=")[^\"]*viewimage\.php[^\"]*modulepart=medias[^\"]*file=([^\"]*)("[^\/]*\/>)/', '\1'.DOL_DATA_ROOT.'/medias/\2\3', $newfreetext);
896
-
897
-		$line.=$outputlangs->convToOutputCharset($newfreetext);
898
-	}
899
-
900
-	// First line of company infos
901
-	$line1=""; $line2=""; $line3=""; $line4="";
902
-
903
-		if ($showdetails == 1 || $showdetails == 3)
904
-	{
905
-		// Company name
906
-		if ($fromcompany->name)
907
-		{
908
-			$line1.=($line1?" - ":"").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name;
909
-		}
910
-		// Address
911
-		if ($fromcompany->address)
912
-		{
913
-			$line1.=($line1?" - ":"").str_replace("\n", ", ", $fromcompany->address);
914
-		}
915
-		// Zip code
916
-		if ($fromcompany->zip)
917
-		{
918
-			$line1.=($line1?" - ":"").$fromcompany->zip;
919
-		}
920
-		// Town
921
-		if ($fromcompany->town)
922
-		{
923
-			$line1.=($line1?" ":"").$fromcompany->town;
924
-		}
925
-		// Phone
926
-		if ($fromcompany->phone)
927
-		{
928
-			$line2.=($line2?" - ":"").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone;
929
-		}
930
-		// Fax
931
-		if ($fromcompany->fax)
932
-		{
933
-			$line2.=($line2?" - ":"").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax;
934
-		}
935
-
936
-		// URL
937
-		if ($fromcompany->url)
938
-		{
939
-			$line2.=($line2?" - ":"").$fromcompany->url;
940
-		}
941
-		// Email
942
-		if ($fromcompany->email)
943
-		{
944
-			$line2.=($line2?" - ":"").$fromcompany->email;
945
-		}
946
-	}
947
-	if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE'))
948
-	{
949
-		// Managers
950
-		if ($fromcompany->managers)
951
-		{
952
-			$line2.=($line2?" - ":"").$fromcompany->managers;
953
-		}
954
-	}
955
-
956
-	// Line 3 of company infos
957
-	// Juridical status
958
-	if ($fromcompany->forme_juridique_code)
959
-	{
960
-		$line3.=($line3?" - ":"").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code));
961
-	}
962
-	// Capital
963
-	if ($fromcompany->capital)
964
-	{
965
-		$tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string
966
-		if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
967
-		else $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",$tmpamounttoshow,$outputlangs);
968
-	}
969
-	// Prof Id 1
970
-	if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || ! $fromcompany->idprof2))
971
-	{
972
-		$field=$outputlangs->transcountrynoentities("ProfId1",$fromcompany->country_code);
973
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
974
-		$line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1);
975
-	}
976
-	// Prof Id 2
977
-	if ($fromcompany->idprof2)
978
-	{
979
-		$field=$outputlangs->transcountrynoentities("ProfId2",$fromcompany->country_code);
980
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
981
-		$line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2);
982
-	}
983
-
984
-	// Line 4 of company infos
985
-	// Prof Id 3
986
-	if ($fromcompany->idprof3)
987
-	{
988
-		$field=$outputlangs->transcountrynoentities("ProfId3",$fromcompany->country_code);
989
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
990
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3);
991
-	}
992
-	// Prof Id 4
993
-	if ($fromcompany->idprof4)
994
-	{
995
-		$field=$outputlangs->transcountrynoentities("ProfId4",$fromcompany->country_code);
996
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
997
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4);
998
-	}
999
-	// Prof Id 5
1000
-	if ($fromcompany->idprof5)
1001
-	{
1002
-		$field=$outputlangs->transcountrynoentities("ProfId5",$fromcompany->country_code);
1003
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1004
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5);
1005
-	}
1006
-	// Prof Id 6
1007
-	if ($fromcompany->idprof6)
1008
-	{
1009
-		$field=$outputlangs->transcountrynoentities("ProfId6",$fromcompany->country_code);
1010
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1011
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6);
1012
-	}
1013
-	// IntraCommunautary VAT
1014
-	if ($fromcompany->tva_intra != '')
1015
-	{
1016
-		$line4.=($line4?" - ":"").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra);
1017
-	}
1018
-
1019
-	$pdf->SetFont('','',7);
1020
-	$pdf->SetDrawColor(224,224,224);
1021
-
1022
-	// The start of the bottom of this page footer is positioned according to # of lines
1023
-	$freetextheight=0;
1024
-	if ($line)	// Free text
1025
-	{
1026
-		//$line="sample text<br>\nfd<strong>sf</strong>sdf<br>\nghfghg<br>";
1027
-	    if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
1028
-		{
1029
-			$width=20000; $align='L';	// By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
1030
-    		if (! empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) {
1031
-    			$width=200; $align='C';
1032
-    		}
1033
-		    $freetextheight=$pdf->getStringHeight($width,$line);
1034
-		}
1035
-		else
1036
-		{
874
+    global $conf,$user,$mysoc;
875
+
876
+    $outputlangs->load("dict");
877
+    $line='';
878
+
879
+    $dims=$pdf->getPageDimensions();
880
+
881
+    // Line of free text
882
+    if (empty($hidefreetext) && ! empty($conf->global->$paramfreetext))
883
+    {
884
+        $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object);
885
+        // More substitution keys
886
+        $substitutionarray['__FROM_NAME__']=$fromcompany->name;
887
+        $substitutionarray['__FROM_EMAIL__']=$fromcompany->email;
888
+        complete_substitutions_array($substitutionarray, $outputlangs, $object);
889
+        $newfreetext=make_substitutions($conf->global->$paramfreetext, $substitutionarray, $outputlangs);
890
+
891
+        // Make a change into HTML code to allow to include images from medias directory.
892
+        // <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
893
+        // become
894
+        // <img alt="" src="'.DOL_DATA_ROOT.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
895
+        $newfreetext=preg_replace('/(<img.*src=")[^\"]*viewimage\.php[^\"]*modulepart=medias[^\"]*file=([^\"]*)("[^\/]*\/>)/', '\1'.DOL_DATA_ROOT.'/medias/\2\3', $newfreetext);
896
+
897
+        $line.=$outputlangs->convToOutputCharset($newfreetext);
898
+    }
899
+
900
+    // First line of company infos
901
+    $line1=""; $line2=""; $line3=""; $line4="";
902
+
903
+        if ($showdetails == 1 || $showdetails == 3)
904
+    {
905
+        // Company name
906
+        if ($fromcompany->name)
907
+        {
908
+            $line1.=($line1?" - ":"").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name;
909
+        }
910
+        // Address
911
+        if ($fromcompany->address)
912
+        {
913
+            $line1.=($line1?" - ":"").str_replace("\n", ", ", $fromcompany->address);
914
+        }
915
+        // Zip code
916
+        if ($fromcompany->zip)
917
+        {
918
+            $line1.=($line1?" - ":"").$fromcompany->zip;
919
+        }
920
+        // Town
921
+        if ($fromcompany->town)
922
+        {
923
+            $line1.=($line1?" ":"").$fromcompany->town;
924
+        }
925
+        // Phone
926
+        if ($fromcompany->phone)
927
+        {
928
+            $line2.=($line2?" - ":"").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone;
929
+        }
930
+        // Fax
931
+        if ($fromcompany->fax)
932
+        {
933
+            $line2.=($line2?" - ":"").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax;
934
+        }
935
+
936
+        // URL
937
+        if ($fromcompany->url)
938
+        {
939
+            $line2.=($line2?" - ":"").$fromcompany->url;
940
+        }
941
+        // Email
942
+        if ($fromcompany->email)
943
+        {
944
+            $line2.=($line2?" - ":"").$fromcompany->email;
945
+        }
946
+    }
947
+    if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE'))
948
+    {
949
+        // Managers
950
+        if ($fromcompany->managers)
951
+        {
952
+            $line2.=($line2?" - ":"").$fromcompany->managers;
953
+        }
954
+    }
955
+
956
+    // Line 3 of company infos
957
+    // Juridical status
958
+    if ($fromcompany->forme_juridique_code)
959
+    {
960
+        $line3.=($line3?" - ":"").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code));
961
+    }
962
+    // Capital
963
+    if ($fromcompany->capital)
964
+    {
965
+        $tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string
966
+        if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
967
+        else $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",$tmpamounttoshow,$outputlangs);
968
+    }
969
+    // Prof Id 1
970
+    if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || ! $fromcompany->idprof2))
971
+    {
972
+        $field=$outputlangs->transcountrynoentities("ProfId1",$fromcompany->country_code);
973
+        if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
974
+        $line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1);
975
+    }
976
+    // Prof Id 2
977
+    if ($fromcompany->idprof2)
978
+    {
979
+        $field=$outputlangs->transcountrynoentities("ProfId2",$fromcompany->country_code);
980
+        if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
981
+        $line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2);
982
+    }
983
+
984
+    // Line 4 of company infos
985
+    // Prof Id 3
986
+    if ($fromcompany->idprof3)
987
+    {
988
+        $field=$outputlangs->transcountrynoentities("ProfId3",$fromcompany->country_code);
989
+        if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
990
+        $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3);
991
+    }
992
+    // Prof Id 4
993
+    if ($fromcompany->idprof4)
994
+    {
995
+        $field=$outputlangs->transcountrynoentities("ProfId4",$fromcompany->country_code);
996
+        if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
997
+        $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4);
998
+    }
999
+    // Prof Id 5
1000
+    if ($fromcompany->idprof5)
1001
+    {
1002
+        $field=$outputlangs->transcountrynoentities("ProfId5",$fromcompany->country_code);
1003
+        if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1004
+        $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5);
1005
+    }
1006
+    // Prof Id 6
1007
+    if ($fromcompany->idprof6)
1008
+    {
1009
+        $field=$outputlangs->transcountrynoentities("ProfId6",$fromcompany->country_code);
1010
+        if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1011
+        $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6);
1012
+    }
1013
+    // IntraCommunautary VAT
1014
+    if ($fromcompany->tva_intra != '')
1015
+    {
1016
+        $line4.=($line4?" - ":"").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra);
1017
+    }
1018
+
1019
+    $pdf->SetFont('','',7);
1020
+    $pdf->SetDrawColor(224,224,224);
1021
+
1022
+    // The start of the bottom of this page footer is positioned according to # of lines
1023
+    $freetextheight=0;
1024
+    if ($line)	// Free text
1025
+    {
1026
+        //$line="sample text<br>\nfd<strong>sf</strong>sdf<br>\nghfghg<br>";
1027
+        if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
1028
+        {
1029
+            $width=20000; $align='L';	// By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
1030
+            if (! empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) {
1031
+                $width=200; $align='C';
1032
+            }
1033
+            $freetextheight=$pdf->getStringHeight($width,$line);
1034
+        }
1035
+        else
1036
+        {
1037 1037
             $freetextheight=pdfGetHeightForHtmlContent($pdf,dol_htmlentitiesbr($line, 1, 'UTF-8', 0));      // New method (works for HTML content)
1038 1038
             //print '<br>'.$freetextheight;exit;
1039
-		}
1040
-	}
1039
+        }
1040
+    }
1041 1041
 
1042
-	$marginwithfooter=$marge_basse + $freetextheight + (! empty($line1)?3:0) + (! empty($line2)?3:0) + (! empty($line3)?3:0) + (! empty($line4)?3:0);
1043
-	$posy=$marginwithfooter+0;
1042
+    $marginwithfooter=$marge_basse + $freetextheight + (! empty($line1)?3:0) + (! empty($line2)?3:0) + (! empty($line3)?3:0) + (! empty($line4)?3:0);
1043
+    $posy=$marginwithfooter+0;
1044 1044
 
1045
-	if ($line)	// Free text
1046
-	{
1047
-		$pdf->SetXY($dims['lm'],-$posy);
1048
-		if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))   // by default
1049
-		{
1045
+    if ($line)	// Free text
1046
+    {
1047
+        $pdf->SetXY($dims['lm'],-$posy);
1048
+        if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))   // by default
1049
+        {
1050 1050
             $pdf->MultiCell(0, 3, $line, 0, $align, 0);
1051
-		}
1052
-		else
1053
-		{
1051
+        }
1052
+        else
1053
+        {
1054 1054
             $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk']-$marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0));
1055
-		}
1056
-		$posy-=$freetextheight;
1057
-	}
1058
-
1059
-	$pdf->SetY(-$posy);
1060
-	$pdf->line($dims['lm'], $dims['hk']-$posy, $dims['wk']-$dims['rm'], $dims['hk']-$posy);
1061
-	$posy--;
1062
-
1063
-	if (! empty($line1))
1064
-	{
1065
-		$pdf->SetFont('','B',7);
1066
-		$pdf->SetXY($dims['lm'],-$posy);
1067
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line1, 0, 'C', 0);
1068
-		$posy-=3;
1069
-		$pdf->SetFont('','',7);
1070
-	}
1071
-
1072
-	if (! empty($line2))
1073
-	{
1074
-		$pdf->SetFont('','B',7);
1075
-		$pdf->SetXY($dims['lm'],-$posy);
1076
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line2, 0, 'C', 0);
1077
-		$posy-=3;
1078
-		$pdf->SetFont('','',7);
1079
-	}
1080
-
1081
-	if (! empty($line3))
1082
-	{
1083
-		$pdf->SetXY($dims['lm'],-$posy);
1084
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line3, 0, 'C', 0);
1085
-	}
1086
-
1087
-	if (! empty($line4))
1088
-	{
1089
-		$posy-=3;
1090
-		$pdf->SetXY($dims['lm'],-$posy);
1091
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line4, 0, 'C', 0);
1092
-	}
1093
-
1094
-	// Show page nb only on iso languages (so default Helvetica font)
1095
-	if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica')
1096
-	{
1097
-		$pdf->SetXY($dims['wk']-$dims['rm']-15, -$posy);
1098
-		//print 'xxx'.$pdf->PageNo().'-'.$pdf->getAliasNbPages().'-'.$pdf->getAliasNumPage();exit;
1099
-		$pdf->MultiCell(15, 2, $pdf->PageNo().'/'.$pdf->getAliasNbPages(), 0, 'R', 0);
1100
-	}
1101
-
1102
-	return $marginwithfooter;
1055
+        }
1056
+        $posy-=$freetextheight;
1057
+    }
1058
+
1059
+    $pdf->SetY(-$posy);
1060
+    $pdf->line($dims['lm'], $dims['hk']-$posy, $dims['wk']-$dims['rm'], $dims['hk']-$posy);
1061
+    $posy--;
1062
+
1063
+    if (! empty($line1))
1064
+    {
1065
+        $pdf->SetFont('','B',7);
1066
+        $pdf->SetXY($dims['lm'],-$posy);
1067
+        $pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line1, 0, 'C', 0);
1068
+        $posy-=3;
1069
+        $pdf->SetFont('','',7);
1070
+    }
1071
+
1072
+    if (! empty($line2))
1073
+    {
1074
+        $pdf->SetFont('','B',7);
1075
+        $pdf->SetXY($dims['lm'],-$posy);
1076
+        $pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line2, 0, 'C', 0);
1077
+        $posy-=3;
1078
+        $pdf->SetFont('','',7);
1079
+    }
1080
+
1081
+    if (! empty($line3))
1082
+    {
1083
+        $pdf->SetXY($dims['lm'],-$posy);
1084
+        $pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line3, 0, 'C', 0);
1085
+    }
1086
+
1087
+    if (! empty($line4))
1088
+    {
1089
+        $posy-=3;
1090
+        $pdf->SetXY($dims['lm'],-$posy);
1091
+        $pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line4, 0, 'C', 0);
1092
+    }
1093
+
1094
+    // Show page nb only on iso languages (so default Helvetica font)
1095
+    if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica')
1096
+    {
1097
+        $pdf->SetXY($dims['wk']-$dims['rm']-15, -$posy);
1098
+        //print 'xxx'.$pdf->PageNo().'-'.$pdf->getAliasNbPages().'-'.$pdf->getAliasNumPage();exit;
1099
+        $pdf->MultiCell(15, 2, $pdf->PageNo().'/'.$pdf->getAliasNbPages(), 0, 'R', 0);
1100
+    }
1101
+
1102
+    return $marginwithfooter;
1103 1103
 }
1104 1104
 
1105 1105
 /**
@@ -1118,25 +1118,25 @@  discard block
 block discarded – undo
1118 1118
  */
1119 1119
 function pdf_writeLinkedObjects(&$pdf,$object,$outputlangs,$posx,$posy,$w,$h,$align,$default_font_size)
1120 1120
 {
1121
-	$linkedobjects = pdf_getLinkedObjects($object,$outputlangs);
1122
-	if (! empty($linkedobjects))
1123
-	{
1124
-		foreach($linkedobjects as $linkedobject)
1125
-		{
1126
-		    $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"];
1127
-		    if (! empty($linkedobject["date_value"]))
1128
-		    {
1129
-		        $reftoshow .= ' / '.$linkedobject["date_value"];
1130
-		    }
1131
-
1132
-			$posy+=3;
1133
-			$pdf->SetXY($posx,$posy);
1134
-			$pdf->SetFont('','', $default_font_size - 2);
1135
-			$pdf->MultiCell($w, $h, $reftoshow, '', $align);
1136
-		}
1137
-	}
1138
-
1139
-	return $pdf->getY();
1121
+    $linkedobjects = pdf_getLinkedObjects($object,$outputlangs);
1122
+    if (! empty($linkedobjects))
1123
+    {
1124
+        foreach($linkedobjects as $linkedobject)
1125
+        {
1126
+            $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"];
1127
+            if (! empty($linkedobject["date_value"]))
1128
+            {
1129
+                $reftoshow .= ' / '.$linkedobject["date_value"];
1130
+            }
1131
+
1132
+            $posy+=3;
1133
+            $pdf->SetXY($posx,$posy);
1134
+            $pdf->SetFont('','', $default_font_size - 2);
1135
+            $pdf->MultiCell($w, $h, $reftoshow, '', $align);
1136
+        }
1137
+    }
1138
+
1139
+    return $pdf->getY();
1140 1140
 }
1141 1141
 
1142 1142
 /**
@@ -1157,29 +1157,29 @@  discard block
 block discarded – undo
1157 1157
  */
1158 1158
 function pdf_writelinedesc(&$pdf,$object,$i,$outputlangs,$w,$h,$posx,$posy,$hideref=0,$hidedesc=0,$issupplierline=0)
1159 1159
 {
1160
-	global $db, $conf, $langs, $hookmanager;
1161
-
1162
-	$reshook=0;
1163
-	$result='';
1164
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1165
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1166
-	{
1167
-		$special_code = $object->lines[$i]->special_code;
1168
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1169
-		$parameters = array('pdf'=>$pdf,'i'=>$i,'outputlangs'=>$outputlangs,'w'=>$w,'h'=>$h,'posx'=>$posx,'posy'=>$posy,'hideref'=>$hideref,'hidedesc'=>$hidedesc,'issupplierline'=>$issupplierline,'special_code'=>$special_code);
1170
-		$action='';
1171
-		$reshook=$hookmanager->executeHooks('pdf_writelinedesc',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1172
-
1173
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1174
-	}
1175
-	if (empty($reshook))
1176
-	{
1177
-		$labelproductservice=pdf_getlinedesc($object,$i,$outputlangs,$hideref,$hidedesc,$issupplierline);
1178
-		// Description
1179
-		$pdf->writeHTMLCell($w, $h, $posx, $posy, $outputlangs->convToOutputCharset($labelproductservice), 0, 1, false, true, 'J',true);
1180
-		$result.=$labelproductservice;
1181
-	}
1182
-	return $result;
1160
+    global $db, $conf, $langs, $hookmanager;
1161
+
1162
+    $reshook=0;
1163
+    $result='';
1164
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1165
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1166
+    {
1167
+        $special_code = $object->lines[$i]->special_code;
1168
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1169
+        $parameters = array('pdf'=>$pdf,'i'=>$i,'outputlangs'=>$outputlangs,'w'=>$w,'h'=>$h,'posx'=>$posx,'posy'=>$posy,'hideref'=>$hideref,'hidedesc'=>$hidedesc,'issupplierline'=>$issupplierline,'special_code'=>$special_code);
1170
+        $action='';
1171
+        $reshook=$hookmanager->executeHooks('pdf_writelinedesc',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1172
+
1173
+        if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1174
+    }
1175
+    if (empty($reshook))
1176
+    {
1177
+        $labelproductservice=pdf_getlinedesc($object,$i,$outputlangs,$hideref,$hidedesc,$issupplierline);
1178
+        // Description
1179
+        $pdf->writeHTMLCell($w, $h, $posx, $posy, $outputlangs->convToOutputCharset($labelproductservice), 0, 1, false, true, 'J',true);
1180
+        $result.=$labelproductservice;
1181
+    }
1182
+    return $result;
1183 1183
 }
1184 1184
 
1185 1185
 /**
@@ -1195,222 +1195,222 @@  discard block
 block discarded – undo
1195 1195
  */
1196 1196
 function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issupplierline=0)
1197 1197
 {
1198
-	global $db, $conf, $langs;
1199
-
1200
-	$idprod=(! empty($object->lines[$i]->fk_product)?$object->lines[$i]->fk_product:false);
1201
-	$label=(! empty($object->lines[$i]->label)?$object->lines[$i]->label:(! empty($object->lines[$i]->product_label)?$object->lines[$i]->product_label:''));
1202
-	$desc=(! empty($object->lines[$i]->desc)?$object->lines[$i]->desc:(! empty($object->lines[$i]->description)?$object->lines[$i]->description:''));
1203
-	$ref_supplier=(! empty($object->lines[$i]->ref_supplier)?$object->lines[$i]->ref_supplier:(! empty($object->lines[$i]->ref_fourn)?$object->lines[$i]->ref_fourn:''));    // TODO Not yet saved for supplier invoices, only supplier orders
1204
-	$note=(! empty($object->lines[$i]->note)?$object->lines[$i]->note:'');
1205
-	$dbatch=(! empty($object->lines[$i]->detail_batch)?$object->lines[$i]->detail_batch:false);
1206
-
1207
-	if ($issupplierline)
1208
-	{
1209
-		include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1210
-		$prodser = new ProductFournisseur($db);
1211
-	}
1212
-	else
1213
-	{
1214
-		include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1215
-		$prodser = new Product($db);
1216
-	}
1217
-
1218
-	if ($idprod)
1219
-	{
1220
-		$prodser->fetch($idprod);
1221
-		// If a predefined product and multilang and on other lang, we renamed label with label translated
1222
-		if (! empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang))
1223
-		{
1224
-			$translatealsoifmodified=(! empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED));	// By default if value was modified manually, we keep it (no translation because we don't have it)
1225
-
1226
-			// TODO Instead of making a compare to see if param was modified, check that content contains reference translation. If yes, add the added part to the new translation
1227
-			// ($textwasmodified is replaced with $textwasmodifiedorcompleted and we add completion).
1228
-
1229
-			// Set label
1230
-			// If we want another language, and if label is same than default language (we did force it to a specific value), we can use translation.
1231
-			//var_dump($outputlangs->defaultlang.' - '.$langs->defaultlang.' - '.$label.' - '.$prodser->label);exit;
1232
-			$textwasmodified=($label == $prodser->label);
1233
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified))     $label=$prodser->multilangs[$outputlangs->defaultlang]["label"];
1234
-
1235
-			// Set desc
1236
-			// Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no
1237
-			$textwasmodified=false;
1238
-			if (!empty($desc) && dol_textishtml($desc) && !empty($prodser->description) && dol_textishtml($prodser->description)) {
1239
-				$textwasmodified=(strpos(dol_html_entity_decode($desc,ENT_QUOTES | ENT_HTML401),dol_html_entity_decode($prodser->description,ENT_QUOTES | ENT_HTML401))!==false);
1240
-			} else {
1241
-				$textwasmodified=($desc == $prodser->description);
1242
-			}
1243
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified))  $desc=$prodser->multilangs[$outputlangs->defaultlang]["description"];
1244
-
1245
-			// Set note
1246
-			$textwasmodified=($note == $prodser->note);
1247
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified))  $note=$prodser->multilangs[$outputlangs->defaultlang]["note"];
1248
-		}
1249
-	}
1250
-
1251
-	// Description short of product line
1252
-	$libelleproduitservice=$label;
1253
-
1254
-	// Description long of product line
1255
-	if (! empty($desc) && ($desc != $label))
1256
-	{
1257
-		if ($libelleproduitservice && empty($hidedesc))
1258
-		{
1259
-			$libelleproduitservice.='__N__';
1260
-		}
1261
-
1262
-		if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except)
1263
-		{
1264
-			$discount=new DiscountAbsolute($db);
1265
-			$discount->fetch($object->lines[$i]->fk_remise_except);
1266
-			$sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1267
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref);
1268
-		}
1269
-		elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except)
1270
-		{
1271
-			$discount=new DiscountAbsolute($db);
1272
-			$discount->fetch($object->lines[$i]->fk_remise_except);
1273
-			$sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1274
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref);
1275
-			// Add date of deposit
1276
-			if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')';
1277
-		}
1278
-		if ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except)
1279
-		{
1280
-			$discount=new DiscountAbsolute($db);
1281
-			$discount->fetch($object->lines[$i]->fk_remise_except);
1282
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source);
1283
-		}
1284
-		elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except)
1285
-		{
1286
-			$discount=new DiscountAbsolute($db);
1287
-			$discount->fetch($object->lines[$i]->fk_remise_except);
1288
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source);
1289
-		}
1290
-		else
1291
-		{
1292
-			if ($idprod)
1293
-			{
1294
-				if (empty($hidedesc))
1295
-				{
1296
-					if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST))
1297
-					{
1298
-						$libelleproduitservice=$desc."\n".$libelleproduitservice;
1299
-					}
1300
-					else
1301
-					{
1302
-						$libelleproduitservice.=$desc;
1303
-					}
1304
-				}
1305
-			}
1306
-			else
1307
-			{
1308
-				$libelleproduitservice.=$desc;
1309
-			}
1310
-		}
1311
-	}
1312
-
1313
-	// We add ref of product (and supplier ref if defined)
1314
-	$prefix_prodserv = "";
1315
-	$ref_prodserv = "";
1316
-	if (! empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS))   // In standard mode, we do not show this
1317
-	{
1318
-		if ($prodser->isService())
1319
-		{
1320
-			$prefix_prodserv = $outputlangs->transnoentitiesnoconv("Service")." ";
1321
-		}
1322
-		else
1323
-		{
1324
-			$prefix_prodserv = $outputlangs->transnoentitiesnoconv("Product")." ";
1325
-		}
1326
-	}
1327
-
1328
-	if (empty($hideref))
1329
-	{
1330
-		if ($issupplierline)
1331
-		{
1332
-			if ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1)
1333
-				$ref_prodserv = $ref_supplier;
1334
-			elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2)
1335
-				$ref_prodserv = $ref_supplier. ' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')';
1336
-			else	// Common case
1337
-			{
1338
-				$ref_prodserv = $prodser->ref; // Show local ref
1339
-				if ($ref_supplier) $ref_prodserv.= ($prodser->ref?' (':'').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref?')':'');
1340
-			}
1341
-		}
1342
-		else
1343
-		{
1344
-			$ref_prodserv = $prodser->ref; // Show local ref only
1345
-		}
1346
-
1347
-		if (! empty($libelleproduitservice) && ! empty($ref_prodserv)) $ref_prodserv .= " - ";
1348
-	}
1349
-
1350
-	if(!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){ $ref_prodserv = '<b>'.$ref_prodserv.'</b>'; }
1351
-	$libelleproduitservice=$prefix_prodserv.$ref_prodserv.$libelleproduitservice;
1352
-
1353
-	// Add an additional description for the category products
1354
-	if (! empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && ! empty($conf->categorie->enabled))
1355
-	{
1356
-		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1357
-		$categstatic=new Categorie($db);
1358
-		// recovering the list of all the categories linked to product
1359
-		$tblcateg=$categstatic->containing($idprod, Categorie::TYPE_PRODUCT);
1360
-		foreach ($tblcateg as $cate)
1361
-		{
1362
-			// Adding the descriptions if they are filled
1363
-			$desccateg=$cate->add_description;
1364
-			if ($desccateg)
1365
-				$libelleproduitservice.='__N__'.$desccateg;
1366
-		}
1367
-	}
1368
-
1369
-	if (! empty($object->lines[$i]->date_start) || ! empty($object->lines[$i]->date_end))
1370
-	{
1371
-		$format='day';
1372
-		// Show duration if exists
1373
-		if ($object->lines[$i]->date_start && $object->lines[$i]->date_end)
1374
-		{
1375
-			$period='('.$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs),dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1376
-		}
1377
-		if ($object->lines[$i]->date_start && ! $object->lines[$i]->date_end)
1378
-		{
1379
-			$period='('.$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')';
1380
-		}
1381
-		if (! $object->lines[$i]->date_start && $object->lines[$i]->date_end)
1382
-		{
1383
-			$period='('.$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1384
-		}
1385
-		//print '>'.$outputlangs->charset_output.','.$period;
1386
-		if(!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){
1387
-		    $libelleproduitservice.= '<b style="color:#333666;" ><em>'."__N__</b> ".$period.'</em>';
1388
-		}else{
1389
-		$libelleproduitservice.="__N__".$period;
1390
-		}
1391
-		//print $libelleproduitservice;
1392
-	}
1393
-
1394
-	if ($dbatch)
1395
-	{
1396
-		$format='day';
1397
-		foreach ($dbatch as $detail)
1398
-		{
1399
-			$dte=array();
1400
-			if ($detail->eatby) $dte[]=$outputlangs->transnoentitiesnoconv('printEatby',dol_print_date($detail->eatby, $format, false, $outputlangs));
1401
-			if ($detail->sellby) $dte[]=$outputlangs->transnoentitiesnoconv('printSellby',dol_print_date($detail->sellby, $format, false, $outputlangs));
1402
-			if ($detail->batch) $dte[]=$outputlangs->transnoentitiesnoconv('printBatch',$detail->batch);
1403
-			$dte[]=$outputlangs->transnoentitiesnoconv('printQty',$detail->qty);
1404
-			$libelleproduitservice.= "__N__  ".implode(" - ", $dte);
1405
-		}
1406
-	}
1407
-
1408
-	// Now we convert \n into br
1409
-	if (dol_textishtml($libelleproduitservice)) $libelleproduitservice=preg_replace('/__N__/','<br>',$libelleproduitservice);
1410
-	else $libelleproduitservice=preg_replace('/__N__/',"\n",$libelleproduitservice);
1411
-	$libelleproduitservice=dol_htmlentitiesbr($libelleproduitservice,1);
1412
-
1413
-	return $libelleproduitservice;
1198
+    global $db, $conf, $langs;
1199
+
1200
+    $idprod=(! empty($object->lines[$i]->fk_product)?$object->lines[$i]->fk_product:false);
1201
+    $label=(! empty($object->lines[$i]->label)?$object->lines[$i]->label:(! empty($object->lines[$i]->product_label)?$object->lines[$i]->product_label:''));
1202
+    $desc=(! empty($object->lines[$i]->desc)?$object->lines[$i]->desc:(! empty($object->lines[$i]->description)?$object->lines[$i]->description:''));
1203
+    $ref_supplier=(! empty($object->lines[$i]->ref_supplier)?$object->lines[$i]->ref_supplier:(! empty($object->lines[$i]->ref_fourn)?$object->lines[$i]->ref_fourn:''));    // TODO Not yet saved for supplier invoices, only supplier orders
1204
+    $note=(! empty($object->lines[$i]->note)?$object->lines[$i]->note:'');
1205
+    $dbatch=(! empty($object->lines[$i]->detail_batch)?$object->lines[$i]->detail_batch:false);
1206
+
1207
+    if ($issupplierline)
1208
+    {
1209
+        include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1210
+        $prodser = new ProductFournisseur($db);
1211
+    }
1212
+    else
1213
+    {
1214
+        include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1215
+        $prodser = new Product($db);
1216
+    }
1217
+
1218
+    if ($idprod)
1219
+    {
1220
+        $prodser->fetch($idprod);
1221
+        // If a predefined product and multilang and on other lang, we renamed label with label translated
1222
+        if (! empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang))
1223
+        {
1224
+            $translatealsoifmodified=(! empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED));	// By default if value was modified manually, we keep it (no translation because we don't have it)
1225
+
1226
+            // TODO Instead of making a compare to see if param was modified, check that content contains reference translation. If yes, add the added part to the new translation
1227
+            // ($textwasmodified is replaced with $textwasmodifiedorcompleted and we add completion).
1228
+
1229
+            // Set label
1230
+            // If we want another language, and if label is same than default language (we did force it to a specific value), we can use translation.
1231
+            //var_dump($outputlangs->defaultlang.' - '.$langs->defaultlang.' - '.$label.' - '.$prodser->label);exit;
1232
+            $textwasmodified=($label == $prodser->label);
1233
+            if (! empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified))     $label=$prodser->multilangs[$outputlangs->defaultlang]["label"];
1234
+
1235
+            // Set desc
1236
+            // Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no
1237
+            $textwasmodified=false;
1238
+            if (!empty($desc) && dol_textishtml($desc) && !empty($prodser->description) && dol_textishtml($prodser->description)) {
1239
+                $textwasmodified=(strpos(dol_html_entity_decode($desc,ENT_QUOTES | ENT_HTML401),dol_html_entity_decode($prodser->description,ENT_QUOTES | ENT_HTML401))!==false);
1240
+            } else {
1241
+                $textwasmodified=($desc == $prodser->description);
1242
+            }
1243
+            if (! empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified))  $desc=$prodser->multilangs[$outputlangs->defaultlang]["description"];
1244
+
1245
+            // Set note
1246
+            $textwasmodified=($note == $prodser->note);
1247
+            if (! empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified))  $note=$prodser->multilangs[$outputlangs->defaultlang]["note"];
1248
+        }
1249
+    }
1250
+
1251
+    // Description short of product line
1252
+    $libelleproduitservice=$label;
1253
+
1254
+    // Description long of product line
1255
+    if (! empty($desc) && ($desc != $label))
1256
+    {
1257
+        if ($libelleproduitservice && empty($hidedesc))
1258
+        {
1259
+            $libelleproduitservice.='__N__';
1260
+        }
1261
+
1262
+        if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except)
1263
+        {
1264
+            $discount=new DiscountAbsolute($db);
1265
+            $discount->fetch($object->lines[$i]->fk_remise_except);
1266
+            $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1267
+            $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref);
1268
+        }
1269
+        elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except)
1270
+        {
1271
+            $discount=new DiscountAbsolute($db);
1272
+            $discount->fetch($object->lines[$i]->fk_remise_except);
1273
+            $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1274
+            $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref);
1275
+            // Add date of deposit
1276
+            if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')';
1277
+        }
1278
+        if ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except)
1279
+        {
1280
+            $discount=new DiscountAbsolute($db);
1281
+            $discount->fetch($object->lines[$i]->fk_remise_except);
1282
+            $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source);
1283
+        }
1284
+        elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except)
1285
+        {
1286
+            $discount=new DiscountAbsolute($db);
1287
+            $discount->fetch($object->lines[$i]->fk_remise_except);
1288
+            $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source);
1289
+        }
1290
+        else
1291
+        {
1292
+            if ($idprod)
1293
+            {
1294
+                if (empty($hidedesc))
1295
+                {
1296
+                    if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST))
1297
+                    {
1298
+                        $libelleproduitservice=$desc."\n".$libelleproduitservice;
1299
+                    }
1300
+                    else
1301
+                    {
1302
+                        $libelleproduitservice.=$desc;
1303
+                    }
1304
+                }
1305
+            }
1306
+            else
1307
+            {
1308
+                $libelleproduitservice.=$desc;
1309
+            }
1310
+        }
1311
+    }
1312
+
1313
+    // We add ref of product (and supplier ref if defined)
1314
+    $prefix_prodserv = "";
1315
+    $ref_prodserv = "";
1316
+    if (! empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS))   // In standard mode, we do not show this
1317
+    {
1318
+        if ($prodser->isService())
1319
+        {
1320
+            $prefix_prodserv = $outputlangs->transnoentitiesnoconv("Service")." ";
1321
+        }
1322
+        else
1323
+        {
1324
+            $prefix_prodserv = $outputlangs->transnoentitiesnoconv("Product")." ";
1325
+        }
1326
+    }
1327
+
1328
+    if (empty($hideref))
1329
+    {
1330
+        if ($issupplierline)
1331
+        {
1332
+            if ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1)
1333
+                $ref_prodserv = $ref_supplier;
1334
+            elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2)
1335
+                $ref_prodserv = $ref_supplier. ' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')';
1336
+            else	// Common case
1337
+            {
1338
+                $ref_prodserv = $prodser->ref; // Show local ref
1339
+                if ($ref_supplier) $ref_prodserv.= ($prodser->ref?' (':'').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref?')':'');
1340
+            }
1341
+        }
1342
+        else
1343
+        {
1344
+            $ref_prodserv = $prodser->ref; // Show local ref only
1345
+        }
1346
+
1347
+        if (! empty($libelleproduitservice) && ! empty($ref_prodserv)) $ref_prodserv .= " - ";
1348
+    }
1349
+
1350
+    if(!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){ $ref_prodserv = '<b>'.$ref_prodserv.'</b>'; }
1351
+    $libelleproduitservice=$prefix_prodserv.$ref_prodserv.$libelleproduitservice;
1352
+
1353
+    // Add an additional description for the category products
1354
+    if (! empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && ! empty($conf->categorie->enabled))
1355
+    {
1356
+        include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1357
+        $categstatic=new Categorie($db);
1358
+        // recovering the list of all the categories linked to product
1359
+        $tblcateg=$categstatic->containing($idprod, Categorie::TYPE_PRODUCT);
1360
+        foreach ($tblcateg as $cate)
1361
+        {
1362
+            // Adding the descriptions if they are filled
1363
+            $desccateg=$cate->add_description;
1364
+            if ($desccateg)
1365
+                $libelleproduitservice.='__N__'.$desccateg;
1366
+        }
1367
+    }
1368
+
1369
+    if (! empty($object->lines[$i]->date_start) || ! empty($object->lines[$i]->date_end))
1370
+    {
1371
+        $format='day';
1372
+        // Show duration if exists
1373
+        if ($object->lines[$i]->date_start && $object->lines[$i]->date_end)
1374
+        {
1375
+            $period='('.$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs),dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1376
+        }
1377
+        if ($object->lines[$i]->date_start && ! $object->lines[$i]->date_end)
1378
+        {
1379
+            $period='('.$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')';
1380
+        }
1381
+        if (! $object->lines[$i]->date_start && $object->lines[$i]->date_end)
1382
+        {
1383
+            $period='('.$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1384
+        }
1385
+        //print '>'.$outputlangs->charset_output.','.$period;
1386
+        if(!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){
1387
+            $libelleproduitservice.= '<b style="color:#333666;" ><em>'."__N__</b> ".$period.'</em>';
1388
+        }else{
1389
+        $libelleproduitservice.="__N__".$period;
1390
+        }
1391
+        //print $libelleproduitservice;
1392
+    }
1393
+
1394
+    if ($dbatch)
1395
+    {
1396
+        $format='day';
1397
+        foreach ($dbatch as $detail)
1398
+        {
1399
+            $dte=array();
1400
+            if ($detail->eatby) $dte[]=$outputlangs->transnoentitiesnoconv('printEatby',dol_print_date($detail->eatby, $format, false, $outputlangs));
1401
+            if ($detail->sellby) $dte[]=$outputlangs->transnoentitiesnoconv('printSellby',dol_print_date($detail->sellby, $format, false, $outputlangs));
1402
+            if ($detail->batch) $dte[]=$outputlangs->transnoentitiesnoconv('printBatch',$detail->batch);
1403
+            $dte[]=$outputlangs->transnoentitiesnoconv('printQty',$detail->qty);
1404
+            $libelleproduitservice.= "__N__  ".implode(" - ", $dte);
1405
+        }
1406
+    }
1407
+
1408
+    // Now we convert \n into br
1409
+    if (dol_textishtml($libelleproduitservice)) $libelleproduitservice=preg_replace('/__N__/','<br>',$libelleproduitservice);
1410
+    else $libelleproduitservice=preg_replace('/__N__/',"\n",$libelleproduitservice);
1411
+    $libelleproduitservice=dol_htmlentitiesbr($libelleproduitservice,1);
1412
+
1413
+    return $libelleproduitservice;
1414 1414
 }
1415 1415
 
1416 1416
 /**
@@ -1424,25 +1424,25 @@  discard block
 block discarded – undo
1424 1424
  */
1425 1425
 function pdf_getlinenum($object,$i,$outputlangs,$hidedetails=0)
1426 1426
 {
1427
-	global $hookmanager;
1428
-
1429
-	$reshook=0;
1430
-	$result='';
1431
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1432
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1433
-	{
1434
-		$special_code = $object->lines[$i]->special_code;
1435
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1436
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1437
-		$action='';
1438
-		$reshook = $hookmanager->executeHooks('pdf_getlinenum',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1439
-		$result.=$hookmanager->resPrint;
1440
-	}
1441
-	if (empty($reshook))
1442
-	{
1443
-		$result.=dol_htmlentitiesbr($object->lines[$i]->num);
1444
-	}
1445
-	return $result;
1427
+    global $hookmanager;
1428
+
1429
+    $reshook=0;
1430
+    $result='';
1431
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1432
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1433
+    {
1434
+        $special_code = $object->lines[$i]->special_code;
1435
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1436
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1437
+        $action='';
1438
+        $reshook = $hookmanager->executeHooks('pdf_getlinenum',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1439
+        $result.=$hookmanager->resPrint;
1440
+    }
1441
+    if (empty($reshook))
1442
+    {
1443
+        $result.=dol_htmlentitiesbr($object->lines[$i]->num);
1444
+    }
1445
+    return $result;
1446 1446
 }
1447 1447
 
1448 1448
 
@@ -1457,25 +1457,25 @@  discard block
 block discarded – undo
1457 1457
  */
1458 1458
 function pdf_getlineref($object,$i,$outputlangs,$hidedetails=0)
1459 1459
 {
1460
-	global $hookmanager;
1461
-
1462
-	$reshook=0;
1463
-	$result='';
1464
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1465
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1466
-	{
1467
-		$special_code = $object->lines[$i]->special_code;
1468
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1469
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1470
-		$action='';
1471
-		$reshook = $hookmanager->executeHooks('pdf_getlineref',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1472
-		$result.=$hookmanager->resPrint;
1473
-	}
1474
-	if (empty($reshook))
1475
-	{
1476
-		$result.=dol_htmlentitiesbr($object->lines[$i]->product_ref);
1477
-	}
1478
-	return $result;
1460
+    global $hookmanager;
1461
+
1462
+    $reshook=0;
1463
+    $result='';
1464
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1465
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1466
+    {
1467
+        $special_code = $object->lines[$i]->special_code;
1468
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1469
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1470
+        $action='';
1471
+        $reshook = $hookmanager->executeHooks('pdf_getlineref',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1472
+        $result.=$hookmanager->resPrint;
1473
+    }
1474
+    if (empty($reshook))
1475
+    {
1476
+        $result.=dol_htmlentitiesbr($object->lines[$i]->product_ref);
1477
+    }
1478
+    return $result;
1479 1479
 }
1480 1480
 
1481 1481
 /**
@@ -1489,25 +1489,25 @@  discard block
 block discarded – undo
1489 1489
  */
1490 1490
 function pdf_getlineref_supplier($object,$i,$outputlangs,$hidedetails=0)
1491 1491
 {
1492
-	global $hookmanager;
1493
-
1494
-	$reshook=0;
1495
-	$result='';
1496
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1497
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1498
-	{
1499
-		$special_code = $object->lines[$i]->special_code;
1500
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1501
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1502
-		$action='';
1503
-		$reshook = $hookmanager->executeHooks('pdf_getlineref_supplier',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1504
-		$result.=$hookmanager->resPrint;
1505
-	}
1506
-	if (empty($reshook))
1507
-	{
1508
-		$result.=dol_htmlentitiesbr($object->lines[$i]->ref_supplier);
1509
-	}
1510
-	return $result;
1492
+    global $hookmanager;
1493
+
1494
+    $reshook=0;
1495
+    $result='';
1496
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1497
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1498
+    {
1499
+        $special_code = $object->lines[$i]->special_code;
1500
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1501
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1502
+        $action='';
1503
+        $reshook = $hookmanager->executeHooks('pdf_getlineref_supplier',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1504
+        $result.=$hookmanager->resPrint;
1505
+    }
1506
+    if (empty($reshook))
1507
+    {
1508
+        $result.=dol_htmlentitiesbr($object->lines[$i]->ref_supplier);
1509
+    }
1510
+    return $result;
1511 1511
 }
1512 1512
 
1513 1513
 /**
@@ -1521,52 +1521,52 @@  discard block
 block discarded – undo
1521 1521
  */
1522 1522
 function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails=0)
1523 1523
 {
1524
-	global $conf, $hookmanager, $mysoc;
1525
-
1526
-	$result='';
1527
-	$reshook=0;
1528
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1529
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
1530
-	{
1531
-		$special_code = $object->lines[$i]->special_code;
1532
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1533
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1534
-		$action='';
1535
-		$reshook = $hookmanager->executeHooks('pdf_getlinevatrate',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1536
-
1537
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1538
-	}
1539
-	if (empty($reshook))
1540
-	{
1541
-		if (empty($hidedetails) || $hidedetails > 1)
1542
-		{
1543
-			$tmpresult='';
1544
-
1545
-			$tmpresult.=vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1);
1546
-			if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX))
1547
-			{
1548
-				if ($object->lines[$i]->total_localtax1 != 0)
1549
-				{
1550
-					if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1551
-					else $tmpresult='';
1552
-					$tmpresult.=vatrate(abs($object->lines[$i]->localtax1_tx), 0);
1553
-				}
1554
-			}
1555
-			if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX))
1556
-			{
1557
-				if ($object->lines[$i]->total_localtax2 != 0)
1558
-				{
1559
-					if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1560
-					else $tmpresult='';
1561
-					$tmpresult.=vatrate(abs($object->lines[$i]->localtax2_tx), 0);
1562
-				}
1563
-			}
1564
-			$tmpresult.= '%';
1565
-
1566
-			$result.=$tmpresult;
1567
-		}
1568
-	}
1569
-	return $result;
1524
+    global $conf, $hookmanager, $mysoc;
1525
+
1526
+    $result='';
1527
+    $reshook=0;
1528
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1529
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
1530
+    {
1531
+        $special_code = $object->lines[$i]->special_code;
1532
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1533
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1534
+        $action='';
1535
+        $reshook = $hookmanager->executeHooks('pdf_getlinevatrate',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1536
+
1537
+        if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1538
+    }
1539
+    if (empty($reshook))
1540
+    {
1541
+        if (empty($hidedetails) || $hidedetails > 1)
1542
+        {
1543
+            $tmpresult='';
1544
+
1545
+            $tmpresult.=vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1);
1546
+            if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX))
1547
+            {
1548
+                if ($object->lines[$i]->total_localtax1 != 0)
1549
+                {
1550
+                    if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1551
+                    else $tmpresult='';
1552
+                    $tmpresult.=vatrate(abs($object->lines[$i]->localtax1_tx), 0);
1553
+                }
1554
+            }
1555
+            if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX))
1556
+            {
1557
+                if ($object->lines[$i]->total_localtax2 != 0)
1558
+                {
1559
+                    if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1560
+                    else $tmpresult='';
1561
+                    $tmpresult.=vatrate(abs($object->lines[$i]->localtax2_tx), 0);
1562
+                }
1563
+            }
1564
+            $tmpresult.= '%';
1565
+
1566
+            $result.=$tmpresult;
1567
+        }
1568
+    }
1569
+    return $result;
1570 1570
 }
1571 1571
 
1572 1572
 /**
@@ -1580,33 +1580,33 @@  discard block
 block discarded – undo
1580 1580
  */
1581 1581
 function pdf_getlineupexcltax($object,$i,$outputlangs,$hidedetails=0)
1582 1582
 {
1583
-	global $conf, $hookmanager;
1584
-
1585
-	$sign=1;
1586
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1587
-
1588
-	$result='';
1589
-	$reshook=0;
1590
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1591
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1592
-	{
1593
-		$special_code = $object->lines[$i]->special_code;
1594
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1595
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1596
-		$action='';
1597
-		$reshook = $hookmanager->executeHooks('pdf_getlineupexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1598
-
1599
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1600
-	}
1601
-	if (empty($reshook))
1602
-	{
1603
-		if (empty($hidedetails) || $hidedetails > 1)
1604
-		{
1605
-			$subprice = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice);
1606
-			$result.=price($sign * $subprice, 0, $outputlangs);
1607
-		}
1608
-	}
1609
-	return $result;
1583
+    global $conf, $hookmanager;
1584
+
1585
+    $sign=1;
1586
+    if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1587
+
1588
+    $result='';
1589
+    $reshook=0;
1590
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1591
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1592
+    {
1593
+        $special_code = $object->lines[$i]->special_code;
1594
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1595
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1596
+        $action='';
1597
+        $reshook = $hookmanager->executeHooks('pdf_getlineupexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1598
+
1599
+        if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1600
+    }
1601
+    if (empty($reshook))
1602
+    {
1603
+        if (empty($hidedetails) || $hidedetails > 1)
1604
+        {
1605
+            $subprice = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice);
1606
+            $result.=price($sign * $subprice, 0, $outputlangs);
1607
+        }
1608
+    }
1609
+    return $result;
1610 1610
 }
1611 1611
 
1612 1612
 /**
@@ -1620,29 +1620,29 @@  discard block
 block discarded – undo
1620 1620
  */
1621 1621
 function pdf_getlineupwithtax($object,$i,$outputlangs,$hidedetails=0)
1622 1622
 {
1623
-	global $hookmanager,$conf;
1624
-
1625
-	$sign=1;
1626
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1627
-
1628
-	$result='';
1629
-	$reshook=0;
1630
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1631
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1632
-	{
1633
-		$special_code = $object->lines[$i]->special_code;
1634
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1635
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1636
-		$action='';
1637
-		$reshook = $hookmanager->executeHooks('pdf_getlineupwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1638
-
1639
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1640
-	}
1641
-	if (empty($reshook))
1642
-	{
1643
-		if (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice)*($object->lines[$i]->tva_tx)/100), 0, $outputlangs);
1644
-	}
1645
-	return $result;
1623
+    global $hookmanager,$conf;
1624
+
1625
+    $sign=1;
1626
+    if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1627
+
1628
+    $result='';
1629
+    $reshook=0;
1630
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1631
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1632
+    {
1633
+        $special_code = $object->lines[$i]->special_code;
1634
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1635
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1636
+        $action='';
1637
+        $reshook = $hookmanager->executeHooks('pdf_getlineupwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1638
+
1639
+        if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1640
+    }
1641
+    if (empty($reshook))
1642
+    {
1643
+        if (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice)*($object->lines[$i]->tva_tx)/100), 0, $outputlangs);
1644
+    }
1645
+    return $result;
1646 1646
 }
1647 1647
 
1648 1648
 /**
@@ -1656,27 +1656,27 @@  discard block
 block discarded – undo
1656 1656
  */
1657 1657
 function pdf_getlineqty($object,$i,$outputlangs,$hidedetails=0)
1658 1658
 {
1659
-	global $hookmanager;
1660
-
1661
-	$result='';
1662
-	$reshook=0;
1663
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1664
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1665
-	{
1666
-		$special_code = $object->lines[$i]->special_code;
1667
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1668
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1669
-		$action='';
1670
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1671
-
1672
-		if(!empty($hookmanager->resPrint)) $result=$hookmanager->resPrint;
1673
-	}
1659
+    global $hookmanager;
1660
+
1661
+    $result='';
1662
+    $reshook=0;
1663
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1664
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1665
+    {
1666
+        $special_code = $object->lines[$i]->special_code;
1667
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1668
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1669
+        $action='';
1670
+        $reshook = $hookmanager->executeHooks('pdf_getlineqty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1671
+
1672
+        if(!empty($hookmanager->resPrint)) $result=$hookmanager->resPrint;
1673
+    }
1674 1674
     if (empty($reshook))
1675
-	{
1676
-	   if ($object->lines[$i]->special_code == 3) return '';
1677
-	   if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty;
1678
-	}
1679
-	return $result;
1675
+    {
1676
+        if ($object->lines[$i]->special_code == 3) return '';
1677
+        if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty;
1678
+    }
1679
+    return $result;
1680 1680
 }
1681 1681
 
1682 1682
 /**
@@ -1690,27 +1690,27 @@  discard block
 block discarded – undo
1690 1690
  */
1691 1691
 function pdf_getlineqty_asked($object,$i,$outputlangs,$hidedetails=0)
1692 1692
 {
1693
-	global $hookmanager;
1694
-
1695
-	$reshook=0;
1696
-	$result='';
1697
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1698
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1699
-	{
1700
-		$special_code = $object->lines[$i]->special_code;
1701
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1702
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1703
-		$action='';
1704
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty_asked',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1705
-
1706
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1707
-	}
1708
-	if (empty($reshook))
1709
-	{
1693
+    global $hookmanager;
1694
+
1695
+    $reshook=0;
1696
+    $result='';
1697
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1698
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1699
+    {
1700
+        $special_code = $object->lines[$i]->special_code;
1701
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1702
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1703
+        $action='';
1704
+        $reshook = $hookmanager->executeHooks('pdf_getlineqty_asked',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1705
+
1706
+        if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1707
+    }
1708
+    if (empty($reshook))
1709
+    {
1710 1710
         if ($object->lines[$i]->special_code == 3) return '';
1711 1711
         if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_asked;
1712
-	}
1713
-	return $result;
1712
+    }
1713
+    return $result;
1714 1714
 }
1715 1715
 
1716 1716
 /**
@@ -1724,27 +1724,27 @@  discard block
 block discarded – undo
1724 1724
  */
1725 1725
 function pdf_getlineqty_shipped($object,$i,$outputlangs,$hidedetails=0)
1726 1726
 {
1727
-	global $hookmanager;
1728
-
1729
-	$reshook=0;
1730
-	$result='';
1731
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1732
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1733
-	{
1734
-		$special_code = $object->lines[$i]->special_code;
1735
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1736
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1737
-		$action='';
1738
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1739
-
1740
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1741
-	}
1742
-	if (empty($reshook))
1743
-	{
1727
+    global $hookmanager;
1728
+
1729
+    $reshook=0;
1730
+    $result='';
1731
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1732
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1733
+    {
1734
+        $special_code = $object->lines[$i]->special_code;
1735
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1736
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1737
+        $action='';
1738
+        $reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1739
+
1740
+        if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1741
+    }
1742
+    if (empty($reshook))
1743
+    {
1744 1744
         if ($object->lines[$i]->special_code == 3) return '';
1745
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_shipped;
1746
-	}
1747
-	return $result;
1745
+        if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_shipped;
1746
+    }
1747
+    return $result;
1748 1748
 }
1749 1749
 
1750 1750
 /**
@@ -1758,27 +1758,27 @@  discard block
 block discarded – undo
1758 1758
  */
1759 1759
 function pdf_getlineqty_keeptoship($object,$i,$outputlangs,$hidedetails=0)
1760 1760
 {
1761
-	global $hookmanager;
1761
+    global $hookmanager;
1762 1762
 
1763
-	$reshook=0;
1763
+    $reshook=0;
1764 1764
     $result='';
1765 1765
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1766
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1767
-	{
1768
-		$special_code = $object->lines[$i]->special_code;
1769
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1770
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1771
-		$action='';
1772
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1773
-
1774
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1775
-	}
1776
-	if (empty($reshook))
1777
-	{
1766
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1767
+    {
1768
+        $special_code = $object->lines[$i]->special_code;
1769
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1770
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1771
+        $action='';
1772
+        $reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1773
+
1774
+        if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1775
+    }
1776
+    if (empty($reshook))
1777
+    {
1778 1778
         if ($object->lines[$i]->special_code == 3) return '';
1779
-		if (empty($hidedetails) || $hidedetails > 1) $result.=($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
1780
-	}
1781
-	return $result;
1779
+        if (empty($hidedetails) || $hidedetails > 1) $result.=($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
1780
+    }
1781
+    return $result;
1782 1782
 }
1783 1783
 
1784 1784
 /**
@@ -1793,34 +1793,34 @@  discard block
 block discarded – undo
1793 1793
  */
1794 1794
 function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = false)
1795 1795
 {
1796
-	global $langs;
1796
+    global $langs;
1797 1797
 
1798
-	$reshook=0;
1798
+    $reshook=0;
1799 1799
     $result='';
1800 1800
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1801
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1802
-	{
1803
-		$special_code = $object->lines[$i]->special_code;
1804
-		if (!empty($object->lines[$i]->fk_parent_line)) {
1805
-			$special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1806
-		}
1807
-		$parameters = array(
1808
-			'i' => $i,
1809
-			'outputlangs' => $outputlangs,
1810
-			'hidedetails' => $hidedetails,
1811
-			'special_code' => $special_code
1812
-		);
1813
-		$action = '';
1814
-		$reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1815
-
1816
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1817
-	}
1818
-	if (empty($reshook))
1819
-	{
1801
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1802
+    {
1803
+        $special_code = $object->lines[$i]->special_code;
1804
+        if (!empty($object->lines[$i]->fk_parent_line)) {
1805
+            $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1806
+        }
1807
+        $parameters = array(
1808
+            'i' => $i,
1809
+            'outputlangs' => $outputlangs,
1810
+            'hidedetails' => $hidedetails,
1811
+            'special_code' => $special_code
1812
+        );
1813
+        $action = '';
1814
+        $reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1815
+
1816
+        if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1817
+    }
1818
+    if (empty($reshook))
1819
+    {
1820 1820
         if ($object->lines[$i]->special_code == 3) return '';
1821
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
1822
-	}
1823
-	return $result;
1821
+        if (empty($hidedetails) || $hidedetails > 1) $result.=$langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
1822
+    }
1823
+    return $result;
1824 1824
 }
1825 1825
 
1826 1826
 
@@ -1835,29 +1835,29 @@  discard block
 block discarded – undo
1835 1835
  */
1836 1836
 function pdf_getlineremisepercent($object,$i,$outputlangs,$hidedetails=0)
1837 1837
 {
1838
-	global $hookmanager;
1839
-
1840
-	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1841
-
1842
-	$reshook=0;
1843
-	$result='';
1844
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1845
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1846
-	{
1847
-		$special_code = $object->lines[$i]->special_code;
1848
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1849
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1850
-		$action='';
1851
-		$reshook = $hookmanager->executeHooks('pdf_getlineremisepercent',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1852
-
1853
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1854
-	}
1855
-	if (empty($reshook))
1856
-	{
1838
+    global $hookmanager;
1839
+
1840
+    include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1841
+
1842
+    $reshook=0;
1843
+    $result='';
1844
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1845
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1846
+    {
1847
+        $special_code = $object->lines[$i]->special_code;
1848
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1849
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1850
+        $action='';
1851
+        $reshook = $hookmanager->executeHooks('pdf_getlineremisepercent',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1852
+
1853
+        if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1854
+    }
1855
+    if (empty($reshook))
1856
+    {
1857 1857
         if ($object->lines[$i]->special_code == 3) return '';
1858
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=dol_print_reduction($object->lines[$i]->remise_percent,$outputlangs);
1859
-	}
1860
-	return $result;
1858
+        if (empty($hidedetails) || $hidedetails > 1) $result.=dol_print_reduction($object->lines[$i]->remise_percent,$outputlangs);
1859
+    }
1860
+    return $result;
1861 1861
 }
1862 1862
 
1863 1863
 /**
@@ -1872,41 +1872,41 @@  discard block
 block discarded – undo
1872 1872
  */
1873 1873
 function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = null)
1874 1874
 {
1875
-	if (empty($hookmanager)) global $hookmanager;
1876
-	global $conf;
1875
+    if (empty($hookmanager)) global $hookmanager;
1876
+    global $conf;
1877 1877
 
1878
-	$reshook=0;
1878
+    $reshook=0;
1879 1879
     $result='';
1880 1880
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1881
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1882
-	{
1883
-		$special_code = $object->lines[$i]->special_code;
1884
-		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1885
-		$parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code);
1886
-		$action = '';
1887
-		$reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1888
-
1889
-		if(!empty($hookmanager->resPrint)) return $hookmanager->resPrint;
1890
-	}
1891
-	if (empty($reshook))
1892
-	{
1893
-        	if ($object->lines[$i]->special_code == 3) return '';
1894
-		if (empty($hidedetails) || $hidedetails > 1)
1895
-		{
1896
-			if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF)
1897
-			{
1898
-				$prev_progress = 0;
1899
-				if (method_exists($object, 'get_prev_progress'))
1900
-				{
1901
-			 		$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1902
-				}
1903
-			 	$result = ($object->lines[$i]->situation_percent - $prev_progress) . '%';
1904
-			}
1905
-			else
1906
-				$result = $object->lines[$i]->situation_percent . '%';
1907
-	  	}
1908
-	}
1909
-	return $result;
1881
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1882
+    {
1883
+        $special_code = $object->lines[$i]->special_code;
1884
+        if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1885
+        $parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code);
1886
+        $action = '';
1887
+        $reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1888
+
1889
+        if(!empty($hookmanager->resPrint)) return $hookmanager->resPrint;
1890
+    }
1891
+    if (empty($reshook))
1892
+    {
1893
+            if ($object->lines[$i]->special_code == 3) return '';
1894
+        if (empty($hidedetails) || $hidedetails > 1)
1895
+        {
1896
+            if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF)
1897
+            {
1898
+                $prev_progress = 0;
1899
+                if (method_exists($object, 'get_prev_progress'))
1900
+                {
1901
+                        $prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1902
+                }
1903
+                    $result = ($object->lines[$i]->situation_percent - $prev_progress) . '%';
1904
+            }
1905
+            else
1906
+                $result = $object->lines[$i]->situation_percent . '%';
1907
+            }
1908
+    }
1909
+    return $result;
1910 1910
 }
1911 1911
 
1912 1912
 /**
@@ -1920,49 +1920,49 @@  discard block
 block discarded – undo
1920 1920
  */
1921 1921
 function pdf_getlinetotalexcltax($object,$i,$outputlangs,$hidedetails=0)
1922 1922
 {
1923
-	global $conf, $hookmanager;
1924
-
1925
-	$sign=1;
1926
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1927
-
1928
-	$reshook=0;
1929
-	$result='';
1930
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1931
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1932
-	{
1933
-		$special_code = $object->lines[$i]->special_code;
1934
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1935
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code, 'sign'=>$sign);
1936
-		$action='';
1937
-		$reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1938
-
1939
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1940
-	}
1923
+    global $conf, $hookmanager;
1924
+
1925
+    $sign=1;
1926
+    if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1927
+
1928
+    $reshook=0;
1929
+    $result='';
1930
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1931
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1932
+    {
1933
+        $special_code = $object->lines[$i]->special_code;
1934
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1935
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code, 'sign'=>$sign);
1936
+        $action='';
1937
+        $reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1938
+
1939
+        if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1940
+    }
1941 1941
     if (empty($reshook))
1942 1942
     {
1943
-	    if ($object->lines[$i]->special_code == 3)
1944
-    	{
1945
-    		return $outputlangs->transnoentities("Option");
1946
-    	}
1943
+        if ($object->lines[$i]->special_code == 3)
1944
+        {
1945
+            return $outputlangs->transnoentities("Option");
1946
+        }
1947 1947
         if (empty($hidedetails) || $hidedetails > 1)
1948 1948
         {
1949
-        	$total_ht = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht);
1950
-        	if ($object->lines[$i]->situation_percent > 0)
1951
-        	{
1952
-        		$prev_progress = 0;
1953
-        		$progress = 1;
1954
-        		if (method_exists($object->lines[$i], 'get_prev_progress'))
1955
-        		{
1956
-					$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1957
-					$progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100;
1958
-        		}
1959
-				$result.=price($sign * ($total_ht/($object->lines[$i]->situation_percent/100)) * $progress, 0, $outputlangs);
1960
-        	}
1961
-        	else
1962
-			$result.=price($sign * $total_ht, 0, $outputlangs);
1963
-	}
1964
-    }
1965
-	return $result;
1949
+            $total_ht = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht);
1950
+            if ($object->lines[$i]->situation_percent > 0)
1951
+            {
1952
+                $prev_progress = 0;
1953
+                $progress = 1;
1954
+                if (method_exists($object->lines[$i], 'get_prev_progress'))
1955
+                {
1956
+                    $prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1957
+                    $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100;
1958
+                }
1959
+                $result.=price($sign * ($total_ht/($object->lines[$i]->situation_percent/100)) * $progress, 0, $outputlangs);
1960
+            }
1961
+            else
1962
+            $result.=price($sign * $total_ht, 0, $outputlangs);
1963
+    }
1964
+    }
1965
+    return $result;
1966 1966
 }
1967 1967
 
1968 1968
 /**
@@ -1976,33 +1976,33 @@  discard block
 block discarded – undo
1976 1976
  */
1977 1977
 function pdf_getlinetotalwithtax($object,$i,$outputlangs,$hidedetails=0)
1978 1978
 {
1979
-	global $hookmanager,$conf;
1980
-
1981
-	$sign=1;
1982
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1983
-
1984
-	$reshook=0;
1985
-	$result='';
1986
-	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1987
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1988
-	{
1989
-		$special_code = $object->lines[$i]->special_code;
1990
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1991
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1992
-		$action='';
1993
-		$reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1994
-
1995
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1996
-	}
1997
-	if (empty($reshook))
1998
-	{
1999
-		if ($object->lines[$i]->special_code == 3)
2000
-    	{
2001
-    		$result.=$outputlangs->transnoentities("Option");
2002
-    	}
2003
-		elseif (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht)*($object->lines[$i]->tva_tx)/100, 0, $outputlangs);
2004
-	}
2005
-	return $result;
1979
+    global $hookmanager,$conf;
1980
+
1981
+    $sign=1;
1982
+    if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1983
+
1984
+    $reshook=0;
1985
+    $result='';
1986
+    //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1987
+    if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1988
+    {
1989
+        $special_code = $object->lines[$i]->special_code;
1990
+        if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1991
+        $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1992
+        $action='';
1993
+        $reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1994
+
1995
+        if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1996
+    }
1997
+    if (empty($reshook))
1998
+    {
1999
+        if ($object->lines[$i]->special_code == 3)
2000
+        {
2001
+            $result.=$outputlangs->transnoentities("Option");
2002
+        }
2003
+        elseif (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht)*($object->lines[$i]->tva_tx)/100, 0, $outputlangs);
2004
+    }
2005
+    return $result;
2006 2006
 }
2007 2007
 
2008 2008
 /**
@@ -2016,41 +2016,41 @@  discard block
 block discarded – undo
2016 2016
  */
2017 2017
 function pdf_getTotalQty($object,$type,$outputlangs)
2018 2018
 {
2019
-	global $hookmanager;
2020
-
2021
-	$total=0;
2022
-	$nblignes=count($object->lines);
2023
-
2024
-	// Loop on each lines
2025
-	for ($i = 0 ; $i < $nblignes ; $i++)
2026
-	{
2027
-		if ($object->lines[$i]->special_code != 3)
2028
-		{
2029
-			if ($type=='all')
2030
-			{
2031
-				$total += $object->lines[$i]->qty;
2032
-			}
2033
-			else if ($type==9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line)))
2034
-			{
2035
-				$special_code = $object->lines[$i]->special_code;
2036
-				if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2037
-				$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
2038
-				$action='';
2039
-				$reshook = $hookmanager->executeHooks('pdf_getTotalQty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2040
-				return $hookmanager->resPrint;
2041
-			}
2042
-			else if ($type==0 && $object->lines[$i]->product_type == 0)
2043
-			{
2044
-				$total += $object->lines[$i]->qty;
2045
-			}
2046
-			else if ($type==1 && $object->lines[$i]->product_type == 1)
2047
-			{
2048
-				$total += $object->lines[$i]->qty;
2049
-			}
2050
-		}
2051
-	}
2052
-
2053
-	return $total;
2019
+    global $hookmanager;
2020
+
2021
+    $total=0;
2022
+    $nblignes=count($object->lines);
2023
+
2024
+    // Loop on each lines
2025
+    for ($i = 0 ; $i < $nblignes ; $i++)
2026
+    {
2027
+        if ($object->lines[$i]->special_code != 3)
2028
+        {
2029
+            if ($type=='all')
2030
+            {
2031
+                $total += $object->lines[$i]->qty;
2032
+            }
2033
+            else if ($type==9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line)))
2034
+            {
2035
+                $special_code = $object->lines[$i]->special_code;
2036
+                if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2037
+                $parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
2038
+                $action='';
2039
+                $reshook = $hookmanager->executeHooks('pdf_getTotalQty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2040
+                return $hookmanager->resPrint;
2041
+            }
2042
+            else if ($type==0 && $object->lines[$i]->product_type == 0)
2043
+            {
2044
+                $total += $object->lines[$i]->qty;
2045
+            }
2046
+            else if ($type==1 && $object->lines[$i]->product_type == 1)
2047
+            {
2048
+                $total += $object->lines[$i]->qty;
2049
+            }
2050
+        }
2051
+    }
2052
+
2053
+    return $total;
2054 2054
 }
2055 2055
 
2056 2056
 /**
@@ -2063,97 +2063,97 @@  discard block
 block discarded – undo
2063 2063
  */
2064 2064
 function pdf_getLinkedObjects($object,$outputlangs)
2065 2065
 {
2066
-	global $hookmanager;
2067
-
2068
-	$linkedobjects=array();
2069
-
2070
-	$object->fetchObjectLinked();
2071
-
2072
-	foreach($object->linkedObjects as $objecttype => $objects)
2073
-	{
2074
-	    if ($objecttype == 'facture')
2075
-	    {
2076
-	       // For invoice, we don't want to have a reference line on document. Image we are using recuring invoice, we will have a line longer than document width.
2077
-	    }
2078
-	    elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal')
2079
-		{
2080
-			$outputlangs->load('propal');
2081
-
2082
-			foreach($objects as $elementobject)
2083
-			{
2084
-				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefProposal");
2085
-				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
2086
-				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal");
2087
-				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2088
-			}
2089
-		}
2090
-		else if ($objecttype == 'commande' || $objecttype == 'supplier_order')
2091
-		{
2092
-			$outputlangs->load('orders');
2093
-			foreach($objects as $elementobject)
2094
-			{
2095
-				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder");
2096
-				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref) . ($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '') . ($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : '');
2097
-				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate");
2098
-				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2099
-			}
2100
-		}
2101
-		else if ($objecttype == 'contrat')
2102
-		{
2103
-			$outputlangs->load('contracts');
2104
-			foreach($objects as $elementobject)
2105
-			{
2106
-				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefContract");
2107
-				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
2108
-				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract");
2109
-				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat,'day','',$outputlangs);
2110
-			}
2111
-		}
2112
-		else if ($objecttype == 'shipping')
2113
-		{
2114
-			$outputlangs->loadLangs(array("orders", "sendings"));
2115
-
2116
-			foreach($objects as $x => $elementobject)
2117
-			{
2118
-			    $order=null;
2119
-			    // We concat this record info into fields xxx_value. title is overwrote.
2120
-			    if (empty($object->linkedObjects['commande']) && $object->element != 'commande')	// There is not already a link to order and object is not the order, so we show also info with order
2121
-			    {
2122
-			        $elementobject->fetchObjectLinked();
2123
-			        if (! empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']);
2124
-			    }
2125
-			    if (! is_object($order))
2126
-			    {
2127
-			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending");
2128
-			        if (! empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'].=' / ';
2129
-			        $linkedobjects[$objecttype]['ref_value'].= $outputlangs->transnoentities($elementobject->ref);
2130
-			        //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment");
2131
-			        //if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / ';
2132
-			        //$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs);
2133
-			    }
2134
-			    else
2135
-			    {
2136
-			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder") . ' / ' . $outputlangs->transnoentities("RefSending");
2137
-			        if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref) . ($order->ref_client ? ' ('.$order->ref_client.')' : '');
2138
-			        $linkedobjects[$objecttype]['ref_value'].= ' / ' . $outputlangs->transnoentities($elementobject->ref);
2139
-			        //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : '');
2140
-			        //if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs);
2141
-			        //$linkedobjects[$objecttype]['date_value'].= ($elementobject->date_delivery ? ' / ' . dol_print_date($elementobject->date_delivery,'day','',$outputlangs) : '');
2142
-			    }
2143
-			}
2144
-		}
2145
-	}
2146
-
2147
-	// For add external linked objects
2148
-	if (is_object($hookmanager))
2149
-	{
2150
-		$parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs);
2151
-		$action='';
2152
-		$hookmanager->executeHooks('pdf_getLinkedObjects',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2153
-		if (! empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray;
2154
-	}
2155
-
2156
-	return $linkedobjects;
2066
+    global $hookmanager;
2067
+
2068
+    $linkedobjects=array();
2069
+
2070
+    $object->fetchObjectLinked();
2071
+
2072
+    foreach($object->linkedObjects as $objecttype => $objects)
2073
+    {
2074
+        if ($objecttype == 'facture')
2075
+        {
2076
+            // For invoice, we don't want to have a reference line on document. Image we are using recuring invoice, we will have a line longer than document width.
2077
+        }
2078
+        elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal')
2079
+        {
2080
+            $outputlangs->load('propal');
2081
+
2082
+            foreach($objects as $elementobject)
2083
+            {
2084
+                $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefProposal");
2085
+                $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
2086
+                $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal");
2087
+                $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2088
+            }
2089
+        }
2090
+        else if ($objecttype == 'commande' || $objecttype == 'supplier_order')
2091
+        {
2092
+            $outputlangs->load('orders');
2093
+            foreach($objects as $elementobject)
2094
+            {
2095
+                $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder");
2096
+                $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref) . ($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '') . ($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : '');
2097
+                $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate");
2098
+                $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2099
+            }
2100
+        }
2101
+        else if ($objecttype == 'contrat')
2102
+        {
2103
+            $outputlangs->load('contracts');
2104
+            foreach($objects as $elementobject)
2105
+            {
2106
+                $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefContract");
2107
+                $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
2108
+                $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract");
2109
+                $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat,'day','',$outputlangs);
2110
+            }
2111
+        }
2112
+        else if ($objecttype == 'shipping')
2113
+        {
2114
+            $outputlangs->loadLangs(array("orders", "sendings"));
2115
+
2116
+            foreach($objects as $x => $elementobject)
2117
+            {
2118
+                $order=null;
2119
+                // We concat this record info into fields xxx_value. title is overwrote.
2120
+                if (empty($object->linkedObjects['commande']) && $object->element != 'commande')	// There is not already a link to order and object is not the order, so we show also info with order
2121
+                {
2122
+                    $elementobject->fetchObjectLinked();
2123
+                    if (! empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']);
2124
+                }
2125
+                if (! is_object($order))
2126
+                {
2127
+                    $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending");
2128
+                    if (! empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'].=' / ';
2129
+                    $linkedobjects[$objecttype]['ref_value'].= $outputlangs->transnoentities($elementobject->ref);
2130
+                    //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment");
2131
+                    //if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / ';
2132
+                    //$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs);
2133
+                }
2134
+                else
2135
+                {
2136
+                    $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder") . ' / ' . $outputlangs->transnoentities("RefSending");
2137
+                    if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref) . ($order->ref_client ? ' ('.$order->ref_client.')' : '');
2138
+                    $linkedobjects[$objecttype]['ref_value'].= ' / ' . $outputlangs->transnoentities($elementobject->ref);
2139
+                    //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : '');
2140
+                    //if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs);
2141
+                    //$linkedobjects[$objecttype]['date_value'].= ($elementobject->date_delivery ? ' / ' . dol_print_date($elementobject->date_delivery,'day','',$outputlangs) : '');
2142
+                }
2143
+            }
2144
+        }
2145
+    }
2146
+
2147
+    // For add external linked objects
2148
+    if (is_object($hookmanager))
2149
+    {
2150
+        $parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs);
2151
+        $action='';
2152
+        $hookmanager->executeHooks('pdf_getLinkedObjects',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2153
+        if (! empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray;
2154
+    }
2155
+
2156
+    return $linkedobjects;
2157 2157
 }
2158 2158
 
2159 2159
 /**
@@ -2165,24 +2165,24 @@  discard block
 block discarded – undo
2165 2165
  */
2166 2166
 function pdf_getSizeForImage($realpath)
2167 2167
 {
2168
-	global $conf;
2169
-
2170
-	$maxwidth=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);
2171
-	$maxheight=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT)?32:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT);
2172
-	include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2173
-	$tmp=dol_getImageSize($realpath);
2174
-	if ($tmp['height'])
2175
-	{
2176
-		$width=(int) round($maxheight*$tmp['width']/$tmp['height']);	// I try to use maxheight
2177
-		if ($width > $maxwidth)	// Pb with maxheight, so i use maxwidth
2178
-		{
2179
-			$width=$maxwidth;
2180
-			$height=(int) round($maxwidth*$tmp['height']/$tmp['width']);
2181
-		}
2182
-		else	// No pb with maxheight
2183
-		{
2184
-			$height=$maxheight;
2185
-		}
2186
-	}
2187
-	return array('width'=>$width,'height'=>$height);
2168
+    global $conf;
2169
+
2170
+    $maxwidth=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);
2171
+    $maxheight=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT)?32:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT);
2172
+    include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2173
+    $tmp=dol_getImageSize($realpath);
2174
+    if ($tmp['height'])
2175
+    {
2176
+        $width=(int) round($maxheight*$tmp['width']/$tmp['height']);	// I try to use maxheight
2177
+        if ($width > $maxwidth)	// Pb with maxheight, so i use maxwidth
2178
+        {
2179
+            $width=$maxwidth;
2180
+            $height=(int) round($maxwidth*$tmp['height']/$tmp['width']);
2181
+        }
2182
+        else	// No pb with maxheight
2183
+        {
2184
+            $height=$maxheight;
2185
+        }
2186
+    }
2187
+    return array('width'=>$width,'height'=>$height);
2188 2188
 }
Please login to merge, or discard this patch.
Spacing   +576 added lines, -576 removed lines patch added patch discarded remove patch
@@ -41,34 +41,34 @@  discard block
 block discarded – undo
41 41
  */
42 42
 function pdf_getFormat(Translate $outputlangs = null)
43 43
 {
44
-	global $conf,$db;
44
+	global $conf, $db;
45 45
 
46 46
 	// Default value if setup was not done and/or entry into c_paper_format not defined
47
-	$width=210; $height=297; $unit='mm';
47
+	$width = 210; $height = 297; $unit = 'mm';
48 48
 
49 49
 	if (empty($conf->global->MAIN_PDF_FORMAT))
50 50
 	{
51 51
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
52
-		$pdfformat=dol_getDefaultFormat($outputlangs);
52
+		$pdfformat = dol_getDefaultFormat($outputlangs);
53 53
 	}
54
-	else $pdfformat=$conf->global->MAIN_PDF_FORMAT;
54
+	else $pdfformat = $conf->global->MAIN_PDF_FORMAT;
55 55
 
56
-	$sql="SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format";
57
-	$sql.=" WHERE code = '".$pdfformat."'";
58
-	$resql=$db->query($sql);
56
+	$sql = "SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format";
57
+	$sql .= " WHERE code = '".$pdfformat."'";
58
+	$resql = $db->query($sql);
59 59
 	if ($resql)
60 60
 	{
61
-		$obj=$db->fetch_object($resql);
61
+		$obj = $db->fetch_object($resql);
62 62
 		if ($obj)
63 63
 		{
64
-			$width=(int) $obj->width;
65
-			$height=(int) $obj->height;
66
-			$unit=$obj->unit;
64
+			$width = (int) $obj->width;
65
+			$height = (int) $obj->height;
66
+			$unit = $obj->unit;
67 67
 		}
68 68
 	}
69 69
 
70 70
 	//print "pdfformat=".$pdfformat." width=".$width." height=".$height." unit=".$unit;
71
-	return array('width'=>$width,'height'=>$height,'unit'=>$unit);
71
+	return array('width'=>$width, 'height'=>$height, 'unit'=>$unit);
72 72
 }
73 73
 
74 74
 /**
@@ -79,14 +79,14 @@  discard block
 block discarded – undo
79 79
  *      @param  string		$pagetype       'P' or 'l'
80 80
  *      @return TCPDF						PDF object
81 81
  */
82
-function pdf_getInstance($format='',$metric='mm',$pagetype='P')
82
+function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P')
83 83
 {
84 84
 	global $conf;
85 85
 
86 86
 	// Define constant for TCPDF
87
-	if (! defined('K_TCPDF_EXTERNAL_CONFIG'))
87
+	if (!defined('K_TCPDF_EXTERNAL_CONFIG'))
88 88
 	{
89
-		define('K_TCPDF_EXTERNAL_CONFIG',1);	// this avoid using tcpdf_config file
89
+		define('K_TCPDF_EXTERNAL_CONFIG', 1); // this avoid using tcpdf_config file
90 90
 		define('K_PATH_CACHE', DOL_DATA_ROOT.'/admin/temp/');
91 91
 		define('K_PATH_URL_CACHE', DOL_DATA_ROOT.'/admin/temp/');
92 92
 		dol_mkdir(K_PATH_CACHE);
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 		define('HEAD_MAGNIFICATION', 1.1);
114 114
 		define('K_CELL_HEIGHT_RATIO', 1.25);
115 115
 		define('K_TITLE_MAGNIFICATION', 1.3);
116
-		define('K_SMALL_RATIO', 2/3);
116
+		define('K_SMALL_RATIO', 2 / 3);
117 117
 		define('K_THAI_TOPCHARS', true);
118 118
 		define('K_TCPDF_CALLS_IN_HTML', true);
119 119
 		define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
@@ -129,14 +129,14 @@  discard block
 block discarded – undo
129 129
 	//$format=array($arrayformat['width'],$arrayformat['height']);
130 130
 	//$metric=$arrayformat['unit'];
131 131
 
132
-	$pdfa=false;											// PDF-1.3
133
-	if (! empty($conf->global->PDF_USE_1A)) $pdfa=true;		// PDF1/A
132
+	$pdfa = false; // PDF-1.3
133
+	if (!empty($conf->global->PDF_USE_1A)) $pdfa = true; // PDF1/A
134 134
 
135
-	if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
136
-	else $pdf = new TCPDF($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
135
+	if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa);
136
+	else $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa);
137 137
 
138 138
 	// Protection and encryption of pdf
139
-	if (! empty($conf->global->PDF_SECURITY_ENCRYPTION))
139
+	if (!empty($conf->global->PDF_SECURITY_ENCRYPTION))
140 140
 	{
141 141
 		/* Permission supported by TCPDF
142 142
 		- print : Print the document;
@@ -151,22 +151,22 @@  discard block
 block discarded – undo
151 151
 		*/
152 152
 
153 153
 		// For TCPDF, we specify permission we want to block
154
-		$pdfrights = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS, true):array('modify','copy')); // Json format in llx_const
154
+		$pdfrights = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS) ?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS, true) : array('modify', 'copy')); // Json format in llx_const
155 155
 
156 156
 		// Password for the end user
157
-		$pdfuserpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_USERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_USERPASS:'');
157
+		$pdfuserpass = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_USERPASS) ? $conf->global->PDF_SECURITY_ENCRYPTION_USERPASS : '');
158 158
 
159 159
 		// Password of the owner, created randomly if not defined
160
-		$pdfownerpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS:null);
160
+		$pdfownerpass = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS) ? $conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS : null);
161 161
 
162 162
 		// For encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit
163
-		$encstrength = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH)?$conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH:0);
163
+		$encstrength = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH) ? $conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH : 0);
164 164
 
165 165
 		// Array of recipients containing public-key certificates ('c') and permissions ('p').
166 166
 		// For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
167
-		$pubkeys = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS, true):null); // Json format in llx_const
167
+		$pubkeys = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS) ?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS, true) : null); // Json format in llx_const
168 168
 
169
-		$pdf->SetProtection($pdfrights,$pdfuserpass,$pdfownerpass,$encstrength,$pubkeys);
169
+		$pdf->SetProtection($pdfrights, $pdfuserpass, $pdfownerpass, $encstrength, $pubkeys);
170 170
 	}
171 171
 
172 172
 	return $pdf;
@@ -202,14 +202,14 @@  discard block
 block discarded – undo
202 202
 {
203 203
 	global $conf;
204 204
 
205
-	if (! empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT;
205
+	if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT;
206 206
 
207
-	$font='Helvetica'; // By default, for FPDI, or ISO language on TCPDF
207
+	$font = 'Helvetica'; // By default, for FPDI, or ISO language on TCPDF
208 208
 	if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
209 209
 	{
210
-		if ($outputlangs->trans('FONTFORPDF')!='FONTFORPDF')
210
+		if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF')
211 211
 		{
212
-			$font=$outputlangs->trans('FONTFORPDF');
212
+			$font = $outputlangs->trans('FONTFORPDF');
213 213
 		}
214 214
 	}
215 215
 	return $font;
@@ -223,10 +223,10 @@  discard block
 block discarded – undo
223 223
  */
224 224
 function pdf_getPDFFontSize($outputlangs)
225 225
 {
226
-	$size=10;                   // By default, for FPDI or ISO language on TCPDF
226
+	$size = 10; // By default, for FPDI or ISO language on TCPDF
227 227
 	if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
228 228
 	{
229
-		if ($outputlangs->trans('FONTSIZEFORPDF')!='FONTSIZEFORPDF')
229
+		if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF')
230 230
 		{
231 231
 			$size = (int) $outputlangs->trans('FONTSIZEFORPDF');
232 232
 		}
@@ -245,14 +245,14 @@  discard block
 block discarded – undo
245 245
 function pdf_getHeightForLogo($logo, $url = false)
246 246
 {
247 247
 	global $conf;
248
-	$height=(empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT)?22:$conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT);
249
-	$maxwidth=130;
248
+	$height = (empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT) ? 22 : $conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT);
249
+	$maxwidth = 130;
250 250
 	include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
251
-	$tmp=dol_getImageSize($logo, $url);
251
+	$tmp = dol_getImageSize($logo, $url);
252 252
 	if ($tmp['height'])
253 253
 	{
254
-		$width=round($height*$tmp['width']/$tmp['height']);
255
-		if ($width > $maxwidth) $height=$height*$maxwidth/$width;
254
+		$width = round($height * $tmp['width'] / $tmp['height']);
255
+		if ($width > $maxwidth) $height = $height * $maxwidth / $width;
256 256
 	}
257 257
 	//print $tmp['width'].' '.$tmp['height'].' '.$width; exit;
258 258
 	return $height;
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
     //var_dump($start_y);
276 276
     $start_page = $pdf->getPage();
277 277
     // call printing functions with content
278
-    $pdf->writeHTMLCell(0, 0, 0, $start_y, $htmlcontent, 0, 1, false, true, 'J',true);
278
+    $pdf->writeHTMLCell(0, 0, 0, $start_y, $htmlcontent, 0, 1, false, true, 'J', true);
279 279
     // get the new Y
280 280
     $end_y = $pdf->GetY();
281 281
     $end_page = $pdf->getPage();
@@ -286,9 +286,9 @@  discard block
 block discarded – undo
286 286
     }
287 287
     else
288 288
     {
289
-        for ($page=$start_page; $page <= $end_page; ++$page) {
289
+        for ($page = $start_page; $page <= $end_page; ++$page) {
290 290
         	$pdf->setPage($page);
291
-        	$tmpm=$pdf->getMargins();
291
+        	$tmpm = $pdf->getMargins();
292 292
         	$tMargin = $tmpm['top'];
293 293
         	if ($page == $start_page) {
294 294
         		// first page
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
  * @param   int                 $includealias   1=Include alias name after name
317 317
  * @return  string                              String with name of thirdparty (+ alias if requested)
318 318
  */
319
-function pdfBuildThirdpartyName($thirdparty, Translate $outputlangs, $includealias=0)
319
+function pdfBuildThirdpartyName($thirdparty, Translate $outputlangs, $includealias = 0)
320 320
 {
321 321
     global $conf;
322 322
 
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 
326 326
 	if ($thirdparty instanceof Societe) {
327 327
 		$socname .= $thirdparty->name;
328
-		if (($includealias || ! empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) {
328
+		if (($includealias || !empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) {
329 329
 		    $socname .= "\n".$thirdparty->name_alias;
330 330
 		}
331 331
 	} elseif ($thirdparty instanceof Contact) {
@@ -350,28 +350,28 @@  discard block
 block discarded – undo
350 350
  *      @param  Object      $object             Object we want to build document for
351 351
  * 		@return	string							String with full address
352 352
  */
353
-function pdf_build_address($outputlangs,$sourcecompany,$targetcompany='',$targetcontact='',$usecontact=0,$mode='source',$object=null)
353
+function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $targetcontact = '', $usecontact = 0, $mode = 'source', $object = null)
354 354
 {
355 355
 	global $conf, $hookmanager;
356 356
 
357
-	if ($mode == 'source' && ! is_object($sourcecompany)) return -1;
358
-	if ($mode == 'target' && ! is_object($targetcompany)) return -1;
357
+	if ($mode == 'source' && !is_object($sourcecompany)) return -1;
358
+	if ($mode == 'target' && !is_object($targetcompany)) return -1;
359 359
 
360
-	if (! empty($sourcecompany->state_id) && empty($sourcecompany->departement)) $sourcecompany->departement=getState($sourcecompany->state_id); //TODO deprecated
361
-	if (! empty($sourcecompany->state_id) && empty($sourcecompany->state))       $sourcecompany->state=getState($sourcecompany->state_id);
362
-	if (! empty($sourcecompany->state_id) && !isset($sourcecompany->departement_id))   $sourcecompany->departement_id=getState($sourcecompany->state_id,'2');
363
-	if (! empty($targetcompany->state_id) && empty($targetcompany->departement)) $targetcompany->departement=getState($targetcompany->state_id); //TODO deprecated
364
-	if (! empty($targetcompany->state_id) && empty($targetcompany->state))       $targetcompany->state=getState($targetcompany->state_id);
365
-	if (! empty($targetcompany->state_id) && !isset($targetcompany->departement_id))   $targetcompany->departement_id=getState($targetcompany->state_id,'2');
360
+	if (!empty($sourcecompany->state_id) && empty($sourcecompany->departement)) $sourcecompany->departement = getState($sourcecompany->state_id); //TODO deprecated
361
+	if (!empty($sourcecompany->state_id) && empty($sourcecompany->state))       $sourcecompany->state = getState($sourcecompany->state_id);
362
+	if (!empty($sourcecompany->state_id) && !isset($sourcecompany->departement_id))   $sourcecompany->departement_id = getState($sourcecompany->state_id, '2');
363
+	if (!empty($targetcompany->state_id) && empty($targetcompany->departement)) $targetcompany->departement = getState($targetcompany->state_id); //TODO deprecated
364
+	if (!empty($targetcompany->state_id) && empty($targetcompany->state))       $targetcompany->state = getState($targetcompany->state_id);
365
+	if (!empty($targetcompany->state_id) && !isset($targetcompany->departement_id))   $targetcompany->departement_id = getState($targetcompany->state_id, '2');
366 366
 
367
-	$reshook=0;
367
+	$reshook = 0;
368 368
 	$stringaddress = '';
369 369
 	if (is_object($hookmanager))
370 370
 	{
371
-		$parameters = array('sourcecompany'=>&$sourcecompany,'targetcompany'=>&$targetcompany,'targetcontact'=>$targetcontact,'outputlangs'=>$outputlangs,'mode'=>$mode,'usecontact'=>$usecontact);
372
-		$action='';
373
-		$reshook = $hookmanager->executeHooks('pdf_build_address',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
374
-		$stringaddress.=$hookmanager->resPrint;
371
+		$parameters = array('sourcecompany'=>&$sourcecompany, 'targetcompany'=>&$targetcompany, 'targetcontact'=>$targetcontact, 'outputlangs'=>$outputlangs, 'mode'=>$mode, 'usecontact'=>$usecontact);
372
+		$action = '';
373
+		$reshook = $hookmanager->executeHooks('pdf_build_address', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
374
+		$stringaddress .= $hookmanager->resPrint;
375 375
 	}
376 376
 	if (empty($reshook))
377 377
 	{
@@ -380,71 +380,71 @@  discard block
 block discarded – undo
380 380
     		$withCountry = 0;
381 381
     		if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1;
382 382
 
383
-    		$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n";
383
+    		$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n";
384 384
 
385 385
     		if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS))
386 386
     		{
387 387
     			// Phone
388
-    			if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
388
+    			if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
389 389
     			// Fax
390
-    			if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
390
+    			if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
391 391
     			// EMail
392
-    			if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
392
+    			if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
393 393
     			// Web
394
-    			if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
394
+    			if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
395 395
     		}
396 396
     		// Intra VAT
397
-    		if (! empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS))
397
+    		if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS))
398 398
     		{
399
-    			if ($sourcecompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
399
+    			if ($sourcecompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
400 400
     		}
401 401
     		// Professionnal Ids
402
-    		if (! empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof1))
402
+    		if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1))
403 403
     		{
404
-    			$tmp=$outputlangs->transcountrynoentities("ProfId1",$sourcecompany->country_code);
405
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
406
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1);
404
+    			$tmp = $outputlangs->transcountrynoentities("ProfId1", $sourcecompany->country_code);
405
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
406
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1);
407 407
     		}
408
-    		if (! empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof2))
408
+    		if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2))
409 409
     		{
410
-    			$tmp=$outputlangs->transcountrynoentities("ProfId2",$sourcecompany->country_code);
411
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
412
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2);
410
+    			$tmp = $outputlangs->transcountrynoentities("ProfId2", $sourcecompany->country_code);
411
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
412
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2);
413 413
     		}
414
-    		if (! empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof3))
414
+    		if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3))
415 415
     		{
416
-    			$tmp=$outputlangs->transcountrynoentities("ProfId3",$sourcecompany->country_code);
417
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
418
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3);
416
+    			$tmp = $outputlangs->transcountrynoentities("ProfId3", $sourcecompany->country_code);
417
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
418
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3);
419 419
     		}
420
-    		if (! empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof4))
420
+    		if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4))
421 421
     		{
422
-    			$tmp=$outputlangs->transcountrynoentities("ProfId4",$sourcecompany->country_code);
423
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
424
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4);
422
+    			$tmp = $outputlangs->transcountrynoentities("ProfId4", $sourcecompany->country_code);
423
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
424
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4);
425 425
     		}
426
-    		if (! empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof5))
426
+    		if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5))
427 427
     		{
428
-    			$tmp=$outputlangs->transcountrynoentities("ProfId5",$sourcecompany->country_code);
429
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
430
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5);
428
+    			$tmp = $outputlangs->transcountrynoentities("ProfId5", $sourcecompany->country_code);
429
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
430
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5);
431 431
     		}
432
-    		if (! empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof6))
432
+    		if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6))
433 433
     		{
434
-    			$tmp=$outputlangs->transcountrynoentities("ProfId6",$sourcecompany->country_code);
435
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
436
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6);
434
+    			$tmp = $outputlangs->transcountrynoentities("ProfId6", $sourcecompany->country_code);
435
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
436
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6);
437 437
     		}
438 438
     	}
439 439
 
440
-    	if ($mode == 'target' || preg_match('/targetwithdetails/',$mode))
440
+    	if ($mode == 'target' || preg_match('/targetwithdetails/', $mode))
441 441
     	{
442 442
     		if ($usecontact)
443 443
     		{
444
-    			$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs,1));
444
+    			$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1));
445 445
 
446 446
     			if (!empty($targetcontact->address)) {
447
-    				$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcontact));
447
+    				$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcontact));
448 448
     			} else {
449 449
     				$companytouseforaddress = $targetcompany;
450 450
 
@@ -455,73 +455,73 @@  discard block
 block discarded – undo
455 455
 						$companytouseforaddress = $targetcontact->thirdparty;
456 456
 					}
457 457
 
458
-					$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress));
458
+					$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress));
459 459
 				}
460 460
     			// Country
461 461
     			if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) {
462
-    				$stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code));
462
+    				$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code));
463 463
     			}
464 464
     			else if (empty($targetcontact->country_code) && !empty($targetcompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
465
-    				$stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
465
+    				$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
466 466
     			}
467 467
 
468
-    			if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
468
+    			if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode))
469 469
     			{
470 470
     				// Phone
471
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
471
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode))
472 472
     			    {
473
-        				if (! empty($targetcontact->phone_pro) || ! empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
474
-        				if (! empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
475
-        				if (! empty($targetcontact->phone_pro) && ! empty($targetcontact->phone_mobile)) $stringaddress .= " / ";
476
-        				if (! empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
473
+        				if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": ";
474
+        				if (!empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
475
+        				if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) $stringaddress .= " / ";
476
+        				if (!empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
477 477
     			    }
478 478
     				// Fax
479
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
479
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode))
480 480
     			    {
481
-                        if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
481
+                        if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
482 482
     			    }
483 483
     				// EMail
484
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
484
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode))
485 485
     			    {
486
-                        if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
486
+                        if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
487 487
     			    }
488 488
     				// Web
489
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
489
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode))
490 490
     			    {
491
-                        if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
491
+                        if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
492 492
     			    }
493 493
     			}
494 494
     		}
495 495
     		else
496 496
     		{
497
-    			$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcompany));
497
+    			$stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcompany));
498 498
     			// Country
499
-    			if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
499
+    			if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
500 500
 
501
-    			if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
501
+    			if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode))
502 502
     			{
503 503
     				// Phone
504
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
504
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode))
505 505
     			    {
506
-    			    	if (! empty($targetcompany->phone) || ! empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
507
-	    				if (! empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
508
-    					if (! empty($targetcompany->phone) && ! empty($targetcompany->phone_mobile)) $stringaddress .= " / ";
509
-    					if (! empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
506
+    			    	if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": ";
507
+	    				if (!empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
508
+    					if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) $stringaddress .= " / ";
509
+    					if (!empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
510 510
     			    }
511 511
     				// Fax
512
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
512
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode))
513 513
     			    {
514
-    			    	if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
514
+    			    	if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
515 515
     			    }
516 516
     				// EMail
517
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
517
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode))
518 518
     			    {
519
-    			    	if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
519
+    			    	if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
520 520
     			    }
521 521
     				// Web
522
-    			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
522
+    			    if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode))
523 523
     			    {
524
-    			    	if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
524
+    			    	if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
525 525
     			    }
526 526
     			}
527 527
     		}
@@ -529,57 +529,57 @@  discard block
 block discarded – undo
529 529
     		// Intra VAT
530 530
     		if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS))
531 531
     		{
532
-    			if ($targetcompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
532
+    			if ($targetcompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
533 533
     		}
534 534
 
535 535
     		// Professionnal Ids
536
-    		if (! empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && ! empty($targetcompany->idprof1))
536
+    		if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1))
537 537
     		{
538
-    			$tmp=$outputlangs->transcountrynoentities("ProfId1",$targetcompany->country_code);
539
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
540
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1);
538
+    			$tmp = $outputlangs->transcountrynoentities("ProfId1", $targetcompany->country_code);
539
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
540
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1);
541 541
     		}
542
-    		if (! empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && ! empty($targetcompany->idprof2))
542
+    		if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2))
543 543
     		{
544
-    			$tmp=$outputlangs->transcountrynoentities("ProfId2",$targetcompany->country_code);
545
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
546
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2);
544
+    			$tmp = $outputlangs->transcountrynoentities("ProfId2", $targetcompany->country_code);
545
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
546
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2);
547 547
     		}
548
-    		if (! empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && ! empty($targetcompany->idprof3))
548
+    		if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3))
549 549
     		{
550
-    			$tmp=$outputlangs->transcountrynoentities("ProfId3",$targetcompany->country_code);
551
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
552
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3);
550
+    			$tmp = $outputlangs->transcountrynoentities("ProfId3", $targetcompany->country_code);
551
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
552
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3);
553 553
     		}
554
-    		if (! empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && ! empty($targetcompany->idprof4))
554
+    		if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4))
555 555
     		{
556
-    			$tmp=$outputlangs->transcountrynoentities("ProfId4",$targetcompany->country_code);
557
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
558
-    			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4);
556
+    			$tmp = $outputlangs->transcountrynoentities("ProfId4", $targetcompany->country_code);
557
+    			if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
558
+    			$stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4);
559 559
     		}
560
-    		if (! empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && ! empty($targetcompany->idprof5))
560
+    		if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5))
561 561
     		{
562
-    		    $tmp=$outputlangs->transcountrynoentities("ProfId5",$targetcompany->country_code);
563
-    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
564
-    		    $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5);
562
+    		    $tmp = $outputlangs->transcountrynoentities("ProfId5", $targetcompany->country_code);
563
+    		    if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
564
+    		    $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5);
565 565
     		}
566
-    		if (! empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && ! empty($targetcompany->idprof6))
566
+    		if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6))
567 567
     		{
568
-    		    $tmp=$outputlangs->transcountrynoentities("ProfId6",$targetcompany->country_code);
569
-    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
570
-    		    $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6);
568
+    		    $tmp = $outputlangs->transcountrynoentities("ProfId6", $targetcompany->country_code);
569
+    		    if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1];
570
+    		    $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6);
571 571
     		}
572 572
 
573 573
     		// Public note
574
-    		if (! empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS))
574
+    		if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS))
575 575
     		{
576
-    		    if ($mode == 'source' && ! empty($sourcecompany->note_public))
576
+    		    if ($mode == 'source' && !empty($sourcecompany->note_public))
577 577
         		{
578
-        		    $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($sourcecompany->note_public);
578
+        		    $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($sourcecompany->note_public);
579 579
         		}
580
-        		if (($mode == 'target' || preg_match('/targetwithdetails/',$mode)) && ! empty($targetcompany->note_public))
580
+        		if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public))
581 581
         		{
582
-        		    $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($targetcompany->note_public);
582
+        		    $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public);
583 583
         		}
584 584
     		}
585 585
     	}
@@ -597,16 +597,16 @@  discard block
 block discarded – undo
597 597
  * 		@param		int			$page_height	Height of page
598 598
  *      @return	void
599 599
  */
600
-function pdf_pagehead(&$pdf,$outputlangs,$page_height)
600
+function pdf_pagehead(&$pdf, $outputlangs, $page_height)
601 601
 {
602 602
 	global $conf;
603 603
 
604 604
 	// Add a background image on document
605
-	if (! empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF))		// Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
605
+	if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF))		// Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
606 606
 	{
607
-		$pdf->SetAutoPageBreak(0,0);	// Disable auto pagebreak before adding image
608
-		$pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_X:0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y:0), 0, $page_height);
609
-		$pdf->SetAutoPageBreak(1,0);	// Restore pagebreak
607
+		$pdf->SetAutoPageBreak(0, 0); // Disable auto pagebreak before adding image
608
+		$pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_X : 0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y : 0), 0, $page_height);
609
+		$pdf->SetAutoPageBreak(1, 0); // Restore pagebreak
610 610
 	}
611 611
 }
612 612
 
@@ -620,11 +620,11 @@  discard block
 block discarded – undo
620 620
  *	@param	int         $onlykey       1=Do not calculate some heavy values of keys (performance enhancement when we need only the keys), 2=Values are truncated and html sanitized (to use for help tooltip)
621 621
  *	@return	array						Array of substitutions
622 622
  */
623
-function pdf_getSubstitutionArray($outputlangs, $exclude=null, $object=null, $onlykey=0)
623
+function pdf_getSubstitutionArray($outputlangs, $exclude = null, $object = null, $onlykey = 0)
624 624
 {
625 625
     $substitutionarray = getCommonSubstitutionArray($outputlangs, $onlykey, $exclude, $object);
626
-    $substitutionarray['__FROM_NAME__']='__FROM_NAME__';
627
-    $substitutionarray['__FROM_EMAIL__']='__FROM_EMAIL__';
626
+    $substitutionarray['__FROM_NAME__'] = '__FROM_NAME__';
627
+    $substitutionarray['__FROM_EMAIL__'] = '__FROM_EMAIL__';
628 628
     return $substitutionarray;
629 629
 }
630 630
 
@@ -645,35 +645,35 @@  discard block
 block discarded – undo
645 645
 	global $langs, $mysoc, $user;
646 646
 
647 647
 	// Print Draft Watermark
648
-	if ($unit=='pt') $k=1;
649
-	elseif ($unit=='mm') $k=72/25.4;
650
-	elseif ($unit=='cm') $k=72/2.54;
651
-	elseif ($unit=='in') $k=72;
648
+	if ($unit == 'pt') $k = 1;
649
+	elseif ($unit == 'mm') $k = 72 / 25.4;
650
+	elseif ($unit == 'cm') $k = 72 / 2.54;
651
+	elseif ($unit == 'in') $k = 72;
652 652
 
653 653
 	// Make substitution
654
-	$substitutionarray=pdf_getSubstitutionArray($outputlangs, null, null);
654
+	$substitutionarray = pdf_getSubstitutionArray($outputlangs, null, null);
655 655
 	complete_substitutions_array($substitutionarray, $outputlangs, null);
656
-	$text=make_substitutions($text, $substitutionarray, $outputlangs);
657
-	$text=$outputlangs->convToOutputCharset($text);
658
-
659
-	$savx=$pdf->getX(); $savy=$pdf->getY();
660
-
661
-	$watermark_angle=atan($h/$w)/2;
662
-	$watermark_x_pos=0;
663
-	$watermark_y_pos=$h/3;
664
-	$watermark_x=$w/2;
665
-	$watermark_y=$h/3;
666
-	$pdf->SetFont('','B',40);
667
-	$pdf->SetTextColor(255,192,203);
656
+	$text = make_substitutions($text, $substitutionarray, $outputlangs);
657
+	$text = $outputlangs->convToOutputCharset($text);
658
+
659
+	$savx = $pdf->getX(); $savy = $pdf->getY();
660
+
661
+	$watermark_angle = atan($h / $w) / 2;
662
+	$watermark_x_pos = 0;
663
+	$watermark_y_pos = $h / 3;
664
+	$watermark_x = $w / 2;
665
+	$watermark_y = $h / 3;
666
+	$pdf->SetFont('', 'B', 40);
667
+	$pdf->SetTextColor(255, 192, 203);
668 668
 	//rotate
669
-	$pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',cos($watermark_angle),sin($watermark_angle),-sin($watermark_angle),cos($watermark_angle),$watermark_x*$k,($h-$watermark_y)*$k,-$watermark_x*$k,-($h-$watermark_y)*$k));
669
+	$pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', cos($watermark_angle), sin($watermark_angle), -sin($watermark_angle), cos($watermark_angle), $watermark_x * $k, ($h - $watermark_y) * $k, -$watermark_x * $k, -($h - $watermark_y) * $k));
670 670
 	//print watermark
671
-	$pdf->SetXY($watermark_x_pos,$watermark_y_pos);
672
-	$pdf->Cell($w-20,25,$outputlangs->convToOutputCharset($text),"",2,"C",0);
671
+	$pdf->SetXY($watermark_x_pos, $watermark_y_pos);
672
+	$pdf->Cell($w - 20, 25, $outputlangs->convToOutputCharset($text), "", 2, "C", 0);
673 673
 	//antirotate
674 674
 	$pdf->_out('Q');
675 675
 
676
-	$pdf->SetXY($savx,$savy);
676
+	$pdf->SetXY($savx, $savy);
677 677
 }
678 678
 
679 679
 
@@ -689,43 +689,43 @@  discard block
 block discarded – undo
689 689
  *  @param	int			$default_font_size		Default font size
690 690
  *  @return	float                               The Y PDF position
691 691
  */
692
-function pdf_bank(&$pdf,$outputlangs,$curx,$cury,$account,$onlynumber=0,$default_font_size=10)
692
+function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $default_font_size = 10)
693 693
 {
694 694
 	global $mysoc, $conf;
695 695
 
696 696
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php';
697 697
 
698
-	$diffsizetitle=(empty($conf->global->PDF_DIFFSIZE_TITLE)?3:$conf->global->PDF_DIFFSIZE_TITLE);
699
-	$diffsizecontent=(empty($conf->global->PDF_DIFFSIZE_CONTENT)?4:$conf->global->PDF_DIFFSIZE_CONTENT);
698
+	$diffsizetitle = (empty($conf->global->PDF_DIFFSIZE_TITLE) ? 3 : $conf->global->PDF_DIFFSIZE_TITLE);
699
+	$diffsizecontent = (empty($conf->global->PDF_DIFFSIZE_CONTENT) ? 4 : $conf->global->PDF_DIFFSIZE_CONTENT);
700 700
 	$pdf->SetXY($curx, $cury);
701 701
 
702 702
 	if (empty($onlynumber))
703 703
 	{
704
-		$pdf->SetFont('','B',$default_font_size - $diffsizetitle);
704
+		$pdf->SetFont('', 'B', $default_font_size - $diffsizetitle);
705 705
 		$pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0);
706
-		$cury+=4;
706
+		$cury += 4;
707 707
 	}
708 708
 
709 709
 	$outputlangs->load("banks");
710 710
 
711 711
 	// Use correct name of bank id according to country
712
-	$bickey="BICNumber";
713
-	if ($account->getCountryCode() == 'IN') $bickey="SWIFT";
712
+	$bickey = "BICNumber";
713
+	if ($account->getCountryCode() == 'IN') $bickey = "SWIFT";
714 714
 
715 715
 	// Get format of bank account according to its country
716
-	$usedetailedbban=$account->useDetailedBBAN();
716
+	$usedetailedbban = $account->useDetailedBBAN();
717 717
 
718 718
 	//$onlynumber=0; $usedetailedbban=1; // For tests
719 719
 	if ($usedetailedbban)
720 720
 	{
721
-		$savcurx=$curx;
721
+		$savcurx = $curx;
722 722
 
723 723
 		if (empty($onlynumber))
724 724
 		{
725
-			$pdf->SetFont('','',$default_font_size - $diffsizecontent);
725
+			$pdf->SetFont('', '', $default_font_size - $diffsizecontent);
726 726
 			$pdf->SetXY($curx, $cury);
727
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
728
-			$cury+=3;
727
+			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
728
+			$cury += 3;
729 729
 		}
730 730
 
731 731
 		if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN))    // Note that some countries still need bank number, BIC/IBAN not enougth for them
@@ -735,13 +735,13 @@  discard block
 block discarded – undo
735 735
 		    // desk = code guichet (FR), used only when $usedetailedbban = 1
736 736
 		    // number = account number
737 737
 		    // key = check control key used only when $usedetailedbban = 1
738
-    		if (empty($onlynumber)) $pdf->line($curx+1, $cury+1, $curx+1, $cury+6);
738
+    		if (empty($onlynumber)) $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6);
739 739
 
740 740
 
741 741
 			foreach ($account->getFieldsToShow() as $val)
742 742
 			{
743
-				$pdf->SetXY($curx, $cury+4);
744
-				$pdf->SetFont('','',$default_font_size - 3);
743
+				$pdf->SetXY($curx, $cury + 4);
744
+				$pdf->SetFont('', '', $default_font_size - 3);
745 745
 
746 746
 				if ($val == 'BankCode') {
747 747
 					// Bank code
@@ -778,54 +778,54 @@  discard block
 block discarded – undo
778 778
 				}
779 779
     		}
780 780
 
781
-    		$curx=$savcurx;
782
-    		$cury+=8;
781
+    		$curx = $savcurx;
782
+    		$cury += 8;
783 783
 		}
784 784
 	}
785 785
 	else
786 786
 	{
787
-		$pdf->SetFont('','B',$default_font_size - $diffsizecontent);
787
+		$pdf->SetFont('', 'B', $default_font_size - $diffsizecontent);
788 788
 		$pdf->SetXY($curx, $cury);
789
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
790
-		$cury+=3;
789
+		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0);
790
+		$cury += 3;
791 791
 
792
-		$pdf->SetFont('','B',$default_font_size - $diffsizecontent);
792
+		$pdf->SetFont('', 'B', $default_font_size - $diffsizecontent);
793 793
 		$pdf->SetXY($curx, $cury);
794
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': ' . $outputlangs->convToOutputCharset($account->number), 0, 'L', 0);
795
-		$cury+=3;
794
+		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': '.$outputlangs->convToOutputCharset($account->number), 0, 'L', 0);
795
+		$cury += 3;
796 796
 
797
-		if ($diffsizecontent <= 2) $cury+=1;
797
+		if ($diffsizecontent <= 2) $cury += 1;
798 798
 	}
799 799
 
800
-	$pdf->SetFont('','',$default_font_size - $diffsizecontent);
800
+	$pdf->SetFont('', '', $default_font_size - $diffsizecontent);
801 801
 
802
-	if (empty($onlynumber) && ! empty($account->domiciliation))
802
+	if (empty($onlynumber) && !empty($account->domiciliation))
803 803
 	{
804 804
 		$pdf->SetXY($curx, $cury);
805
-		$val=$outputlangs->transnoentities("Residence").': ' . $outputlangs->convToOutputCharset($account->domiciliation);
805
+		$val = $outputlangs->transnoentities("Residence").': '.$outputlangs->convToOutputCharset($account->domiciliation);
806 806
 		$pdf->MultiCell(100, 3, $val, 0, 'L', 0);
807 807
 		//$nboflines=dol_nboflines_bis($val,120);
808 808
 		//$cury+=($nboflines*3)+2;
809
-		$tmpy=$pdf->getStringHeight(100, $val);
810
-		$cury+=$tmpy;
809
+		$tmpy = $pdf->getStringHeight(100, $val);
810
+		$cury += $tmpy;
811 811
 	}
812 812
 
813
-	if (! empty($account->proprio))
813
+	if (!empty($account->proprio))
814 814
 	{
815 815
 		$pdf->SetXY($curx, $cury);
816
-		$val=$outputlangs->transnoentities("BankAccountOwner").': ' . $outputlangs->convToOutputCharset($account->proprio);
816
+		$val = $outputlangs->transnoentities("BankAccountOwner").': '.$outputlangs->convToOutputCharset($account->proprio);
817 817
 		$pdf->MultiCell(100, 3, $val, 0, 'L', 0);
818
-		$tmpy=$pdf->getStringHeight(100, $val);
819
-		$cury+=$tmpy;
820
-		$cur+=1;
818
+		$tmpy = $pdf->getStringHeight(100, $val);
819
+		$cury += $tmpy;
820
+		$cur += 1;
821 821
 	}
822 822
 
823
-	else if (! $usedetailedbban) $cury+=1;
823
+	else if (!$usedetailedbban) $cury += 1;
824 824
 
825 825
 	// Use correct name of bank id according to country
826 826
 	$ibankey = FormBank::getIBANLabel($account);
827 827
 
828
-	if (! empty($account->iban))
828
+	if (!empty($account->iban))
829 829
 	{
830 830
 		//Remove whitespaces to ensure we are dealing with the format we expect
831 831
 		$ibanDisplay_temp = str_replace(' ', '', $outputlangs->convToOutputCharset($account->iban));
@@ -835,20 +835,20 @@  discard block
 block discarded – undo
835 835
 		for ($i = 0; $i < $nbIbanDisplay_temp; $i++)
836 836
 		{
837 837
 			$ibanDisplay .= $ibanDisplay_temp[$i];
838
-			if($i%4 == 3 && $i > 0)	$ibanDisplay .= " ";
838
+			if ($i % 4 == 3 && $i > 0)	$ibanDisplay .= " ";
839 839
 		}
840 840
 
841
-		$pdf->SetFont('','B',$default_font_size - 3);
841
+		$pdf->SetFont('', 'B', $default_font_size - 3);
842 842
 		$pdf->SetXY($curx, $cury);
843
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities($ibankey).': ' . $ibanDisplay, 0, 'L', 0);
844
-		$cury+=3;
843
+		$pdf->MultiCell(100, 3, $outputlangs->transnoentities($ibankey).': '.$ibanDisplay, 0, 'L', 0);
844
+		$cury += 3;
845 845
 	}
846 846
 
847
-	if (! empty($account->bic))
847
+	if (!empty($account->bic))
848 848
 	{
849
-		$pdf->SetFont('','B',$default_font_size - 3);
849
+		$pdf->SetFont('', 'B', $default_font_size - 3);
850 850
 		$pdf->SetXY($curx, $cury);
851
-		$pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': ' . $outputlangs->convToOutputCharset($account->bic), 0, 'L', 0);
851
+		$pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': '.$outputlangs->convToOutputCharset($account->bic), 0, 'L', 0);
852 852
 	}
853 853
 
854 854
 	return $pdf->getY();
@@ -869,79 +869,79 @@  discard block
 block discarded – undo
869 869
  *  @param	int			$hidefreetext	1=Hide free text, 0=Show free text
870 870
  * 	@return	int							Return height of bottom margin including footer text
871 871
  */
872
-function pdf_pagefoot(&$pdf,$outputlangs,$paramfreetext,$fromcompany,$marge_basse,$marge_gauche,$page_hauteur,$object,$showdetails=0,$hidefreetext=0)
872
+function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_basse, $marge_gauche, $page_hauteur, $object, $showdetails = 0, $hidefreetext = 0)
873 873
 {
874
-	global $conf,$user,$mysoc;
874
+	global $conf, $user, $mysoc;
875 875
 
876 876
 	$outputlangs->load("dict");
877
-	$line='';
877
+	$line = '';
878 878
 
879
-	$dims=$pdf->getPageDimensions();
879
+	$dims = $pdf->getPageDimensions();
880 880
 
881 881
 	// Line of free text
882
-	if (empty($hidefreetext) && ! empty($conf->global->$paramfreetext))
882
+	if (empty($hidefreetext) && !empty($conf->global->$paramfreetext))
883 883
 	{
884
-		$substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object);
884
+		$substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object);
885 885
 		// More substitution keys
886
-		$substitutionarray['__FROM_NAME__']=$fromcompany->name;
887
-		$substitutionarray['__FROM_EMAIL__']=$fromcompany->email;
886
+		$substitutionarray['__FROM_NAME__'] = $fromcompany->name;
887
+		$substitutionarray['__FROM_EMAIL__'] = $fromcompany->email;
888 888
 		complete_substitutions_array($substitutionarray, $outputlangs, $object);
889
-		$newfreetext=make_substitutions($conf->global->$paramfreetext, $substitutionarray, $outputlangs);
889
+		$newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray, $outputlangs);
890 890
 
891 891
 		// Make a change into HTML code to allow to include images from medias directory.
892 892
 		// <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
893 893
 		// become
894 894
 		// <img alt="" src="'.DOL_DATA_ROOT.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
895
-		$newfreetext=preg_replace('/(<img.*src=")[^\"]*viewimage\.php[^\"]*modulepart=medias[^\"]*file=([^\"]*)("[^\/]*\/>)/', '\1'.DOL_DATA_ROOT.'/medias/\2\3', $newfreetext);
895
+		$newfreetext = preg_replace('/(<img.*src=")[^\"]*viewimage\.php[^\"]*modulepart=medias[^\"]*file=([^\"]*)("[^\/]*\/>)/', '\1'.DOL_DATA_ROOT.'/medias/\2\3', $newfreetext);
896 896
 
897
-		$line.=$outputlangs->convToOutputCharset($newfreetext);
897
+		$line .= $outputlangs->convToOutputCharset($newfreetext);
898 898
 	}
899 899
 
900 900
 	// First line of company infos
901
-	$line1=""; $line2=""; $line3=""; $line4="";
901
+	$line1 = ""; $line2 = ""; $line3 = ""; $line4 = "";
902 902
 
903 903
 		if ($showdetails == 1 || $showdetails == 3)
904 904
 	{
905 905
 		// Company name
906 906
 		if ($fromcompany->name)
907 907
 		{
908
-			$line1.=($line1?" - ":"").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name;
908
+			$line1 .= ($line1 ? " - " : "").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name;
909 909
 		}
910 910
 		// Address
911 911
 		if ($fromcompany->address)
912 912
 		{
913
-			$line1.=($line1?" - ":"").str_replace("\n", ", ", $fromcompany->address);
913
+			$line1 .= ($line1 ? " - " : "").str_replace("\n", ", ", $fromcompany->address);
914 914
 		}
915 915
 		// Zip code
916 916
 		if ($fromcompany->zip)
917 917
 		{
918
-			$line1.=($line1?" - ":"").$fromcompany->zip;
918
+			$line1 .= ($line1 ? " - " : "").$fromcompany->zip;
919 919
 		}
920 920
 		// Town
921 921
 		if ($fromcompany->town)
922 922
 		{
923
-			$line1.=($line1?" ":"").$fromcompany->town;
923
+			$line1 .= ($line1 ? " " : "").$fromcompany->town;
924 924
 		}
925 925
 		// Phone
926 926
 		if ($fromcompany->phone)
927 927
 		{
928
-			$line2.=($line2?" - ":"").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone;
928
+			$line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone;
929 929
 		}
930 930
 		// Fax
931 931
 		if ($fromcompany->fax)
932 932
 		{
933
-			$line2.=($line2?" - ":"").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax;
933
+			$line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax;
934 934
 		}
935 935
 
936 936
 		// URL
937 937
 		if ($fromcompany->url)
938 938
 		{
939
-			$line2.=($line2?" - ":"").$fromcompany->url;
939
+			$line2 .= ($line2 ? " - " : "").$fromcompany->url;
940 940
 		}
941 941
 		// Email
942 942
 		if ($fromcompany->email)
943 943
 		{
944
-			$line2.=($line2?" - ":"").$fromcompany->email;
944
+			$line2 .= ($line2 ? " - " : "").$fromcompany->email;
945 945
 		}
946 946
 	}
947 947
 	if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE'))
@@ -949,7 +949,7 @@  discard block
 block discarded – undo
949 949
 		// Managers
950 950
 		if ($fromcompany->managers)
951 951
 		{
952
-			$line2.=($line2?" - ":"").$fromcompany->managers;
952
+			$line2 .= ($line2 ? " - " : "").$fromcompany->managers;
953 953
 		}
954 954
 	}
955 955
 
@@ -957,144 +957,144 @@  discard block
 block discarded – undo
957 957
 	// Juridical status
958 958
 	if ($fromcompany->forme_juridique_code)
959 959
 	{
960
-		$line3.=($line3?" - ":"").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code));
960
+		$line3 .= ($line3 ? " - " : "").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code));
961 961
 	}
962 962
 	// Capital
963 963
 	if ($fromcompany->capital)
964 964
 	{
965 965
 		$tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string
966
-		if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
967
-		else $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",$tmpamounttoshow,$outputlangs);
966
+		if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
967
+		else $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs);
968 968
 	}
969 969
 	// Prof Id 1
970
-	if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || ! $fromcompany->idprof2))
970
+	if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2))
971 971
 	{
972
-		$field=$outputlangs->transcountrynoentities("ProfId1",$fromcompany->country_code);
973
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
974
-		$line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1);
972
+		$field = $outputlangs->transcountrynoentities("ProfId1", $fromcompany->country_code);
973
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
974
+		$line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1);
975 975
 	}
976 976
 	// Prof Id 2
977 977
 	if ($fromcompany->idprof2)
978 978
 	{
979
-		$field=$outputlangs->transcountrynoentities("ProfId2",$fromcompany->country_code);
980
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
981
-		$line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2);
979
+		$field = $outputlangs->transcountrynoentities("ProfId2", $fromcompany->country_code);
980
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
981
+		$line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2);
982 982
 	}
983 983
 
984 984
 	// Line 4 of company infos
985 985
 	// Prof Id 3
986 986
 	if ($fromcompany->idprof3)
987 987
 	{
988
-		$field=$outputlangs->transcountrynoentities("ProfId3",$fromcompany->country_code);
989
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
990
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3);
988
+		$field = $outputlangs->transcountrynoentities("ProfId3", $fromcompany->country_code);
989
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
990
+		$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3);
991 991
 	}
992 992
 	// Prof Id 4
993 993
 	if ($fromcompany->idprof4)
994 994
 	{
995
-		$field=$outputlangs->transcountrynoentities("ProfId4",$fromcompany->country_code);
996
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
997
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4);
995
+		$field = $outputlangs->transcountrynoentities("ProfId4", $fromcompany->country_code);
996
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
997
+		$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4);
998 998
 	}
999 999
 	// Prof Id 5
1000 1000
 	if ($fromcompany->idprof5)
1001 1001
 	{
1002
-		$field=$outputlangs->transcountrynoentities("ProfId5",$fromcompany->country_code);
1003
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1004
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5);
1002
+		$field = $outputlangs->transcountrynoentities("ProfId5", $fromcompany->country_code);
1003
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
1004
+		$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5);
1005 1005
 	}
1006 1006
 	// Prof Id 6
1007 1007
 	if ($fromcompany->idprof6)
1008 1008
 	{
1009
-		$field=$outputlangs->transcountrynoentities("ProfId6",$fromcompany->country_code);
1010
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1011
-		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6);
1009
+		$field = $outputlangs->transcountrynoentities("ProfId6", $fromcompany->country_code);
1010
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
1011
+		$line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6);
1012 1012
 	}
1013 1013
 	// IntraCommunautary VAT
1014 1014
 	if ($fromcompany->tva_intra != '')
1015 1015
 	{
1016
-		$line4.=($line4?" - ":"").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra);
1016
+		$line4 .= ($line4 ? " - " : "").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra);
1017 1017
 	}
1018 1018
 
1019
-	$pdf->SetFont('','',7);
1020
-	$pdf->SetDrawColor(224,224,224);
1019
+	$pdf->SetFont('', '', 7);
1020
+	$pdf->SetDrawColor(224, 224, 224);
1021 1021
 
1022 1022
 	// The start of the bottom of this page footer is positioned according to # of lines
1023
-	$freetextheight=0;
1023
+	$freetextheight = 0;
1024 1024
 	if ($line)	// Free text
1025 1025
 	{
1026 1026
 		//$line="sample text<br>\nfd<strong>sf</strong>sdf<br>\nghfghg<br>";
1027 1027
 	    if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
1028 1028
 		{
1029
-			$width=20000; $align='L';	// By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
1030
-    		if (! empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) {
1031
-    			$width=200; $align='C';
1029
+			$width = 20000; $align = 'L'; // By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
1030
+    		if (!empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) {
1031
+    			$width = 200; $align = 'C';
1032 1032
     		}
1033
-		    $freetextheight=$pdf->getStringHeight($width,$line);
1033
+		    $freetextheight = $pdf->getStringHeight($width, $line);
1034 1034
 		}
1035 1035
 		else
1036 1036
 		{
1037
-            $freetextheight=pdfGetHeightForHtmlContent($pdf,dol_htmlentitiesbr($line, 1, 'UTF-8', 0));      // New method (works for HTML content)
1037
+            $freetextheight = pdfGetHeightForHtmlContent($pdf, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); // New method (works for HTML content)
1038 1038
             //print '<br>'.$freetextheight;exit;
1039 1039
 		}
1040 1040
 	}
1041 1041
 
1042
-	$marginwithfooter=$marge_basse + $freetextheight + (! empty($line1)?3:0) + (! empty($line2)?3:0) + (! empty($line3)?3:0) + (! empty($line4)?3:0);
1043
-	$posy=$marginwithfooter+0;
1042
+	$marginwithfooter = $marge_basse + $freetextheight + (!empty($line1) ? 3 : 0) + (!empty($line2) ? 3 : 0) + (!empty($line3) ? 3 : 0) + (!empty($line4) ? 3 : 0);
1043
+	$posy = $marginwithfooter + 0;
1044 1044
 
1045 1045
 	if ($line)	// Free text
1046 1046
 	{
1047
-		$pdf->SetXY($dims['lm'],-$posy);
1047
+		$pdf->SetXY($dims['lm'], -$posy);
1048 1048
 		if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))   // by default
1049 1049
 		{
1050 1050
             $pdf->MultiCell(0, 3, $line, 0, $align, 0);
1051 1051
 		}
1052 1052
 		else
1053 1053
 		{
1054
-            $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk']-$marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0));
1054
+            $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk'] - $marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0));
1055 1055
 		}
1056
-		$posy-=$freetextheight;
1056
+		$posy -= $freetextheight;
1057 1057
 	}
1058 1058
 
1059 1059
 	$pdf->SetY(-$posy);
1060
-	$pdf->line($dims['lm'], $dims['hk']-$posy, $dims['wk']-$dims['rm'], $dims['hk']-$posy);
1060
+	$pdf->line($dims['lm'], $dims['hk'] - $posy, $dims['wk'] - $dims['rm'], $dims['hk'] - $posy);
1061 1061
 	$posy--;
1062 1062
 
1063
-	if (! empty($line1))
1063
+	if (!empty($line1))
1064 1064
 	{
1065
-		$pdf->SetFont('','B',7);
1066
-		$pdf->SetXY($dims['lm'],-$posy);
1067
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line1, 0, 'C', 0);
1068
-		$posy-=3;
1069
-		$pdf->SetFont('','',7);
1065
+		$pdf->SetFont('', 'B', 7);
1066
+		$pdf->SetXY($dims['lm'], -$posy);
1067
+		$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line1, 0, 'C', 0);
1068
+		$posy -= 3;
1069
+		$pdf->SetFont('', '', 7);
1070 1070
 	}
1071 1071
 
1072
-	if (! empty($line2))
1072
+	if (!empty($line2))
1073 1073
 	{
1074
-		$pdf->SetFont('','B',7);
1075
-		$pdf->SetXY($dims['lm'],-$posy);
1076
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line2, 0, 'C', 0);
1077
-		$posy-=3;
1078
-		$pdf->SetFont('','',7);
1074
+		$pdf->SetFont('', 'B', 7);
1075
+		$pdf->SetXY($dims['lm'], -$posy);
1076
+		$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line2, 0, 'C', 0);
1077
+		$posy -= 3;
1078
+		$pdf->SetFont('', '', 7);
1079 1079
 	}
1080 1080
 
1081
-	if (! empty($line3))
1081
+	if (!empty($line3))
1082 1082
 	{
1083
-		$pdf->SetXY($dims['lm'],-$posy);
1084
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line3, 0, 'C', 0);
1083
+		$pdf->SetXY($dims['lm'], -$posy);
1084
+		$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line3, 0, 'C', 0);
1085 1085
 	}
1086 1086
 
1087
-	if (! empty($line4))
1087
+	if (!empty($line4))
1088 1088
 	{
1089
-		$posy-=3;
1090
-		$pdf->SetXY($dims['lm'],-$posy);
1091
-		$pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line4, 0, 'C', 0);
1089
+		$posy -= 3;
1090
+		$pdf->SetXY($dims['lm'], -$posy);
1091
+		$pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line4, 0, 'C', 0);
1092 1092
 	}
1093 1093
 
1094 1094
 	// Show page nb only on iso languages (so default Helvetica font)
1095 1095
 	if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica')
1096 1096
 	{
1097
-		$pdf->SetXY($dims['wk']-$dims['rm']-15, -$posy);
1097
+		$pdf->SetXY($dims['wk'] - $dims['rm'] - 15, -$posy);
1098 1098
 		//print 'xxx'.$pdf->PageNo().'-'.$pdf->getAliasNbPages().'-'.$pdf->getAliasNumPage();exit;
1099 1099
 		$pdf->MultiCell(15, 2, $pdf->PageNo().'/'.$pdf->getAliasNbPages(), 0, 'R', 0);
1100 1100
 	}
@@ -1116,22 +1116,22 @@  discard block
 block discarded – undo
1116 1116
  *	@param	string		$default_font_size	Font size
1117 1117
  *	@return	float                           The Y PDF position
1118 1118
  */
1119
-function pdf_writeLinkedObjects(&$pdf,$object,$outputlangs,$posx,$posy,$w,$h,$align,$default_font_size)
1119
+function pdf_writeLinkedObjects(&$pdf, $object, $outputlangs, $posx, $posy, $w, $h, $align, $default_font_size)
1120 1120
 {
1121
-	$linkedobjects = pdf_getLinkedObjects($object,$outputlangs);
1122
-	if (! empty($linkedobjects))
1121
+	$linkedobjects = pdf_getLinkedObjects($object, $outputlangs);
1122
+	if (!empty($linkedobjects))
1123 1123
 	{
1124
-		foreach($linkedobjects as $linkedobject)
1124
+		foreach ($linkedobjects as $linkedobject)
1125 1125
 		{
1126 1126
 		    $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"];
1127
-		    if (! empty($linkedobject["date_value"]))
1127
+		    if (!empty($linkedobject["date_value"]))
1128 1128
 		    {
1129 1129
 		        $reftoshow .= ' / '.$linkedobject["date_value"];
1130 1130
 		    }
1131 1131
 
1132
-			$posy+=3;
1133
-			$pdf->SetXY($posx,$posy);
1134
-			$pdf->SetFont('','', $default_font_size - 2);
1132
+			$posy += 3;
1133
+			$pdf->SetXY($posx, $posy);
1134
+			$pdf->SetFont('', '', $default_font_size - 2);
1135 1135
 			$pdf->MultiCell($w, $h, $reftoshow, '', $align);
1136 1136
 		}
1137 1137
 	}
@@ -1155,29 +1155,29 @@  discard block
 block discarded – undo
1155 1155
  * 	@param	int				$issupplierline		Is it a line for a supplier object ?
1156 1156
  * 	@return	string
1157 1157
  */
1158
-function pdf_writelinedesc(&$pdf,$object,$i,$outputlangs,$w,$h,$posx,$posy,$hideref=0,$hidedesc=0,$issupplierline=0)
1158
+function pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $posy, $hideref = 0, $hidedesc = 0, $issupplierline = 0)
1159 1159
 {
1160 1160
 	global $db, $conf, $langs, $hookmanager;
1161 1161
 
1162
-	$reshook=0;
1163
-	$result='';
1162
+	$reshook = 0;
1163
+	$result = '';
1164 1164
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1165 1165
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1166 1166
 	{
1167 1167
 		$special_code = $object->lines[$i]->special_code;
1168
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1169
-		$parameters = array('pdf'=>$pdf,'i'=>$i,'outputlangs'=>$outputlangs,'w'=>$w,'h'=>$h,'posx'=>$posx,'posy'=>$posy,'hideref'=>$hideref,'hidedesc'=>$hidedesc,'issupplierline'=>$issupplierline,'special_code'=>$special_code);
1170
-		$action='';
1171
-		$reshook=$hookmanager->executeHooks('pdf_writelinedesc',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1168
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1169
+		$parameters = array('pdf'=>$pdf, 'i'=>$i, 'outputlangs'=>$outputlangs, 'w'=>$w, 'h'=>$h, 'posx'=>$posx, 'posy'=>$posy, 'hideref'=>$hideref, 'hidedesc'=>$hidedesc, 'issupplierline'=>$issupplierline, 'special_code'=>$special_code);
1170
+		$action = '';
1171
+		$reshook = $hookmanager->executeHooks('pdf_writelinedesc', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1172 1172
 
1173
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1173
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1174 1174
 	}
1175 1175
 	if (empty($reshook))
1176 1176
 	{
1177
-		$labelproductservice=pdf_getlinedesc($object,$i,$outputlangs,$hideref,$hidedesc,$issupplierline);
1177
+		$labelproductservice = pdf_getlinedesc($object, $i, $outputlangs, $hideref, $hidedesc, $issupplierline);
1178 1178
 		// Description
1179
-		$pdf->writeHTMLCell($w, $h, $posx, $posy, $outputlangs->convToOutputCharset($labelproductservice), 0, 1, false, true, 'J',true);
1180
-		$result.=$labelproductservice;
1179
+		$pdf->writeHTMLCell($w, $h, $posx, $posy, $outputlangs->convToOutputCharset($labelproductservice), 0, 1, false, true, 'J', true);
1180
+		$result .= $labelproductservice;
1181 1181
 	}
1182 1182
 	return $result;
1183 1183
 }
@@ -1193,16 +1193,16 @@  discard block
 block discarded – undo
1193 1193
  *  @param  int			$issupplierline      Is it a line for a supplier object ?
1194 1194
  *  @return string       				     String with line
1195 1195
  */
1196
-function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issupplierline=0)
1196
+function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0)
1197 1197
 {
1198 1198
 	global $db, $conf, $langs;
1199 1199
 
1200
-	$idprod=(! empty($object->lines[$i]->fk_product)?$object->lines[$i]->fk_product:false);
1201
-	$label=(! empty($object->lines[$i]->label)?$object->lines[$i]->label:(! empty($object->lines[$i]->product_label)?$object->lines[$i]->product_label:''));
1202
-	$desc=(! empty($object->lines[$i]->desc)?$object->lines[$i]->desc:(! empty($object->lines[$i]->description)?$object->lines[$i]->description:''));
1203
-	$ref_supplier=(! empty($object->lines[$i]->ref_supplier)?$object->lines[$i]->ref_supplier:(! empty($object->lines[$i]->ref_fourn)?$object->lines[$i]->ref_fourn:''));    // TODO Not yet saved for supplier invoices, only supplier orders
1204
-	$note=(! empty($object->lines[$i]->note)?$object->lines[$i]->note:'');
1205
-	$dbatch=(! empty($object->lines[$i]->detail_batch)?$object->lines[$i]->detail_batch:false);
1200
+	$idprod = (!empty($object->lines[$i]->fk_product) ? $object->lines[$i]->fk_product : false);
1201
+	$label = (!empty($object->lines[$i]->label) ? $object->lines[$i]->label : (!empty($object->lines[$i]->product_label) ? $object->lines[$i]->product_label : ''));
1202
+	$desc = (!empty($object->lines[$i]->desc) ? $object->lines[$i]->desc : (!empty($object->lines[$i]->description) ? $object->lines[$i]->description : ''));
1203
+	$ref_supplier = (!empty($object->lines[$i]->ref_supplier) ? $object->lines[$i]->ref_supplier : (!empty($object->lines[$i]->ref_fourn) ? $object->lines[$i]->ref_fourn : '')); // TODO Not yet saved for supplier invoices, only supplier orders
1204
+	$note = (!empty($object->lines[$i]->note) ? $object->lines[$i]->note : '');
1205
+	$dbatch = (!empty($object->lines[$i]->detail_batch) ? $object->lines[$i]->detail_batch : false);
1206 1206
 
1207 1207
 	if ($issupplierline)
1208 1208
 	{
@@ -1219,9 +1219,9 @@  discard block
 block discarded – undo
1219 1219
 	{
1220 1220
 		$prodser->fetch($idprod);
1221 1221
 		// If a predefined product and multilang and on other lang, we renamed label with label translated
1222
-		if (! empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang))
1222
+		if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang))
1223 1223
 		{
1224
-			$translatealsoifmodified=(! empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED));	// By default if value was modified manually, we keep it (no translation because we don't have it)
1224
+			$translatealsoifmodified = (!empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED)); // By default if value was modified manually, we keep it (no translation because we don't have it)
1225 1225
 
1226 1226
 			// TODO Instead of making a compare to see if param was modified, check that content contains reference translation. If yes, add the added part to the new translation
1227 1227
 			// ($textwasmodified is replaced with $textwasmodifiedorcompleted and we add completion).
@@ -1229,63 +1229,63 @@  discard block
 block discarded – undo
1229 1229
 			// Set label
1230 1230
 			// If we want another language, and if label is same than default language (we did force it to a specific value), we can use translation.
1231 1231
 			//var_dump($outputlangs->defaultlang.' - '.$langs->defaultlang.' - '.$label.' - '.$prodser->label);exit;
1232
-			$textwasmodified=($label == $prodser->label);
1233
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified))     $label=$prodser->multilangs[$outputlangs->defaultlang]["label"];
1232
+			$textwasmodified = ($label == $prodser->label);
1233
+			if (!empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified))     $label = $prodser->multilangs[$outputlangs->defaultlang]["label"];
1234 1234
 
1235 1235
 			// Set desc
1236 1236
 			// Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no
1237
-			$textwasmodified=false;
1237
+			$textwasmodified = false;
1238 1238
 			if (!empty($desc) && dol_textishtml($desc) && !empty($prodser->description) && dol_textishtml($prodser->description)) {
1239
-				$textwasmodified=(strpos(dol_html_entity_decode($desc,ENT_QUOTES | ENT_HTML401),dol_html_entity_decode($prodser->description,ENT_QUOTES | ENT_HTML401))!==false);
1239
+				$textwasmodified = (strpos(dol_html_entity_decode($desc, ENT_QUOTES | ENT_HTML401), dol_html_entity_decode($prodser->description, ENT_QUOTES | ENT_HTML401)) !== false);
1240 1240
 			} else {
1241
-				$textwasmodified=($desc == $prodser->description);
1241
+				$textwasmodified = ($desc == $prodser->description);
1242 1242
 			}
1243
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified))  $desc=$prodser->multilangs[$outputlangs->defaultlang]["description"];
1243
+			if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified))  $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"];
1244 1244
 
1245 1245
 			// Set note
1246
-			$textwasmodified=($note == $prodser->note);
1247
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified))  $note=$prodser->multilangs[$outputlangs->defaultlang]["note"];
1246
+			$textwasmodified = ($note == $prodser->note);
1247
+			if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified))  $note = $prodser->multilangs[$outputlangs->defaultlang]["note"];
1248 1248
 		}
1249 1249
 	}
1250 1250
 
1251 1251
 	// Description short of product line
1252
-	$libelleproduitservice=$label;
1252
+	$libelleproduitservice = $label;
1253 1253
 
1254 1254
 	// Description long of product line
1255
-	if (! empty($desc) && ($desc != $label))
1255
+	if (!empty($desc) && ($desc != $label))
1256 1256
 	{
1257 1257
 		if ($libelleproduitservice && empty($hidedesc))
1258 1258
 		{
1259
-			$libelleproduitservice.='__N__';
1259
+			$libelleproduitservice .= '__N__';
1260 1260
 		}
1261 1261
 
1262 1262
 		if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except)
1263 1263
 		{
1264
-			$discount=new DiscountAbsolute($db);
1264
+			$discount = new DiscountAbsolute($db);
1265 1265
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1266
-			$sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1267
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref);
1266
+			$sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source;
1267
+			$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromCreditNote", $sourceref);
1268 1268
 		}
1269 1269
 		elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except)
1270 1270
 		{
1271
-			$discount=new DiscountAbsolute($db);
1271
+			$discount = new DiscountAbsolute($db);
1272 1272
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1273
-			$sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1274
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref);
1273
+			$sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source;
1274
+			$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromDeposit", $sourceref);
1275 1275
 			// Add date of deposit
1276
-			if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')';
1276
+			if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')';
1277 1277
 		}
1278 1278
 		if ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except)
1279 1279
 		{
1280
-			$discount=new DiscountAbsolute($db);
1280
+			$discount = new DiscountAbsolute($db);
1281 1281
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1282
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source);
1282
+			$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source);
1283 1283
 		}
1284 1284
 		elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except)
1285 1285
 		{
1286
-			$discount=new DiscountAbsolute($db);
1286
+			$discount = new DiscountAbsolute($db);
1287 1287
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1288
-			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source);
1288
+			$libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source);
1289 1289
 		}
1290 1290
 		else
1291 1291
 		{
@@ -1295,17 +1295,17 @@  discard block
 block discarded – undo
1295 1295
 				{
1296 1296
 					if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST))
1297 1297
 					{
1298
-						$libelleproduitservice=$desc."\n".$libelleproduitservice;
1298
+						$libelleproduitservice = $desc."\n".$libelleproduitservice;
1299 1299
 					}
1300 1300
 					else
1301 1301
 					{
1302
-						$libelleproduitservice.=$desc;
1302
+						$libelleproduitservice .= $desc;
1303 1303
 					}
1304 1304
 				}
1305 1305
 			}
1306 1306
 			else
1307 1307
 			{
1308
-				$libelleproduitservice.=$desc;
1308
+				$libelleproduitservice .= $desc;
1309 1309
 			}
1310 1310
 		}
1311 1311
 	}
@@ -1313,7 +1313,7 @@  discard block
 block discarded – undo
1313 1313
 	// We add ref of product (and supplier ref if defined)
1314 1314
 	$prefix_prodserv = "";
1315 1315
 	$ref_prodserv = "";
1316
-	if (! empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS))   // In standard mode, we do not show this
1316
+	if (!empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS))   // In standard mode, we do not show this
1317 1317
 	{
1318 1318
 		if ($prodser->isService())
1319 1319
 		{
@@ -1332,11 +1332,11 @@  discard block
 block discarded – undo
1332 1332
 			if ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1)
1333 1333
 				$ref_prodserv = $ref_supplier;
1334 1334
 			elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2)
1335
-				$ref_prodserv = $ref_supplier. ' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')';
1335
+				$ref_prodserv = $ref_supplier.' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')';
1336 1336
 			else	// Common case
1337 1337
 			{
1338 1338
 				$ref_prodserv = $prodser->ref; // Show local ref
1339
-				if ($ref_supplier) $ref_prodserv.= ($prodser->ref?' (':'').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref?')':'');
1339
+				if ($ref_supplier) $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : '');
1340 1340
 			}
1341 1341
 		}
1342 1342
 		else
@@ -1344,71 +1344,71 @@  discard block
 block discarded – undo
1344 1344
 			$ref_prodserv = $prodser->ref; // Show local ref only
1345 1345
 		}
1346 1346
 
1347
-		if (! empty($libelleproduitservice) && ! empty($ref_prodserv)) $ref_prodserv .= " - ";
1347
+		if (!empty($libelleproduitservice) && !empty($ref_prodserv)) $ref_prodserv .= " - ";
1348 1348
 	}
1349 1349
 
1350
-	if(!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){ $ref_prodserv = '<b>'.$ref_prodserv.'</b>'; }
1351
-	$libelleproduitservice=$prefix_prodserv.$ref_prodserv.$libelleproduitservice;
1350
+	if (!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)) { $ref_prodserv = '<b>'.$ref_prodserv.'</b>'; }
1351
+	$libelleproduitservice = $prefix_prodserv.$ref_prodserv.$libelleproduitservice;
1352 1352
 
1353 1353
 	// Add an additional description for the category products
1354
-	if (! empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && ! empty($conf->categorie->enabled))
1354
+	if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled))
1355 1355
 	{
1356 1356
 		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1357
-		$categstatic=new Categorie($db);
1357
+		$categstatic = new Categorie($db);
1358 1358
 		// recovering the list of all the categories linked to product
1359
-		$tblcateg=$categstatic->containing($idprod, Categorie::TYPE_PRODUCT);
1359
+		$tblcateg = $categstatic->containing($idprod, Categorie::TYPE_PRODUCT);
1360 1360
 		foreach ($tblcateg as $cate)
1361 1361
 		{
1362 1362
 			// Adding the descriptions if they are filled
1363
-			$desccateg=$cate->add_description;
1363
+			$desccateg = $cate->add_description;
1364 1364
 			if ($desccateg)
1365
-				$libelleproduitservice.='__N__'.$desccateg;
1365
+				$libelleproduitservice .= '__N__'.$desccateg;
1366 1366
 		}
1367 1367
 	}
1368 1368
 
1369
-	if (! empty($object->lines[$i]->date_start) || ! empty($object->lines[$i]->date_end))
1369
+	if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end))
1370 1370
 	{
1371
-		$format='day';
1371
+		$format = 'day';
1372 1372
 		// Show duration if exists
1373 1373
 		if ($object->lines[$i]->date_start && $object->lines[$i]->date_end)
1374 1374
 		{
1375
-			$period='('.$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs),dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1375
+			$period = '('.$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs), dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1376 1376
 		}
1377
-		if ($object->lines[$i]->date_start && ! $object->lines[$i]->date_end)
1377
+		if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end)
1378 1378
 		{
1379
-			$period='('.$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')';
1379
+			$period = '('.$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')';
1380 1380
 		}
1381
-		if (! $object->lines[$i]->date_start && $object->lines[$i]->date_end)
1381
+		if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end)
1382 1382
 		{
1383
-			$period='('.$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1383
+			$period = '('.$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')';
1384 1384
 		}
1385 1385
 		//print '>'.$outputlangs->charset_output.','.$period;
1386
-		if(!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){
1387
-		    $libelleproduitservice.= '<b style="color:#333666;" ><em>'."__N__</b> ".$period.'</em>';
1388
-		}else{
1389
-		$libelleproduitservice.="__N__".$period;
1386
+		if (!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)) {
1387
+		    $libelleproduitservice .= '<b style="color:#333666;" ><em>'."__N__</b> ".$period.'</em>';
1388
+		} else {
1389
+		$libelleproduitservice .= "__N__".$period;
1390 1390
 		}
1391 1391
 		//print $libelleproduitservice;
1392 1392
 	}
1393 1393
 
1394 1394
 	if ($dbatch)
1395 1395
 	{
1396
-		$format='day';
1396
+		$format = 'day';
1397 1397
 		foreach ($dbatch as $detail)
1398 1398
 		{
1399
-			$dte=array();
1400
-			if ($detail->eatby) $dte[]=$outputlangs->transnoentitiesnoconv('printEatby',dol_print_date($detail->eatby, $format, false, $outputlangs));
1401
-			if ($detail->sellby) $dte[]=$outputlangs->transnoentitiesnoconv('printSellby',dol_print_date($detail->sellby, $format, false, $outputlangs));
1402
-			if ($detail->batch) $dte[]=$outputlangs->transnoentitiesnoconv('printBatch',$detail->batch);
1403
-			$dte[]=$outputlangs->transnoentitiesnoconv('printQty',$detail->qty);
1404
-			$libelleproduitservice.= "__N__  ".implode(" - ", $dte);
1399
+			$dte = array();
1400
+			if ($detail->eatby) $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs));
1401
+			if ($detail->sellby) $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs));
1402
+			if ($detail->batch) $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch);
1403
+			$dte[] = $outputlangs->transnoentitiesnoconv('printQty', $detail->qty);
1404
+			$libelleproduitservice .= "__N__  ".implode(" - ", $dte);
1405 1405
 		}
1406 1406
 	}
1407 1407
 
1408 1408
 	// Now we convert \n into br
1409
-	if (dol_textishtml($libelleproduitservice)) $libelleproduitservice=preg_replace('/__N__/','<br>',$libelleproduitservice);
1410
-	else $libelleproduitservice=preg_replace('/__N__/',"\n",$libelleproduitservice);
1411
-	$libelleproduitservice=dol_htmlentitiesbr($libelleproduitservice,1);
1409
+	if (dol_textishtml($libelleproduitservice)) $libelleproduitservice = preg_replace('/__N__/', '<br>', $libelleproduitservice);
1410
+	else $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice);
1411
+	$libelleproduitservice = dol_htmlentitiesbr($libelleproduitservice, 1);
1412 1412
 
1413 1413
 	return $libelleproduitservice;
1414 1414
 }
@@ -1422,25 +1422,25 @@  discard block
 block discarded – undo
1422 1422
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1423 1423
  * 	@return	string
1424 1424
  */
1425
-function pdf_getlinenum($object,$i,$outputlangs,$hidedetails=0)
1425
+function pdf_getlinenum($object, $i, $outputlangs, $hidedetails = 0)
1426 1426
 {
1427 1427
 	global $hookmanager;
1428 1428
 
1429
-	$reshook=0;
1430
-	$result='';
1429
+	$reshook = 0;
1430
+	$result = '';
1431 1431
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1432 1432
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1433 1433
 	{
1434 1434
 		$special_code = $object->lines[$i]->special_code;
1435
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1436
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1437
-		$action='';
1438
-		$reshook = $hookmanager->executeHooks('pdf_getlinenum',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1439
-		$result.=$hookmanager->resPrint;
1435
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1436
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1437
+		$action = '';
1438
+		$reshook = $hookmanager->executeHooks('pdf_getlinenum', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1439
+		$result .= $hookmanager->resPrint;
1440 1440
 	}
1441 1441
 	if (empty($reshook))
1442 1442
 	{
1443
-		$result.=dol_htmlentitiesbr($object->lines[$i]->num);
1443
+		$result .= dol_htmlentitiesbr($object->lines[$i]->num);
1444 1444
 	}
1445 1445
 	return $result;
1446 1446
 }
@@ -1455,25 +1455,25 @@  discard block
 block discarded – undo
1455 1455
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1456 1456
  * 	@return	string
1457 1457
  */
1458
-function pdf_getlineref($object,$i,$outputlangs,$hidedetails=0)
1458
+function pdf_getlineref($object, $i, $outputlangs, $hidedetails = 0)
1459 1459
 {
1460 1460
 	global $hookmanager;
1461 1461
 
1462
-	$reshook=0;
1463
-	$result='';
1462
+	$reshook = 0;
1463
+	$result = '';
1464 1464
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1465 1465
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1466 1466
 	{
1467 1467
 		$special_code = $object->lines[$i]->special_code;
1468
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1469
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1470
-		$action='';
1471
-		$reshook = $hookmanager->executeHooks('pdf_getlineref',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1472
-		$result.=$hookmanager->resPrint;
1468
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1469
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1470
+		$action = '';
1471
+		$reshook = $hookmanager->executeHooks('pdf_getlineref', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1472
+		$result .= $hookmanager->resPrint;
1473 1473
 	}
1474 1474
 	if (empty($reshook))
1475 1475
 	{
1476
-		$result.=dol_htmlentitiesbr($object->lines[$i]->product_ref);
1476
+		$result .= dol_htmlentitiesbr($object->lines[$i]->product_ref);
1477 1477
 	}
1478 1478
 	return $result;
1479 1479
 }
@@ -1487,25 +1487,25 @@  discard block
 block discarded – undo
1487 1487
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1488 1488
  * 	@return	string
1489 1489
  */
1490
-function pdf_getlineref_supplier($object,$i,$outputlangs,$hidedetails=0)
1490
+function pdf_getlineref_supplier($object, $i, $outputlangs, $hidedetails = 0)
1491 1491
 {
1492 1492
 	global $hookmanager;
1493 1493
 
1494
-	$reshook=0;
1495
-	$result='';
1494
+	$reshook = 0;
1495
+	$result = '';
1496 1496
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1497 1497
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1498 1498
 	{
1499 1499
 		$special_code = $object->lines[$i]->special_code;
1500
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1501
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1502
-		$action='';
1503
-		$reshook = $hookmanager->executeHooks('pdf_getlineref_supplier',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1504
-		$result.=$hookmanager->resPrint;
1500
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1501
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1502
+		$action = '';
1503
+		$reshook = $hookmanager->executeHooks('pdf_getlineref_supplier', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1504
+		$result .= $hookmanager->resPrint;
1505 1505
 	}
1506 1506
 	if (empty($reshook))
1507 1507
 	{
1508
-		$result.=dol_htmlentitiesbr($object->lines[$i]->ref_supplier);
1508
+		$result .= dol_htmlentitiesbr($object->lines[$i]->ref_supplier);
1509 1509
 	}
1510 1510
 	return $result;
1511 1511
 }
@@ -1519,51 +1519,51 @@  discard block
 block discarded – undo
1519 1519
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1520 1520
  * 	@return	string
1521 1521
  */
1522
-function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails=0)
1522
+function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails = 0)
1523 1523
 {
1524 1524
 	global $conf, $hookmanager, $mysoc;
1525 1525
 
1526
-	$result='';
1527
-	$reshook=0;
1526
+	$result = '';
1527
+	$reshook = 0;
1528 1528
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1529 1529
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
1530 1530
 	{
1531 1531
 		$special_code = $object->lines[$i]->special_code;
1532
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1533
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1534
-		$action='';
1535
-		$reshook = $hookmanager->executeHooks('pdf_getlinevatrate',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1532
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1533
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1534
+		$action = '';
1535
+		$reshook = $hookmanager->executeHooks('pdf_getlinevatrate', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1536 1536
 
1537
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1537
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1538 1538
 	}
1539 1539
 	if (empty($reshook))
1540 1540
 	{
1541 1541
 		if (empty($hidedetails) || $hidedetails > 1)
1542 1542
 		{
1543
-			$tmpresult='';
1543
+			$tmpresult = '';
1544 1544
 
1545
-			$tmpresult.=vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1);
1545
+			$tmpresult .= vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1);
1546 1546
 			if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX))
1547 1547
 			{
1548 1548
 				if ($object->lines[$i]->total_localtax1 != 0)
1549 1549
 				{
1550
-					if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1551
-					else $tmpresult='';
1552
-					$tmpresult.=vatrate(abs($object->lines[$i]->localtax1_tx), 0);
1550
+					if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/';
1551
+					else $tmpresult = '';
1552
+					$tmpresult .= vatrate(abs($object->lines[$i]->localtax1_tx), 0);
1553 1553
 				}
1554 1554
 			}
1555 1555
 			if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX))
1556 1556
 			{
1557 1557
 				if ($object->lines[$i]->total_localtax2 != 0)
1558 1558
 				{
1559
-					if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1560
-					else $tmpresult='';
1561
-					$tmpresult.=vatrate(abs($object->lines[$i]->localtax2_tx), 0);
1559
+					if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/';
1560
+					else $tmpresult = '';
1561
+					$tmpresult .= vatrate(abs($object->lines[$i]->localtax2_tx), 0);
1562 1562
 				}
1563 1563
 			}
1564
-			$tmpresult.= '%';
1564
+			$tmpresult .= '%';
1565 1565
 
1566
-			$result.=$tmpresult;
1566
+			$result .= $tmpresult;
1567 1567
 		}
1568 1568
 	}
1569 1569
 	return $result;
@@ -1578,32 +1578,32 @@  discard block
 block discarded – undo
1578 1578
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1579 1579
  * 	@return	string
1580 1580
  */
1581
-function pdf_getlineupexcltax($object,$i,$outputlangs,$hidedetails=0)
1581
+function pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails = 0)
1582 1582
 {
1583 1583
 	global $conf, $hookmanager;
1584 1584
 
1585
-	$sign=1;
1586
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1585
+	$sign = 1;
1586
+	if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
1587 1587
 
1588
-	$result='';
1589
-	$reshook=0;
1588
+	$result = '';
1589
+	$reshook = 0;
1590 1590
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1591 1591
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1592 1592
 	{
1593 1593
 		$special_code = $object->lines[$i]->special_code;
1594
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1595
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1596
-		$action='';
1597
-		$reshook = $hookmanager->executeHooks('pdf_getlineupexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1594
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1595
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1596
+		$action = '';
1597
+		$reshook = $hookmanager->executeHooks('pdf_getlineupexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1598 1598
 
1599
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1599
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1600 1600
 	}
1601 1601
 	if (empty($reshook))
1602 1602
 	{
1603 1603
 		if (empty($hidedetails) || $hidedetails > 1)
1604 1604
 		{
1605 1605
 			$subprice = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice);
1606
-			$result.=price($sign * $subprice, 0, $outputlangs);
1606
+			$result .= price($sign * $subprice, 0, $outputlangs);
1607 1607
 		}
1608 1608
 	}
1609 1609
 	return $result;
@@ -1618,29 +1618,29 @@  discard block
 block discarded – undo
1618 1618
  *  @param	int			$hidedetails		Hide value (0 = no,	1 = yes, 2 = just special lines)
1619 1619
  *  @return	string
1620 1620
  */
1621
-function pdf_getlineupwithtax($object,$i,$outputlangs,$hidedetails=0)
1621
+function pdf_getlineupwithtax($object, $i, $outputlangs, $hidedetails = 0)
1622 1622
 {
1623
-	global $hookmanager,$conf;
1623
+	global $hookmanager, $conf;
1624 1624
 
1625
-	$sign=1;
1626
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1625
+	$sign = 1;
1626
+	if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
1627 1627
 
1628
-	$result='';
1629
-	$reshook=0;
1628
+	$result = '';
1629
+	$reshook = 0;
1630 1630
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1631 1631
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1632 1632
 	{
1633 1633
 		$special_code = $object->lines[$i]->special_code;
1634
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1635
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1636
-		$action='';
1637
-		$reshook = $hookmanager->executeHooks('pdf_getlineupwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1634
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1635
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1636
+		$action = '';
1637
+		$reshook = $hookmanager->executeHooks('pdf_getlineupwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1638 1638
 
1639
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1639
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1640 1640
 	}
1641 1641
 	if (empty($reshook))
1642 1642
 	{
1643
-		if (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice)*($object->lines[$i]->tva_tx)/100), 0, $outputlangs);
1643
+		if (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs);
1644 1644
 	}
1645 1645
 	return $result;
1646 1646
 }
@@ -1654,27 +1654,27 @@  discard block
 block discarded – undo
1654 1654
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1655 1655
  *  @return	string
1656 1656
  */
1657
-function pdf_getlineqty($object,$i,$outputlangs,$hidedetails=0)
1657
+function pdf_getlineqty($object, $i, $outputlangs, $hidedetails = 0)
1658 1658
 {
1659 1659
 	global $hookmanager;
1660 1660
 
1661
-	$result='';
1662
-	$reshook=0;
1661
+	$result = '';
1662
+	$reshook = 0;
1663 1663
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1664 1664
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1665 1665
 	{
1666 1666
 		$special_code = $object->lines[$i]->special_code;
1667
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1668
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1669
-		$action='';
1670
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1667
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1668
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1669
+		$action = '';
1670
+		$reshook = $hookmanager->executeHooks('pdf_getlineqty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1671 1671
 
1672
-		if(!empty($hookmanager->resPrint)) $result=$hookmanager->resPrint;
1672
+		if (!empty($hookmanager->resPrint)) $result = $hookmanager->resPrint;
1673 1673
 	}
1674 1674
     if (empty($reshook))
1675 1675
 	{
1676 1676
 	   if ($object->lines[$i]->special_code == 3) return '';
1677
-	   if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty;
1677
+	   if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty;
1678 1678
 	}
1679 1679
 	return $result;
1680 1680
 }
@@ -1688,27 +1688,27 @@  discard block
 block discarded – undo
1688 1688
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1689 1689
  * 	@return	string
1690 1690
  */
1691
-function pdf_getlineqty_asked($object,$i,$outputlangs,$hidedetails=0)
1691
+function pdf_getlineqty_asked($object, $i, $outputlangs, $hidedetails = 0)
1692 1692
 {
1693 1693
 	global $hookmanager;
1694 1694
 
1695
-	$reshook=0;
1696
-	$result='';
1695
+	$reshook = 0;
1696
+	$result = '';
1697 1697
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1698 1698
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1699 1699
 	{
1700 1700
 		$special_code = $object->lines[$i]->special_code;
1701
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1702
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1703
-		$action='';
1704
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty_asked',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1701
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1702
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1703
+		$action = '';
1704
+		$reshook = $hookmanager->executeHooks('pdf_getlineqty_asked', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1705 1705
 
1706
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1706
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1707 1707
 	}
1708 1708
 	if (empty($reshook))
1709 1709
 	{
1710 1710
         if ($object->lines[$i]->special_code == 3) return '';
1711
-        if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_asked;
1711
+        if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked;
1712 1712
 	}
1713 1713
 	return $result;
1714 1714
 }
@@ -1722,27 +1722,27 @@  discard block
 block discarded – undo
1722 1722
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1723 1723
  * 	@return	string
1724 1724
  */
1725
-function pdf_getlineqty_shipped($object,$i,$outputlangs,$hidedetails=0)
1725
+function pdf_getlineqty_shipped($object, $i, $outputlangs, $hidedetails = 0)
1726 1726
 {
1727 1727
 	global $hookmanager;
1728 1728
 
1729
-	$reshook=0;
1730
-	$result='';
1729
+	$reshook = 0;
1730
+	$result = '';
1731 1731
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1732 1732
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1733 1733
 	{
1734 1734
 		$special_code = $object->lines[$i]->special_code;
1735
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1736
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1737
-		$action='';
1738
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1735
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1736
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1737
+		$action = '';
1738
+		$reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1739 1739
 
1740
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1740
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1741 1741
 	}
1742 1742
 	if (empty($reshook))
1743 1743
 	{
1744 1744
         if ($object->lines[$i]->special_code == 3) return '';
1745
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_shipped;
1745
+	    if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped;
1746 1746
 	}
1747 1747
 	return $result;
1748 1748
 }
@@ -1756,27 +1756,27 @@  discard block
 block discarded – undo
1756 1756
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1757 1757
  * 	@return	string
1758 1758
  */
1759
-function pdf_getlineqty_keeptoship($object,$i,$outputlangs,$hidedetails=0)
1759
+function pdf_getlineqty_keeptoship($object, $i, $outputlangs, $hidedetails = 0)
1760 1760
 {
1761 1761
 	global $hookmanager;
1762 1762
 
1763
-	$reshook=0;
1764
-    $result='';
1763
+	$reshook = 0;
1764
+    $result = '';
1765 1765
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1766 1766
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1767 1767
 	{
1768 1768
 		$special_code = $object->lines[$i]->special_code;
1769
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1770
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1771
-		$action='';
1772
-		$reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1769
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1770
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1771
+		$action = '';
1772
+		$reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1773 1773
 
1774
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1774
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1775 1775
 	}
1776 1776
 	if (empty($reshook))
1777 1777
 	{
1778 1778
         if ($object->lines[$i]->special_code == 3) return '';
1779
-		if (empty($hidedetails) || $hidedetails > 1) $result.=($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
1779
+		if (empty($hidedetails) || $hidedetails > 1) $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
1780 1780
 	}
1781 1781
 	return $result;
1782 1782
 }
@@ -1795,8 +1795,8 @@  discard block
 block discarded – undo
1795 1795
 {
1796 1796
 	global $langs;
1797 1797
 
1798
-	$reshook=0;
1799
-    $result='';
1798
+	$reshook = 0;
1799
+    $result = '';
1800 1800
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1801 1801
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1802 1802
 	{
@@ -1811,14 +1811,14 @@  discard block
 block discarded – undo
1811 1811
 			'special_code' => $special_code
1812 1812
 		);
1813 1813
 		$action = '';
1814
-		$reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1814
+		$reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1815 1815
 
1816
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1816
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1817 1817
 	}
1818 1818
 	if (empty($reshook))
1819 1819
 	{
1820 1820
         if ($object->lines[$i]->special_code == 3) return '';
1821
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
1821
+	    if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
1822 1822
 	}
1823 1823
 	return $result;
1824 1824
 }
@@ -1833,29 +1833,29 @@  discard block
 block discarded – undo
1833 1833
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1834 1834
  * 	@return	string
1835 1835
  */
1836
-function pdf_getlineremisepercent($object,$i,$outputlangs,$hidedetails=0)
1836
+function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0)
1837 1837
 {
1838 1838
 	global $hookmanager;
1839 1839
 
1840 1840
 	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1841 1841
 
1842
-	$reshook=0;
1843
-	$result='';
1842
+	$reshook = 0;
1843
+	$result = '';
1844 1844
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1845 1845
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1846 1846
 	{
1847 1847
 		$special_code = $object->lines[$i]->special_code;
1848
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1849
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1850
-		$action='';
1851
-		$reshook = $hookmanager->executeHooks('pdf_getlineremisepercent',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1848
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1849
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1850
+		$action = '';
1851
+		$reshook = $hookmanager->executeHooks('pdf_getlineremisepercent', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1852 1852
 
1853
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1853
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1854 1854
 	}
1855 1855
 	if (empty($reshook))
1856 1856
 	{
1857 1857
         if ($object->lines[$i]->special_code == 3) return '';
1858
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=dol_print_reduction($object->lines[$i]->remise_percent,$outputlangs);
1858
+	    if (empty($hidedetails) || $hidedetails > 1) $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs);
1859 1859
 	}
1860 1860
 	return $result;
1861 1861
 }
@@ -1875,8 +1875,8 @@  discard block
 block discarded – undo
1875 1875
 	if (empty($hookmanager)) global $hookmanager;
1876 1876
 	global $conf;
1877 1877
 
1878
-	$reshook=0;
1879
-    $result='';
1878
+	$reshook = 0;
1879
+    $result = '';
1880 1880
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1881 1881
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1882 1882
 	{
@@ -1884,9 +1884,9 @@  discard block
 block discarded – undo
1884 1884
 		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1885 1885
 		$parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code);
1886 1886
 		$action = '';
1887
-		$reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1887
+		$reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1888 1888
 
1889
-		if(!empty($hookmanager->resPrint)) return $hookmanager->resPrint;
1889
+		if (!empty($hookmanager->resPrint)) return $hookmanager->resPrint;
1890 1890
 	}
1891 1891
 	if (empty($reshook))
1892 1892
 	{
@@ -1900,10 +1900,10 @@  discard block
 block discarded – undo
1900 1900
 				{
1901 1901
 			 		$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1902 1902
 				}
1903
-			 	$result = ($object->lines[$i]->situation_percent - $prev_progress) . '%';
1903
+			 	$result = ($object->lines[$i]->situation_percent - $prev_progress).'%';
1904 1904
 			}
1905 1905
 			else
1906
-				$result = $object->lines[$i]->situation_percent . '%';
1906
+				$result = $object->lines[$i]->situation_percent.'%';
1907 1907
 	  	}
1908 1908
 	}
1909 1909
 	return $result;
@@ -1918,25 +1918,25 @@  discard block
 block discarded – undo
1918 1918
  *  @param	int			$hidedetails		Hide details (0=no, 1=yes, 2=just special lines)
1919 1919
  * 	@return	string							Return total of line excl tax
1920 1920
  */
1921
-function pdf_getlinetotalexcltax($object,$i,$outputlangs,$hidedetails=0)
1921
+function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0)
1922 1922
 {
1923 1923
 	global $conf, $hookmanager;
1924 1924
 
1925
-	$sign=1;
1926
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1925
+	$sign = 1;
1926
+	if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
1927 1927
 
1928
-	$reshook=0;
1929
-	$result='';
1928
+	$reshook = 0;
1929
+	$result = '';
1930 1930
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1931 1931
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1932 1932
 	{
1933 1933
 		$special_code = $object->lines[$i]->special_code;
1934
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1935
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code, 'sign'=>$sign);
1936
-		$action='';
1937
-		$reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1934
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1935
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code, 'sign'=>$sign);
1936
+		$action = '';
1937
+		$reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1938 1938
 
1939
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1939
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1940 1940
 	}
1941 1941
     if (empty($reshook))
1942 1942
     {
@@ -1956,10 +1956,10 @@  discard block
 block discarded – undo
1956 1956
 					$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1957 1957
 					$progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100;
1958 1958
         		}
1959
-				$result.=price($sign * ($total_ht/($object->lines[$i]->situation_percent/100)) * $progress, 0, $outputlangs);
1959
+				$result .= price($sign * ($total_ht / ($object->lines[$i]->situation_percent / 100)) * $progress, 0, $outputlangs);
1960 1960
         	}
1961 1961
         	else
1962
-			$result.=price($sign * $total_ht, 0, $outputlangs);
1962
+			$result .= price($sign * $total_ht, 0, $outputlangs);
1963 1963
 	}
1964 1964
     }
1965 1965
 	return $result;
@@ -1974,33 +1974,33 @@  discard block
 block discarded – undo
1974 1974
  *  @param	int			$hidedetails		Hide value (0 = no, 1 = yes, 2 = just special lines)
1975 1975
  *  @return	string							Return total of line incl tax
1976 1976
  */
1977
-function pdf_getlinetotalwithtax($object,$i,$outputlangs,$hidedetails=0)
1977
+function pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails = 0)
1978 1978
 {
1979
-	global $hookmanager,$conf;
1979
+	global $hookmanager, $conf;
1980 1980
 
1981
-	$sign=1;
1982
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1981
+	$sign = 1;
1982
+	if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1;
1983 1983
 
1984
-	$reshook=0;
1985
-	$result='';
1984
+	$reshook = 0;
1985
+	$result = '';
1986 1986
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1987 1987
 	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1988 1988
 	{
1989 1989
 		$special_code = $object->lines[$i]->special_code;
1990
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1991
-		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1992
-		$action='';
1993
-		$reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1990
+		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1991
+		$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
1992
+		$action = '';
1993
+		$reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1994 1994
 
1995
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1995
+		if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint;
1996 1996
 	}
1997 1997
 	if (empty($reshook))
1998 1998
 	{
1999 1999
 		if ($object->lines[$i]->special_code == 3)
2000 2000
     	{
2001
-    		$result.=$outputlangs->transnoentities("Option");
2001
+    		$result .= $outputlangs->transnoentities("Option");
2002 2002
     	}
2003
-		elseif (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht)*($object->lines[$i]->tva_tx)/100, 0, $outputlangs);
2003
+		elseif (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht) * ($object->lines[$i]->tva_tx) / 100, 0, $outputlangs);
2004 2004
 	}
2005 2005
 	return $result;
2006 2006
 }
@@ -2014,36 +2014,36 @@  discard block
 block discarded – undo
2014 2014
  * 	@return	integer
2015 2015
  *  @deprecated Not used by Dolibarr core, so will be removed.
2016 2016
  */
2017
-function pdf_getTotalQty($object,$type,$outputlangs)
2017
+function pdf_getTotalQty($object, $type, $outputlangs)
2018 2018
 {
2019 2019
 	global $hookmanager;
2020 2020
 
2021
-	$total=0;
2022
-	$nblignes=count($object->lines);
2021
+	$total = 0;
2022
+	$nblignes = count($object->lines);
2023 2023
 
2024 2024
 	// Loop on each lines
2025
-	for ($i = 0 ; $i < $nblignes ; $i++)
2025
+	for ($i = 0; $i < $nblignes; $i++)
2026 2026
 	{
2027 2027
 		if ($object->lines[$i]->special_code != 3)
2028 2028
 		{
2029
-			if ($type=='all')
2029
+			if ($type == 'all')
2030 2030
 			{
2031 2031
 				$total += $object->lines[$i]->qty;
2032 2032
 			}
2033
-			else if ($type==9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line)))
2033
+			else if ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line)))
2034 2034
 			{
2035 2035
 				$special_code = $object->lines[$i]->special_code;
2036
-				if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2037
-				$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
2038
-				$action='';
2039
-				$reshook = $hookmanager->executeHooks('pdf_getTotalQty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2036
+				if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2037
+				$parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code);
2038
+				$action = '';
2039
+				$reshook = $hookmanager->executeHooks('pdf_getTotalQty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
2040 2040
 				return $hookmanager->resPrint;
2041 2041
 			}
2042
-			else if ($type==0 && $object->lines[$i]->product_type == 0)
2042
+			else if ($type == 0 && $object->lines[$i]->product_type == 0)
2043 2043
 			{
2044 2044
 				$total += $object->lines[$i]->qty;
2045 2045
 			}
2046
-			else if ($type==1 && $object->lines[$i]->product_type == 1)
2046
+			else if ($type == 1 && $object->lines[$i]->product_type == 1)
2047 2047
 			{
2048 2048
 				$total += $object->lines[$i]->qty;
2049 2049
 			}
@@ -2061,15 +2061,15 @@  discard block
 block discarded – undo
2061 2061
  * 	@param	Translate	$outputlangs	Object lang for output
2062 2062
  * 	@return	array                       Linked objects
2063 2063
  */
2064
-function pdf_getLinkedObjects($object,$outputlangs)
2064
+function pdf_getLinkedObjects($object, $outputlangs)
2065 2065
 {
2066 2066
 	global $hookmanager;
2067 2067
 
2068
-	$linkedobjects=array();
2068
+	$linkedobjects = array();
2069 2069
 
2070 2070
 	$object->fetchObjectLinked();
2071 2071
 
2072
-	foreach($object->linkedObjects as $objecttype => $objects)
2072
+	foreach ($object->linkedObjects as $objecttype => $objects)
2073 2073
 	{
2074 2074
 	    if ($objecttype == 'facture')
2075 2075
 	    {
@@ -2079,63 +2079,63 @@  discard block
 block discarded – undo
2079 2079
 		{
2080 2080
 			$outputlangs->load('propal');
2081 2081
 
2082
-			foreach($objects as $elementobject)
2082
+			foreach ($objects as $elementobject)
2083 2083
 			{
2084 2084
 				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefProposal");
2085 2085
 				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
2086 2086
 				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal");
2087
-				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2087
+				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs);
2088 2088
 			}
2089 2089
 		}
2090 2090
 		else if ($objecttype == 'commande' || $objecttype == 'supplier_order')
2091 2091
 		{
2092 2092
 			$outputlangs->load('orders');
2093
-			foreach($objects as $elementobject)
2093
+			foreach ($objects as $elementobject)
2094 2094
 			{
2095 2095
 				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder");
2096
-				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref) . ($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '') . ($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : '');
2096
+				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref).($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '').($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : '');
2097 2097
 				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate");
2098
-				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2098
+				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs);
2099 2099
 			}
2100 2100
 		}
2101 2101
 		else if ($objecttype == 'contrat')
2102 2102
 		{
2103 2103
 			$outputlangs->load('contracts');
2104
-			foreach($objects as $elementobject)
2104
+			foreach ($objects as $elementobject)
2105 2105
 			{
2106 2106
 				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefContract");
2107 2107
 				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);
2108 2108
 				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract");
2109
-				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat,'day','',$outputlangs);
2109
+				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat, 'day', '', $outputlangs);
2110 2110
 			}
2111 2111
 		}
2112 2112
 		else if ($objecttype == 'shipping')
2113 2113
 		{
2114 2114
 			$outputlangs->loadLangs(array("orders", "sendings"));
2115 2115
 
2116
-			foreach($objects as $x => $elementobject)
2116
+			foreach ($objects as $x => $elementobject)
2117 2117
 			{
2118
-			    $order=null;
2118
+			    $order = null;
2119 2119
 			    // We concat this record info into fields xxx_value. title is overwrote.
2120 2120
 			    if (empty($object->linkedObjects['commande']) && $object->element != 'commande')	// There is not already a link to order and object is not the order, so we show also info with order
2121 2121
 			    {
2122 2122
 			        $elementobject->fetchObjectLinked();
2123
-			        if (! empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']);
2123
+			        if (!empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']);
2124 2124
 			    }
2125
-			    if (! is_object($order))
2125
+			    if (!is_object($order))
2126 2126
 			    {
2127 2127
 			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending");
2128
-			        if (! empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'].=' / ';
2129
-			        $linkedobjects[$objecttype]['ref_value'].= $outputlangs->transnoentities($elementobject->ref);
2128
+			        if (!empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] .= ' / ';
2129
+			        $linkedobjects[$objecttype]['ref_value'] .= $outputlangs->transnoentities($elementobject->ref);
2130 2130
 			        //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment");
2131 2131
 			        //if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / ';
2132 2132
 			        //$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs);
2133 2133
 			    }
2134 2134
 			    else
2135 2135
 			    {
2136
-			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder") . ' / ' . $outputlangs->transnoentities("RefSending");
2137
-			        if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref) . ($order->ref_client ? ' ('.$order->ref_client.')' : '');
2138
-			        $linkedobjects[$objecttype]['ref_value'].= ' / ' . $outputlangs->transnoentities($elementobject->ref);
2136
+			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder").' / '.$outputlangs->transnoentities("RefSending");
2137
+			        if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : '');
2138
+			        $linkedobjects[$objecttype]['ref_value'] .= ' / '.$outputlangs->transnoentities($elementobject->ref);
2139 2139
 			        //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : '');
2140 2140
 			        //if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs);
2141 2141
 			        //$linkedobjects[$objecttype]['date_value'].= ($elementobject->date_delivery ? ' / ' . dol_print_date($elementobject->date_delivery,'day','',$outputlangs) : '');
@@ -2148,9 +2148,9 @@  discard block
 block discarded – undo
2148 2148
 	if (is_object($hookmanager))
2149 2149
 	{
2150 2150
 		$parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs);
2151
-		$action='';
2152
-		$hookmanager->executeHooks('pdf_getLinkedObjects',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2153
-		if (! empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray;
2151
+		$action = '';
2152
+		$hookmanager->executeHooks('pdf_getLinkedObjects', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
2153
+		if (!empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray;
2154 2154
 	}
2155 2155
 
2156 2156
 	return $linkedobjects;
@@ -2167,22 +2167,22 @@  discard block
 block discarded – undo
2167 2167
 {
2168 2168
 	global $conf;
2169 2169
 
2170
-	$maxwidth=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);
2171
-	$maxheight=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT)?32:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT);
2170
+	$maxwidth = (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);
2171
+	$maxheight = (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT) ? 32 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT);
2172 2172
 	include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
2173
-	$tmp=dol_getImageSize($realpath);
2173
+	$tmp = dol_getImageSize($realpath);
2174 2174
 	if ($tmp['height'])
2175 2175
 	{
2176
-		$width=(int) round($maxheight*$tmp['width']/$tmp['height']);	// I try to use maxheight
2176
+		$width = (int) round($maxheight * $tmp['width'] / $tmp['height']); // I try to use maxheight
2177 2177
 		if ($width > $maxwidth)	// Pb with maxheight, so i use maxwidth
2178 2178
 		{
2179
-			$width=$maxwidth;
2180
-			$height=(int) round($maxwidth*$tmp['height']/$tmp['width']);
2179
+			$width = $maxwidth;
2180
+			$height = (int) round($maxwidth * $tmp['height'] / $tmp['width']);
2181 2181
 		}
2182 2182
 		else	// No pb with maxheight
2183 2183
 		{
2184
-			$height=$maxheight;
2184
+			$height = $maxheight;
2185 2185
 		}
2186 2186
 	}
2187
-	return array('width'=>$width,'height'=>$height);
2187
+	return array('width'=>$width, 'height'=>$height);
2188 2188
 }
Please login to merge, or discard this patch.
Braces   +510 added lines, -221 removed lines patch added patch discarded remove patch
@@ -50,8 +50,9 @@  discard block
 block discarded – undo
50 50
 	{
51 51
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
52 52
 		$pdfformat=dol_getDefaultFormat($outputlangs);
53
+	} else {
54
+	    $pdfformat=$conf->global->MAIN_PDF_FORMAT;
53 55
 	}
54
-	else $pdfformat=$conf->global->MAIN_PDF_FORMAT;
55 56
 
56 57
 	$sql="SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format";
57 58
 	$sql.=" WHERE code = '".$pdfformat."'";
@@ -123,17 +124,25 @@  discard block
 block discarded – undo
123 124
 	require_once TCPDF_PATH.'tcpdf.php';
124 125
 
125 126
 	// We need to instantiate tcpdi object (instead of tcpdf) to use merging features. But we can disable it (this will break all merge features).
126
-	if (empty($conf->global->MAIN_DISABLE_TCPDI)) require_once TCPDI_PATH.'tcpdi.php';
127
+	if (empty($conf->global->MAIN_DISABLE_TCPDI)) {
128
+	    require_once TCPDI_PATH.'tcpdi.php';
129
+	}
127 130
 
128 131
 	//$arrayformat=pdf_getFormat();
129 132
 	//$format=array($arrayformat['width'],$arrayformat['height']);
130 133
 	//$metric=$arrayformat['unit'];
131 134
 
132 135
 	$pdfa=false;											// PDF-1.3
133
-	if (! empty($conf->global->PDF_USE_1A)) $pdfa=true;		// PDF1/A
136
+	if (! empty($conf->global->PDF_USE_1A)) {
137
+	    $pdfa=true;
138
+	}
139
+	// PDF1/A
134 140
 
135
-	if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
136
-	else $pdf = new TCPDF($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
141
+	if (class_exists('TCPDI')) {
142
+	    $pdf = new TCPDI($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
143
+	} else {
144
+	    $pdf = new TCPDF($pagetype,$metric,$format,true,'UTF-8',false,$pdfa);
145
+	}
137 146
 
138 147
 	// Protection and encryption of pdf
139 148
 	if (! empty($conf->global->PDF_SECURITY_ENCRYPTION))
@@ -202,14 +211,18 @@  discard block
 block discarded – undo
202 211
 {
203 212
 	global $conf;
204 213
 
205
-	if (! empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT;
214
+	if (! empty($conf->global->MAIN_PDF_FORCE_FONT)) {
215
+	    return $conf->global->MAIN_PDF_FORCE_FONT;
216
+	}
206 217
 
207 218
 	$font='Helvetica'; // By default, for FPDI, or ISO language on TCPDF
208
-	if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
219
+	if (class_exists('TCPDF')) {
220
+	    // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
209 221
 	{
210 222
 		if ($outputlangs->trans('FONTFORPDF')!='FONTFORPDF')
211 223
 		{
212 224
 			$font=$outputlangs->trans('FONTFORPDF');
225
+	}
213 226
 		}
214 227
 	}
215 228
 	return $font;
@@ -224,11 +237,13 @@  discard block
 block discarded – undo
224 237
 function pdf_getPDFFontSize($outputlangs)
225 238
 {
226 239
 	$size=10;                   // By default, for FPDI or ISO language on TCPDF
227
-	if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
240
+	if (class_exists('TCPDF')) {
241
+	    // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
228 242
 	{
229 243
 		if ($outputlangs->trans('FONTSIZEFORPDF')!='FONTSIZEFORPDF')
230 244
 		{
231 245
 			$size = (int) $outputlangs->trans('FONTSIZEFORPDF');
246
+	}
232 247
 		}
233 248
 	}
234 249
 	return $size;
@@ -252,7 +267,9 @@  discard block
 block discarded – undo
252 267
 	if ($tmp['height'])
253 268
 	{
254 269
 		$width=round($height*$tmp['width']/$tmp['height']);
255
-		if ($width > $maxwidth) $height=$height*$maxwidth/$width;
270
+		if ($width > $maxwidth) {
271
+		    $height=$height*$maxwidth/$width;
272
+		}
256 273
 	}
257 274
 	//print $tmp['width'].' '.$tmp['height'].' '.$width; exit;
258 275
 	return $height;
@@ -283,8 +300,7 @@  discard block
 block discarded – undo
283 300
     $height = 0;
284 301
     if ($end_page == $start_page) {
285 302
         $height = $end_y - $start_y;
286
-    }
287
-    else
303
+    } else
288 304
     {
289 305
         for ($page=$start_page; $page <= $end_page; ++$page) {
290 306
         	$pdf->setPage($page);
@@ -354,15 +370,33 @@  discard block
 block discarded – undo
354 370
 {
355 371
 	global $conf, $hookmanager;
356 372
 
357
-	if ($mode == 'source' && ! is_object($sourcecompany)) return -1;
358
-	if ($mode == 'target' && ! is_object($targetcompany)) return -1;
373
+	if ($mode == 'source' && ! is_object($sourcecompany)) {
374
+	    return -1;
375
+	}
376
+	if ($mode == 'target' && ! is_object($targetcompany)) {
377
+	    return -1;
378
+	}
359 379
 
360
-	if (! empty($sourcecompany->state_id) && empty($sourcecompany->departement)) $sourcecompany->departement=getState($sourcecompany->state_id); //TODO deprecated
361
-	if (! empty($sourcecompany->state_id) && empty($sourcecompany->state))       $sourcecompany->state=getState($sourcecompany->state_id);
362
-	if (! empty($sourcecompany->state_id) && !isset($sourcecompany->departement_id))   $sourcecompany->departement_id=getState($sourcecompany->state_id,'2');
363
-	if (! empty($targetcompany->state_id) && empty($targetcompany->departement)) $targetcompany->departement=getState($targetcompany->state_id); //TODO deprecated
364
-	if (! empty($targetcompany->state_id) && empty($targetcompany->state))       $targetcompany->state=getState($targetcompany->state_id);
365
-	if (! empty($targetcompany->state_id) && !isset($targetcompany->departement_id))   $targetcompany->departement_id=getState($targetcompany->state_id,'2');
380
+	if (! empty($sourcecompany->state_id) && empty($sourcecompany->departement)) {
381
+	    $sourcecompany->departement=getState($sourcecompany->state_id);
382
+	}
383
+	//TODO deprecated
384
+	if (! empty($sourcecompany->state_id) && empty($sourcecompany->state)) {
385
+	    $sourcecompany->state=getState($sourcecompany->state_id);
386
+	}
387
+	if (! empty($sourcecompany->state_id) && !isset($sourcecompany->departement_id)) {
388
+	    $sourcecompany->departement_id=getState($sourcecompany->state_id,'2');
389
+	}
390
+	if (! empty($targetcompany->state_id) && empty($targetcompany->departement)) {
391
+	    $targetcompany->departement=getState($targetcompany->state_id);
392
+	}
393
+	//TODO deprecated
394
+	if (! empty($targetcompany->state_id) && empty($targetcompany->state)) {
395
+	    $targetcompany->state=getState($targetcompany->state_id);
396
+	}
397
+	if (! empty($targetcompany->state_id) && !isset($targetcompany->departement_id)) {
398
+	    $targetcompany->departement_id=getState($targetcompany->state_id,'2');
399
+	}
366 400
 
367 401
 	$reshook=0;
368 402
 	$stringaddress = '';
@@ -378,61 +412,85 @@  discard block
 block discarded – undo
378 412
     	if ($mode == 'source')
379 413
     	{
380 414
     		$withCountry = 0;
381
-    		if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1;
415
+    		if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
416
+    		    $withCountry = 1;
417
+    		}
382 418
 
383 419
     		$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n";
384 420
 
385 421
     		if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS))
386 422
     		{
387 423
     			// Phone
388
-    			if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
424
+    			if ($sourcecompany->phone) {
425
+    			    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone);
426
+    			}
389 427
     			// Fax
390
-    			if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
428
+    			if ($sourcecompany->fax) {
429
+    			    $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax);
430
+    			}
391 431
     			// EMail
392
-    			if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
432
+    			if ($sourcecompany->email) {
433
+    			    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email);
434
+    			}
393 435
     			// Web
394
-    			if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
436
+    			if ($sourcecompany->url) {
437
+    			    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url);
438
+    			}
395 439
     		}
396 440
     		// Intra VAT
397 441
     		if (! empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS))
398 442
     		{
399
-    			if ($sourcecompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
443
+    			if ($sourcecompany->tva_intra) {
444
+    			    $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra);
445
+    			}
400 446
     		}
401 447
     		// Professionnal Ids
402 448
     		if (! empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof1))
403 449
     		{
404 450
     			$tmp=$outputlangs->transcountrynoentities("ProfId1",$sourcecompany->country_code);
405
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
451
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
452
+    			    $tmp=$reg[1];
453
+    			}
406 454
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1);
407 455
     		}
408 456
     		if (! empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof2))
409 457
     		{
410 458
     			$tmp=$outputlangs->transcountrynoentities("ProfId2",$sourcecompany->country_code);
411
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
459
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
460
+    			    $tmp=$reg[1];
461
+    			}
412 462
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2);
413 463
     		}
414 464
     		if (! empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof3))
415 465
     		{
416 466
     			$tmp=$outputlangs->transcountrynoentities("ProfId3",$sourcecompany->country_code);
417
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
467
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
468
+    			    $tmp=$reg[1];
469
+    			}
418 470
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3);
419 471
     		}
420 472
     		if (! empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof4))
421 473
     		{
422 474
     			$tmp=$outputlangs->transcountrynoentities("ProfId4",$sourcecompany->country_code);
423
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
475
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
476
+    			    $tmp=$reg[1];
477
+    			}
424 478
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4);
425 479
     		}
426 480
     		if (! empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof5))
427 481
     		{
428 482
     			$tmp=$outputlangs->transcountrynoentities("ProfId5",$sourcecompany->country_code);
429
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
483
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
484
+    			    $tmp=$reg[1];
485
+    			}
430 486
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5);
431 487
     		}
432 488
     		if (! empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof6))
433 489
     		{
434 490
     			$tmp=$outputlangs->transcountrynoentities("ProfId6",$sourcecompany->country_code);
435
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
491
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
492
+    			    $tmp=$reg[1];
493
+    			}
436 494
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6);
437 495
     		}
438 496
     	}
@@ -460,8 +518,7 @@  discard block
 block discarded – undo
460 518
     			// Country
461 519
     			if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) {
462 520
     				$stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code));
463
-    			}
464
-    			else if (empty($targetcontact->country_code) && !empty($targetcompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
521
+    			} else if (empty($targetcontact->country_code) && !empty($targetcompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) {
465 522
     				$stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
466 523
     			}
467 524
 
@@ -470,58 +527,87 @@  discard block
 block discarded – undo
470 527
     				// Phone
471 528
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
472 529
     			    {
473
-        				if (! empty($targetcontact->phone_pro) || ! empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
474
-        				if (! empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
475
-        				if (! empty($targetcontact->phone_pro) && ! empty($targetcontact->phone_mobile)) $stringaddress .= " / ";
476
-        				if (! empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
530
+        				if (! empty($targetcontact->phone_pro) || ! empty($targetcontact->phone_mobile)) {
531
+        				    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
532
+        				}
533
+        				if (! empty($targetcontact->phone_pro)) {
534
+        				    $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro);
535
+        				}
536
+        				if (! empty($targetcontact->phone_pro) && ! empty($targetcontact->phone_mobile)) {
537
+        				    $stringaddress .= " / ";
538
+        				}
539
+        				if (! empty($targetcontact->phone_mobile)) {
540
+        				    $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile);
541
+        				}
477 542
     			    }
478 543
     				// Fax
479 544
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
480 545
     			    {
481
-                        if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
546
+                        if ($targetcontact->fax) {
547
+                            $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax);
548
+                        }
482 549
     			    }
483 550
     				// EMail
484 551
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
485 552
     			    {
486
-                        if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
553
+                        if ($targetcontact->email) {
554
+                            $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email);
555
+                        }
487 556
     			    }
488 557
     				// Web
489 558
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
490 559
     			    {
491
-                        if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
560
+                        if ($targetcontact->url) {
561
+                            $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url);
562
+                        }
492 563
     			    }
493 564
     			}
494
-    		}
495
-    		else
565
+    		} else
496 566
     		{
497 567
     			$stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcompany));
498 568
     			// Country
499
-    			if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
569
+    			if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) {
570
+    			    $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code));
571
+    			}
500 572
 
501 573
     			if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/',$mode))
502 574
     			{
503 575
     				// Phone
504 576
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/',$mode))
505 577
     			    {
506
-    			    	if (! empty($targetcompany->phone) || ! empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
507
-	    				if (! empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
508
-    					if (! empty($targetcompany->phone) && ! empty($targetcompany->phone_mobile)) $stringaddress .= " / ";
509
-    					if (! empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
578
+    			    	if (! empty($targetcompany->phone) || ! empty($targetcompany->phone_mobile)) {
579
+    			    	    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Phone").": ";
580
+    			    	}
581
+	    				if (! empty($targetcompany->phone)) {
582
+	    				    $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone);
583
+	    				}
584
+    					if (! empty($targetcompany->phone) && ! empty($targetcompany->phone_mobile)) {
585
+    					    $stringaddress .= " / ";
586
+    					}
587
+    					if (! empty($targetcompany->phone_mobile)) {
588
+    					    $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile);
589
+    					}
510 590
     			    }
511 591
     				// Fax
512 592
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/',$mode))
513 593
     			    {
514
-    			    	if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
594
+    			    	if ($targetcompany->fax) {
595
+    			    	    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax);
596
+    			    	}
515 597
     			    }
516 598
     				// EMail
517 599
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/',$mode))
518 600
     			    {
519
-    			    	if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
601
+    			    	if ($targetcompany->email) {
602
+    			    	    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email);
603
+    			    	}
520 604
     			    }
521 605
     				// Web
522 606
     			    if (! empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/',$mode))
523 607
     			    {
524
-    			    	if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
608
+    			    	if ($targetcompany->url) {
609
+    			    	    $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url);
610
+    			    	}
525 611
     			    }
526 612
     			}
527 613
     		}
@@ -529,44 +615,58 @@  discard block
 block discarded – undo
529 615
     		// Intra VAT
530 616
     		if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS))
531 617
     		{
532
-    			if ($targetcompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
618
+    			if ($targetcompany->tva_intra) {
619
+    			    $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra);
620
+    			}
533 621
     		}
534 622
 
535 623
     		// Professionnal Ids
536 624
     		if (! empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && ! empty($targetcompany->idprof1))
537 625
     		{
538 626
     			$tmp=$outputlangs->transcountrynoentities("ProfId1",$targetcompany->country_code);
539
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
627
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
628
+    			    $tmp=$reg[1];
629
+    			}
540 630
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1);
541 631
     		}
542 632
     		if (! empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && ! empty($targetcompany->idprof2))
543 633
     		{
544 634
     			$tmp=$outputlangs->transcountrynoentities("ProfId2",$targetcompany->country_code);
545
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
635
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
636
+    			    $tmp=$reg[1];
637
+    			}
546 638
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2);
547 639
     		}
548 640
     		if (! empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && ! empty($targetcompany->idprof3))
549 641
     		{
550 642
     			$tmp=$outputlangs->transcountrynoentities("ProfId3",$targetcompany->country_code);
551
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
643
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
644
+    			    $tmp=$reg[1];
645
+    			}
552 646
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3);
553 647
     		}
554 648
     		if (! empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && ! empty($targetcompany->idprof4))
555 649
     		{
556 650
     			$tmp=$outputlangs->transcountrynoentities("ProfId4",$targetcompany->country_code);
557
-    			if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
651
+    			if (preg_match('/\((.+)\)/',$tmp,$reg)) {
652
+    			    $tmp=$reg[1];
653
+    			}
558 654
     			$stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4);
559 655
     		}
560 656
     		if (! empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && ! empty($targetcompany->idprof5))
561 657
     		{
562 658
     		    $tmp=$outputlangs->transcountrynoentities("ProfId5",$targetcompany->country_code);
563
-    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
659
+    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) {
660
+    		        $tmp=$reg[1];
661
+    		    }
564 662
     		    $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5);
565 663
     		}
566 664
     		if (! empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && ! empty($targetcompany->idprof6))
567 665
     		{
568 666
     		    $tmp=$outputlangs->transcountrynoentities("ProfId6",$targetcompany->country_code);
569
-    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) $tmp=$reg[1];
667
+    		    if (preg_match('/\((.+)\)/',$tmp,$reg)) {
668
+    		        $tmp=$reg[1];
669
+    		    }
570 670
     		    $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6);
571 671
     		}
572 672
 
@@ -602,9 +702,12 @@  discard block
 block discarded – undo
602 702
 	global $conf;
603 703
 
604 704
 	// Add a background image on document
605
-	if (! empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF))		// Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
705
+	if (! empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) {
706
+	    // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image
606 707
 	{
607
-		$pdf->SetAutoPageBreak(0,0);	// Disable auto pagebreak before adding image
708
+		$pdf->SetAutoPageBreak(0,0);
709
+	}
710
+	// Disable auto pagebreak before adding image
608 711
 		$pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_X:0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y)?$conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y:0), 0, $page_height);
609 712
 		$pdf->SetAutoPageBreak(1,0);	// Restore pagebreak
610 713
 	}
@@ -645,10 +748,15 @@  discard block
 block discarded – undo
645 748
 	global $langs, $mysoc, $user;
646 749
 
647 750
 	// Print Draft Watermark
648
-	if ($unit=='pt') $k=1;
649
-	elseif ($unit=='mm') $k=72/25.4;
650
-	elseif ($unit=='cm') $k=72/2.54;
651
-	elseif ($unit=='in') $k=72;
751
+	if ($unit=='pt') {
752
+	    $k=1;
753
+	} elseif ($unit=='mm') {
754
+	    $k=72/25.4;
755
+	} elseif ($unit=='cm') {
756
+	    $k=72/2.54;
757
+	} elseif ($unit=='in') {
758
+	    $k=72;
759
+	}
652 760
 
653 761
 	// Make substitution
654 762
 	$substitutionarray=pdf_getSubstitutionArray($outputlangs, null, null);
@@ -710,7 +818,9 @@  discard block
 block discarded – undo
710 818
 
711 819
 	// Use correct name of bank id according to country
712 820
 	$bickey="BICNumber";
713
-	if ($account->getCountryCode() == 'IN') $bickey="SWIFT";
821
+	if ($account->getCountryCode() == 'IN') {
822
+	    $bickey="SWIFT";
823
+	}
714 824
 
715 825
 	// Get format of bank account according to its country
716 826
 	$usedetailedbban=$account->useDetailedBBAN();
@@ -728,7 +838,8 @@  discard block
 block discarded – undo
728 838
 			$cury+=3;
729 839
 		}
730 840
 
731
-		if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN))    // Note that some countries still need bank number, BIC/IBAN not enougth for them
841
+		if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) {
842
+		    // Note that some countries still need bank number, BIC/IBAN not enougth for them
732 843
 		{
733 844
 		    // Note:
734 845
 		    // bank = code_banque (FR), sort code (GB, IR. Example: 12-34-56)
@@ -736,6 +847,7 @@  discard block
 block discarded – undo
736 847
 		    // number = account number
737 848
 		    // key = check control key used only when $usedetailedbban = 1
738 849
     		if (empty($onlynumber)) $pdf->line($curx+1, $cury+1, $curx+1, $cury+6);
850
+		}
739 851
 
740 852
 
741 853
 			foreach ($account->getFieldsToShow() as $val)
@@ -759,7 +871,7 @@  discard block
 block discarded – undo
759 871
 					// Key
760 872
 					$tmplength = 15;
761 873
 					$content = $account->cle_rib;
762
-				}elseif ($val == 'IBAN' || $val == 'BIC') {
874
+				} elseif ($val == 'IBAN' || $val == 'BIC') {
763 875
 					// Key
764 876
 					$tmplength = 0;
765 877
 					$content = '';
@@ -781,8 +893,7 @@  discard block
 block discarded – undo
781 893
     		$curx=$savcurx;
782 894
     		$cury+=8;
783 895
 		}
784
-	}
785
-	else
896
+	} else
786 897
 	{
787 898
 		$pdf->SetFont('','B',$default_font_size - $diffsizecontent);
788 899
 		$pdf->SetXY($curx, $cury);
@@ -794,7 +905,9 @@  discard block
 block discarded – undo
794 905
 		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': ' . $outputlangs->convToOutputCharset($account->number), 0, 'L', 0);
795 906
 		$cury+=3;
796 907
 
797
-		if ($diffsizecontent <= 2) $cury+=1;
908
+		if ($diffsizecontent <= 2) {
909
+		    $cury+=1;
910
+		}
798 911
 	}
799 912
 
800 913
 	$pdf->SetFont('','',$default_font_size - $diffsizecontent);
@@ -818,10 +931,10 @@  discard block
 block discarded – undo
818 931
 		$tmpy=$pdf->getStringHeight(100, $val);
819 932
 		$cury+=$tmpy;
820 933
 		$cur+=1;
934
+	} else if (! $usedetailedbban) {
935
+	    $cury+=1;
821 936
 	}
822 937
 
823
-	else if (! $usedetailedbban) $cury+=1;
824
-
825 938
 	// Use correct name of bank id according to country
826 939
 	$ibankey = FormBank::getIBANLabel($account);
827 940
 
@@ -835,7 +948,9 @@  discard block
 block discarded – undo
835 948
 		for ($i = 0; $i < $nbIbanDisplay_temp; $i++)
836 949
 		{
837 950
 			$ibanDisplay .= $ibanDisplay_temp[$i];
838
-			if($i%4 == 3 && $i > 0)	$ibanDisplay .= " ";
951
+			if($i%4 == 3 && $i > 0) {
952
+			    $ibanDisplay .= " ";
953
+			}
839 954
 		}
840 955
 
841 956
 		$pdf->SetFont('','B',$default_font_size - 3);
@@ -963,21 +1078,28 @@  discard block
 block discarded – undo
963 1078
 	if ($fromcompany->capital)
964 1079
 	{
965 1080
 		$tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string
966
-		if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
967
-		else $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",$tmpamounttoshow,$outputlangs);
1081
+		if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) {
1082
+		    $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency));
1083
+		} else {
1084
+		    $line3.=($line3?" - ":"").$outputlangs->transnoentities("CapitalOf",$tmpamounttoshow,$outputlangs);
1085
+		}
968 1086
 	}
969 1087
 	// Prof Id 1
970 1088
 	if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || ! $fromcompany->idprof2))
971 1089
 	{
972 1090
 		$field=$outputlangs->transcountrynoentities("ProfId1",$fromcompany->country_code);
973
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1091
+		if (preg_match('/\((.*)\)/i',$field,$reg)) {
1092
+		    $field=$reg[1];
1093
+		}
974 1094
 		$line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1);
975 1095
 	}
976 1096
 	// Prof Id 2
977 1097
 	if ($fromcompany->idprof2)
978 1098
 	{
979 1099
 		$field=$outputlangs->transcountrynoentities("ProfId2",$fromcompany->country_code);
980
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1100
+		if (preg_match('/\((.*)\)/i',$field,$reg)) {
1101
+		    $field=$reg[1];
1102
+		}
981 1103
 		$line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2);
982 1104
 	}
983 1105
 
@@ -986,28 +1108,36 @@  discard block
 block discarded – undo
986 1108
 	if ($fromcompany->idprof3)
987 1109
 	{
988 1110
 		$field=$outputlangs->transcountrynoentities("ProfId3",$fromcompany->country_code);
989
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1111
+		if (preg_match('/\((.*)\)/i',$field,$reg)) {
1112
+		    $field=$reg[1];
1113
+		}
990 1114
 		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3);
991 1115
 	}
992 1116
 	// Prof Id 4
993 1117
 	if ($fromcompany->idprof4)
994 1118
 	{
995 1119
 		$field=$outputlangs->transcountrynoentities("ProfId4",$fromcompany->country_code);
996
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1120
+		if (preg_match('/\((.*)\)/i',$field,$reg)) {
1121
+		    $field=$reg[1];
1122
+		}
997 1123
 		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4);
998 1124
 	}
999 1125
 	// Prof Id 5
1000 1126
 	if ($fromcompany->idprof5)
1001 1127
 	{
1002 1128
 		$field=$outputlangs->transcountrynoentities("ProfId5",$fromcompany->country_code);
1003
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1129
+		if (preg_match('/\((.*)\)/i',$field,$reg)) {
1130
+		    $field=$reg[1];
1131
+		}
1004 1132
 		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5);
1005 1133
 	}
1006 1134
 	// Prof Id 6
1007 1135
 	if ($fromcompany->idprof6)
1008 1136
 	{
1009 1137
 		$field=$outputlangs->transcountrynoentities("ProfId6",$fromcompany->country_code);
1010
-		if (preg_match('/\((.*)\)/i',$field,$reg)) $field=$reg[1];
1138
+		if (preg_match('/\((.*)\)/i',$field,$reg)) {
1139
+		    $field=$reg[1];
1140
+		}
1011 1141
 		$line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6);
1012 1142
 	}
1013 1143
 	// IntraCommunautary VAT
@@ -1021,18 +1151,20 @@  discard block
 block discarded – undo
1021 1151
 
1022 1152
 	// The start of the bottom of this page footer is positioned according to # of lines
1023 1153
 	$freetextheight=0;
1024
-	if ($line)	// Free text
1154
+	if ($line) {
1155
+	    // Free text
1025 1156
 	{
1026 1157
 		//$line="sample text<br>\nfd<strong>sf</strong>sdf<br>\nghfghg<br>";
1027 1158
 	    if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
1028 1159
 		{
1029
-			$width=20000; $align='L';	// By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
1160
+			$width=20000;
1161
+	}
1162
+	$align='L';	// By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text.
1030 1163
     		if (! empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) {
1031 1164
     			$width=200; $align='C';
1032 1165
     		}
1033 1166
 		    $freetextheight=$pdf->getStringHeight($width,$line);
1034
-		}
1035
-		else
1167
+		} else
1036 1168
 		{
1037 1169
             $freetextheight=pdfGetHeightForHtmlContent($pdf,dol_htmlentitiesbr($line, 1, 'UTF-8', 0));      // New method (works for HTML content)
1038 1170
             //print '<br>'.$freetextheight;exit;
@@ -1042,14 +1174,17 @@  discard block
 block discarded – undo
1042 1174
 	$marginwithfooter=$marge_basse + $freetextheight + (! empty($line1)?3:0) + (! empty($line2)?3:0) + (! empty($line3)?3:0) + (! empty($line4)?3:0);
1043 1175
 	$posy=$marginwithfooter+0;
1044 1176
 
1045
-	if ($line)	// Free text
1177
+	if ($line) {
1178
+	    // Free text
1046 1179
 	{
1047 1180
 		$pdf->SetXY($dims['lm'],-$posy);
1048
-		if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))   // by default
1181
+	}
1182
+		if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) {
1183
+		    // by default
1049 1184
 		{
1050 1185
             $pdf->MultiCell(0, 3, $line, 0, $align, 0);
1051 1186
 		}
1052
-		else
1187
+		} else
1053 1188
 		{
1054 1189
             $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk']-$marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0));
1055 1190
 		}
@@ -1162,15 +1297,21 @@  discard block
 block discarded – undo
1162 1297
 	$reshook=0;
1163 1298
 	$result='';
1164 1299
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1165
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1300
+	if (is_object($hookmanager)) {
1301
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1166 1302
 	{
1167 1303
 		$special_code = $object->lines[$i]->special_code;
1168
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1304
+	}
1305
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1306
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1307
+		}
1169 1308
 		$parameters = array('pdf'=>$pdf,'i'=>$i,'outputlangs'=>$outputlangs,'w'=>$w,'h'=>$h,'posx'=>$posx,'posy'=>$posy,'hideref'=>$hideref,'hidedesc'=>$hidedesc,'issupplierline'=>$issupplierline,'special_code'=>$special_code);
1170 1309
 		$action='';
1171 1310
 		$reshook=$hookmanager->executeHooks('pdf_writelinedesc',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1172 1311
 
1173
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1312
+		if (!empty($hookmanager->resPrint)) {
1313
+		    $result.=$hookmanager->resPrint;
1314
+		}
1174 1315
 	}
1175 1316
 	if (empty($reshook))
1176 1317
 	{
@@ -1208,8 +1349,7 @@  discard block
 block discarded – undo
1208 1349
 	{
1209 1350
 		include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1210 1351
 		$prodser = new ProductFournisseur($db);
1211
-	}
1212
-	else
1352
+	} else
1213 1353
 	{
1214 1354
 		include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1215 1355
 		$prodser = new Product($db);
@@ -1230,7 +1370,9 @@  discard block
 block discarded – undo
1230 1370
 			// If we want another language, and if label is same than default language (we did force it to a specific value), we can use translation.
1231 1371
 			//var_dump($outputlangs->defaultlang.' - '.$langs->defaultlang.' - '.$label.' - '.$prodser->label);exit;
1232 1372
 			$textwasmodified=($label == $prodser->label);
1233
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified))     $label=$prodser->multilangs[$outputlangs->defaultlang]["label"];
1373
+			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified)) {
1374
+			    $label=$prodser->multilangs[$outputlangs->defaultlang]["label"];
1375
+			}
1234 1376
 
1235 1377
 			// Set desc
1236 1378
 			// Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no
@@ -1240,11 +1382,15 @@  discard block
 block discarded – undo
1240 1382
 			} else {
1241 1383
 				$textwasmodified=($desc == $prodser->description);
1242 1384
 			}
1243
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified))  $desc=$prodser->multilangs[$outputlangs->defaultlang]["description"];
1385
+			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) {
1386
+			    $desc=$prodser->multilangs[$outputlangs->defaultlang]["description"];
1387
+			}
1244 1388
 
1245 1389
 			// Set note
1246 1390
 			$textwasmodified=($note == $prodser->note);
1247
-			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified))  $note=$prodser->multilangs[$outputlangs->defaultlang]["note"];
1391
+			if (! empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) {
1392
+			    $note=$prodser->multilangs[$outputlangs->defaultlang]["note"];
1393
+			}
1248 1394
 		}
1249 1395
 	}
1250 1396
 
@@ -1265,29 +1411,28 @@  discard block
 block discarded – undo
1265 1411
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1266 1412
 			$sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1267 1413
 			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref);
1268
-		}
1269
-		elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except)
1414
+		} elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except)
1270 1415
 		{
1271 1416
 			$discount=new DiscountAbsolute($db);
1272 1417
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1273 1418
 			$sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source;
1274 1419
 			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref);
1275 1420
 			// Add date of deposit
1276
-			if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')';
1421
+			if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) {
1422
+			    echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')';
1423
+			}
1277 1424
 		}
1278 1425
 		if ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except)
1279 1426
 		{
1280 1427
 			$discount=new DiscountAbsolute($db);
1281 1428
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1282 1429
 			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source);
1283
-		}
1284
-		elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except)
1430
+		} elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except)
1285 1431
 		{
1286 1432
 			$discount=new DiscountAbsolute($db);
1287 1433
 			$discount->fetch($object->lines[$i]->fk_remise_except);
1288 1434
 			$libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source);
1289
-		}
1290
-		else
1435
+		} else
1291 1436
 		{
1292 1437
 			if ($idprod)
1293 1438
 			{
@@ -1296,14 +1441,12 @@  discard block
 block discarded – undo
1296 1441
 					if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST))
1297 1442
 					{
1298 1443
 						$libelleproduitservice=$desc."\n".$libelleproduitservice;
1299
-					}
1300
-					else
1444
+					} else
1301 1445
 					{
1302 1446
 						$libelleproduitservice.=$desc;
1303 1447
 					}
1304 1448
 				}
1305
-			}
1306
-			else
1449
+			} else
1307 1450
 			{
1308 1451
 				$libelleproduitservice.=$desc;
1309 1452
 			}
@@ -1313,13 +1456,14 @@  discard block
 block discarded – undo
1313 1456
 	// We add ref of product (and supplier ref if defined)
1314 1457
 	$prefix_prodserv = "";
1315 1458
 	$ref_prodserv = "";
1316
-	if (! empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS))   // In standard mode, we do not show this
1459
+	if (! empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS)) {
1460
+	    // In standard mode, we do not show this
1317 1461
 	{
1318 1462
 		if ($prodser->isService())
1319 1463
 		{
1320 1464
 			$prefix_prodserv = $outputlangs->transnoentitiesnoconv("Service")." ";
1321
-		}
1322
-		else
1465
+	}
1466
+		} else
1323 1467
 		{
1324 1468
 			$prefix_prodserv = $outputlangs->transnoentitiesnoconv("Product")." ";
1325 1469
 		}
@@ -1329,22 +1473,25 @@  discard block
 block discarded – undo
1329 1473
 	{
1330 1474
 		if ($issupplierline)
1331 1475
 		{
1332
-			if ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1)
1333
-				$ref_prodserv = $ref_supplier;
1334
-			elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2)
1335
-				$ref_prodserv = $ref_supplier. ' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')';
1336
-			else	// Common case
1476
+			if ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1) {
1477
+							$ref_prodserv = $ref_supplier;
1478
+			} elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2) {
1479
+							$ref_prodserv = $ref_supplier. ' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')';
1480
+			} else	// Common case
1337 1481
 			{
1338 1482
 				$ref_prodserv = $prodser->ref; // Show local ref
1339
-				if ($ref_supplier) $ref_prodserv.= ($prodser->ref?' (':'').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref?')':'');
1483
+				if ($ref_supplier) {
1484
+				    $ref_prodserv.= ($prodser->ref?' (':'').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref?')':'');
1485
+				}
1340 1486
 			}
1341
-		}
1342
-		else
1487
+		} else
1343 1488
 		{
1344 1489
 			$ref_prodserv = $prodser->ref; // Show local ref only
1345 1490
 		}
1346 1491
 
1347
-		if (! empty($libelleproduitservice) && ! empty($ref_prodserv)) $ref_prodserv .= " - ";
1492
+		if (! empty($libelleproduitservice) && ! empty($ref_prodserv)) {
1493
+		    $ref_prodserv .= " - ";
1494
+		}
1348 1495
 	}
1349 1496
 
1350 1497
 	if(!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){ $ref_prodserv = '<b>'.$ref_prodserv.'</b>'; }
@@ -1361,8 +1508,9 @@  discard block
 block discarded – undo
1361 1508
 		{
1362 1509
 			// Adding the descriptions if they are filled
1363 1510
 			$desccateg=$cate->add_description;
1364
-			if ($desccateg)
1365
-				$libelleproduitservice.='__N__'.$desccateg;
1511
+			if ($desccateg) {
1512
+							$libelleproduitservice.='__N__'.$desccateg;
1513
+			}
1366 1514
 		}
1367 1515
 	}
1368 1516
 
@@ -1385,7 +1533,7 @@  discard block
 block discarded – undo
1385 1533
 		//print '>'.$outputlangs->charset_output.','.$period;
1386 1534
 		if(!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){
1387 1535
 		    $libelleproduitservice.= '<b style="color:#333666;" ><em>'."__N__</b> ".$period.'</em>';
1388
-		}else{
1536
+		} else{
1389 1537
 		$libelleproduitservice.="__N__".$period;
1390 1538
 		}
1391 1539
 		//print $libelleproduitservice;
@@ -1397,17 +1545,26 @@  discard block
 block discarded – undo
1397 1545
 		foreach ($dbatch as $detail)
1398 1546
 		{
1399 1547
 			$dte=array();
1400
-			if ($detail->eatby) $dte[]=$outputlangs->transnoentitiesnoconv('printEatby',dol_print_date($detail->eatby, $format, false, $outputlangs));
1401
-			if ($detail->sellby) $dte[]=$outputlangs->transnoentitiesnoconv('printSellby',dol_print_date($detail->sellby, $format, false, $outputlangs));
1402
-			if ($detail->batch) $dte[]=$outputlangs->transnoentitiesnoconv('printBatch',$detail->batch);
1548
+			if ($detail->eatby) {
1549
+			    $dte[]=$outputlangs->transnoentitiesnoconv('printEatby',dol_print_date($detail->eatby, $format, false, $outputlangs));
1550
+			}
1551
+			if ($detail->sellby) {
1552
+			    $dte[]=$outputlangs->transnoentitiesnoconv('printSellby',dol_print_date($detail->sellby, $format, false, $outputlangs));
1553
+			}
1554
+			if ($detail->batch) {
1555
+			    $dte[]=$outputlangs->transnoentitiesnoconv('printBatch',$detail->batch);
1556
+			}
1403 1557
 			$dte[]=$outputlangs->transnoentitiesnoconv('printQty',$detail->qty);
1404 1558
 			$libelleproduitservice.= "__N__  ".implode(" - ", $dte);
1405 1559
 		}
1406 1560
 	}
1407 1561
 
1408 1562
 	// Now we convert \n into br
1409
-	if (dol_textishtml($libelleproduitservice)) $libelleproduitservice=preg_replace('/__N__/','<br>',$libelleproduitservice);
1410
-	else $libelleproduitservice=preg_replace('/__N__/',"\n",$libelleproduitservice);
1563
+	if (dol_textishtml($libelleproduitservice)) {
1564
+	    $libelleproduitservice=preg_replace('/__N__/','<br>',$libelleproduitservice);
1565
+	} else {
1566
+	    $libelleproduitservice=preg_replace('/__N__/',"\n",$libelleproduitservice);
1567
+	}
1411 1568
 	$libelleproduitservice=dol_htmlentitiesbr($libelleproduitservice,1);
1412 1569
 
1413 1570
 	return $libelleproduitservice;
@@ -1429,10 +1586,14 @@  discard block
 block discarded – undo
1429 1586
 	$reshook=0;
1430 1587
 	$result='';
1431 1588
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1432
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1589
+	if (is_object($hookmanager)) {
1590
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1433 1591
 	{
1434 1592
 		$special_code = $object->lines[$i]->special_code;
1435
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1593
+	}
1594
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1595
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1596
+		}
1436 1597
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1437 1598
 		$action='';
1438 1599
 		$reshook = $hookmanager->executeHooks('pdf_getlinenum',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
@@ -1462,10 +1623,14 @@  discard block
 block discarded – undo
1462 1623
 	$reshook=0;
1463 1624
 	$result='';
1464 1625
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1465
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1626
+	if (is_object($hookmanager)) {
1627
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1466 1628
 	{
1467 1629
 		$special_code = $object->lines[$i]->special_code;
1468
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1630
+	}
1631
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1632
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1633
+		}
1469 1634
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1470 1635
 		$action='';
1471 1636
 		$reshook = $hookmanager->executeHooks('pdf_getlineref',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
@@ -1494,10 +1659,14 @@  discard block
 block discarded – undo
1494 1659
 	$reshook=0;
1495 1660
 	$result='';
1496 1661
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1497
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1662
+	if (is_object($hookmanager)) {
1663
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1498 1664
 	{
1499 1665
 		$special_code = $object->lines[$i]->special_code;
1500
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1666
+	}
1667
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1668
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1669
+		}
1501 1670
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1502 1671
 		$action='';
1503 1672
 		$reshook = $hookmanager->executeHooks('pdf_getlineref_supplier',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
@@ -1526,15 +1695,21 @@  discard block
 block discarded – undo
1526 1695
 	$result='';
1527 1696
 	$reshook=0;
1528 1697
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1529
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
1698
+	if (is_object($hookmanager)) {
1699
+	    // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run
1530 1700
 	{
1531 1701
 		$special_code = $object->lines[$i]->special_code;
1532
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1702
+	}
1703
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1704
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1705
+		}
1533 1706
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1534 1707
 		$action='';
1535 1708
 		$reshook = $hookmanager->executeHooks('pdf_getlinevatrate',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1536 1709
 
1537
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1710
+		if (!empty($hookmanager->resPrint)) {
1711
+		    $result.=$hookmanager->resPrint;
1712
+		}
1538 1713
 	}
1539 1714
 	if (empty($reshook))
1540 1715
 	{
@@ -1547,8 +1722,11 @@  discard block
 block discarded – undo
1547 1722
 			{
1548 1723
 				if ($object->lines[$i]->total_localtax1 != 0)
1549 1724
 				{
1550
-					if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1551
-					else $tmpresult='';
1725
+					if (preg_replace('/[\s0%]/','',$tmpresult)) {
1726
+					    $tmpresult.='/';
1727
+					} else {
1728
+					    $tmpresult='';
1729
+					}
1552 1730
 					$tmpresult.=vatrate(abs($object->lines[$i]->localtax1_tx), 0);
1553 1731
 				}
1554 1732
 			}
@@ -1556,8 +1734,11 @@  discard block
 block discarded – undo
1556 1734
 			{
1557 1735
 				if ($object->lines[$i]->total_localtax2 != 0)
1558 1736
 				{
1559
-					if (preg_replace('/[\s0%]/','',$tmpresult)) $tmpresult.='/';
1560
-					else $tmpresult='';
1737
+					if (preg_replace('/[\s0%]/','',$tmpresult)) {
1738
+					    $tmpresult.='/';
1739
+					} else {
1740
+					    $tmpresult='';
1741
+					}
1561 1742
 					$tmpresult.=vatrate(abs($object->lines[$i]->localtax2_tx), 0);
1562 1743
 				}
1563 1744
 			}
@@ -1583,20 +1764,28 @@  discard block
 block discarded – undo
1583 1764
 	global $conf, $hookmanager;
1584 1765
 
1585 1766
 	$sign=1;
1586
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1767
+	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
1768
+	    $sign=-1;
1769
+	}
1587 1770
 
1588 1771
 	$result='';
1589 1772
 	$reshook=0;
1590 1773
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1591
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1774
+	if (is_object($hookmanager)) {
1775
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1592 1776
 	{
1593 1777
 		$special_code = $object->lines[$i]->special_code;
1594
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1778
+	}
1779
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1780
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1781
+		}
1595 1782
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1596 1783
 		$action='';
1597 1784
 		$reshook = $hookmanager->executeHooks('pdf_getlineupexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1598 1785
 
1599
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1786
+		if (!empty($hookmanager->resPrint)) {
1787
+		    $result.=$hookmanager->resPrint;
1788
+		}
1600 1789
 	}
1601 1790
 	if (empty($reshook))
1602 1791
 	{
@@ -1623,24 +1812,34 @@  discard block
 block discarded – undo
1623 1812
 	global $hookmanager,$conf;
1624 1813
 
1625 1814
 	$sign=1;
1626
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
1815
+	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
1816
+	    $sign=-1;
1817
+	}
1627 1818
 
1628 1819
 	$result='';
1629 1820
 	$reshook=0;
1630 1821
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1631
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1822
+	if (is_object($hookmanager)) {
1823
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1632 1824
 	{
1633 1825
 		$special_code = $object->lines[$i]->special_code;
1634
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1826
+	}
1827
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1828
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1829
+		}
1635 1830
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1636 1831
 		$action='';
1637 1832
 		$reshook = $hookmanager->executeHooks('pdf_getlineupwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1638 1833
 
1639
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1834
+		if (!empty($hookmanager->resPrint)) {
1835
+		    $result.=$hookmanager->resPrint;
1836
+		}
1640 1837
 	}
1641 1838
 	if (empty($reshook))
1642 1839
 	{
1643
-		if (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice)*($object->lines[$i]->tva_tx)/100), 0, $outputlangs);
1840
+		if (empty($hidedetails) || $hidedetails > 1) {
1841
+		    $result.=price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice)*($object->lines[$i]->tva_tx)/100), 0, $outputlangs);
1842
+		}
1644 1843
 	}
1645 1844
 	return $result;
1646 1845
 }
@@ -1661,20 +1860,30 @@  discard block
 block discarded – undo
1661 1860
 	$result='';
1662 1861
 	$reshook=0;
1663 1862
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1664
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1863
+	if (is_object($hookmanager)) {
1864
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1665 1865
 	{
1666 1866
 		$special_code = $object->lines[$i]->special_code;
1667
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1867
+	}
1868
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1869
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1870
+		}
1668 1871
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1669 1872
 		$action='';
1670 1873
 		$reshook = $hookmanager->executeHooks('pdf_getlineqty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1671 1874
 
1672
-		if(!empty($hookmanager->resPrint)) $result=$hookmanager->resPrint;
1875
+		if(!empty($hookmanager->resPrint)) {
1876
+		    $result=$hookmanager->resPrint;
1877
+		}
1673 1878
 	}
1674 1879
     if (empty($reshook))
1675 1880
 	{
1676
-	   if ($object->lines[$i]->special_code == 3) return '';
1677
-	   if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty;
1881
+	   if ($object->lines[$i]->special_code == 3) {
1882
+	       return '';
1883
+	   }
1884
+	   if (empty($hidedetails) || $hidedetails > 1) {
1885
+	       $result.=$object->lines[$i]->qty;
1886
+	   }
1678 1887
 	}
1679 1888
 	return $result;
1680 1889
 }
@@ -1695,20 +1904,30 @@  discard block
 block discarded – undo
1695 1904
 	$reshook=0;
1696 1905
 	$result='';
1697 1906
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1698
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1907
+	if (is_object($hookmanager)) {
1908
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1699 1909
 	{
1700 1910
 		$special_code = $object->lines[$i]->special_code;
1701
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1911
+	}
1912
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1913
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1914
+		}
1702 1915
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1703 1916
 		$action='';
1704 1917
 		$reshook = $hookmanager->executeHooks('pdf_getlineqty_asked',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1705 1918
 
1706
-		if (!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1919
+		if (!empty($hookmanager->resPrint)) {
1920
+		    $result.=$hookmanager->resPrint;
1921
+		}
1707 1922
 	}
1708 1923
 	if (empty($reshook))
1709 1924
 	{
1710
-        if ($object->lines[$i]->special_code == 3) return '';
1711
-        if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_asked;
1925
+        if ($object->lines[$i]->special_code == 3) {
1926
+            return '';
1927
+        }
1928
+        if (empty($hidedetails) || $hidedetails > 1) {
1929
+            $result.=$object->lines[$i]->qty_asked;
1930
+        }
1712 1931
 	}
1713 1932
 	return $result;
1714 1933
 }
@@ -1729,20 +1948,30 @@  discard block
 block discarded – undo
1729 1948
 	$reshook=0;
1730 1949
 	$result='';
1731 1950
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1732
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1951
+	if (is_object($hookmanager)) {
1952
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1733 1953
 	{
1734 1954
 		$special_code = $object->lines[$i]->special_code;
1735
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1955
+	}
1956
+		if (! empty($object->lines[$i]->fk_parent_line)) {
1957
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1958
+		}
1736 1959
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1737 1960
 		$action='';
1738 1961
 		$reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1739 1962
 
1740
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
1963
+		if(!empty($hookmanager->resPrint)) {
1964
+		    $result.=$hookmanager->resPrint;
1965
+		}
1741 1966
 	}
1742 1967
 	if (empty($reshook))
1743 1968
 	{
1744
-        if ($object->lines[$i]->special_code == 3) return '';
1745
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$object->lines[$i]->qty_shipped;
1969
+        if ($object->lines[$i]->special_code == 3) {
1970
+            return '';
1971
+        }
1972
+	    if (empty($hidedetails) || $hidedetails > 1) {
1973
+	        $result.=$object->lines[$i]->qty_shipped;
1974
+	    }
1746 1975
 	}
1747 1976
 	return $result;
1748 1977
 }
@@ -1763,20 +1992,30 @@  discard block
 block discarded – undo
1763 1992
 	$reshook=0;
1764 1993
     $result='';
1765 1994
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1766
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1995
+	if (is_object($hookmanager)) {
1996
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1767 1997
 	{
1768 1998
 		$special_code = $object->lines[$i]->special_code;
1769
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1999
+	}
2000
+		if (! empty($object->lines[$i]->fk_parent_line)) {
2001
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2002
+		}
1770 2003
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1771 2004
 		$action='';
1772 2005
 		$reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1773 2006
 
1774
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
2007
+		if(!empty($hookmanager->resPrint)) {
2008
+		    $result.=$hookmanager->resPrint;
2009
+		}
1775 2010
 	}
1776 2011
 	if (empty($reshook))
1777 2012
 	{
1778
-        if ($object->lines[$i]->special_code == 3) return '';
1779
-		if (empty($hidedetails) || $hidedetails > 1) $result.=($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
2013
+        if ($object->lines[$i]->special_code == 3) {
2014
+            return '';
2015
+        }
2016
+		if (empty($hidedetails) || $hidedetails > 1) {
2017
+		    $result.=($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped);
2018
+		}
1780 2019
 	}
1781 2020
 	return $result;
1782 2021
 }
@@ -1798,9 +2037,11 @@  discard block
 block discarded – undo
1798 2037
 	$reshook=0;
1799 2038
     $result='';
1800 2039
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1801
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
2040
+	if (is_object($hookmanager)) {
2041
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1802 2042
 	{
1803 2043
 		$special_code = $object->lines[$i]->special_code;
2044
+	}
1804 2045
 		if (!empty($object->lines[$i]->fk_parent_line)) {
1805 2046
 			$special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
1806 2047
 		}
@@ -1813,12 +2054,18 @@  discard block
 block discarded – undo
1813 2054
 		$action = '';
1814 2055
 		$reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1815 2056
 
1816
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
2057
+		if(!empty($hookmanager->resPrint)) {
2058
+		    $result.=$hookmanager->resPrint;
2059
+		}
1817 2060
 	}
1818 2061
 	if (empty($reshook))
1819 2062
 	{
1820
-        if ($object->lines[$i]->special_code == 3) return '';
1821
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=$langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
2063
+        if ($object->lines[$i]->special_code == 3) {
2064
+            return '';
2065
+        }
2066
+	    if (empty($hidedetails) || $hidedetails > 1) {
2067
+	        $result.=$langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short'));
2068
+	    }
1822 2069
 	}
1823 2070
 	return $result;
1824 2071
 }
@@ -1842,20 +2089,30 @@  discard block
 block discarded – undo
1842 2089
 	$reshook=0;
1843 2090
 	$result='';
1844 2091
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1845
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
2092
+	if (is_object($hookmanager)) {
2093
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1846 2094
 	{
1847 2095
 		$special_code = $object->lines[$i]->special_code;
1848
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2096
+	}
2097
+		if (! empty($object->lines[$i]->fk_parent_line)) {
2098
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2099
+		}
1849 2100
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1850 2101
 		$action='';
1851 2102
 		$reshook = $hookmanager->executeHooks('pdf_getlineremisepercent',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1852 2103
 
1853
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
2104
+		if(!empty($hookmanager->resPrint)) {
2105
+		    $result.=$hookmanager->resPrint;
2106
+		}
1854 2107
 	}
1855 2108
 	if (empty($reshook))
1856 2109
 	{
1857
-        if ($object->lines[$i]->special_code == 3) return '';
1858
-	    if (empty($hidedetails) || $hidedetails > 1) $result.=dol_print_reduction($object->lines[$i]->remise_percent,$outputlangs);
2110
+        if ($object->lines[$i]->special_code == 3) {
2111
+            return '';
2112
+        }
2113
+	    if (empty($hidedetails) || $hidedetails > 1) {
2114
+	        $result.=dol_print_reduction($object->lines[$i]->remise_percent,$outputlangs);
2115
+	    }
1859 2116
 	}
1860 2117
 	return $result;
1861 2118
 }
@@ -1872,25 +2129,35 @@  discard block
 block discarded – undo
1872 2129
  */
1873 2130
 function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = null)
1874 2131
 {
1875
-	if (empty($hookmanager)) global $hookmanager;
2132
+	if (empty($hookmanager)) {
2133
+	    global $hookmanager;
2134
+	}
1876 2135
 	global $conf;
1877 2136
 
1878 2137
 	$reshook=0;
1879 2138
     $result='';
1880 2139
     //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1881
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
2140
+	if (is_object($hookmanager)) {
2141
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1882 2142
 	{
1883 2143
 		$special_code = $object->lines[$i]->special_code;
1884
-		if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2144
+	}
2145
+		if (!empty($object->lines[$i]->fk_parent_line)) {
2146
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2147
+		}
1885 2148
 		$parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code);
1886 2149
 		$action = '';
1887 2150
 		$reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1888 2151
 
1889
-		if(!empty($hookmanager->resPrint)) return $hookmanager->resPrint;
2152
+		if(!empty($hookmanager->resPrint)) {
2153
+		    return $hookmanager->resPrint;
2154
+		}
1890 2155
 	}
1891 2156
 	if (empty($reshook))
1892 2157
 	{
1893
-        	if ($object->lines[$i]->special_code == 3) return '';
2158
+        	if ($object->lines[$i]->special_code == 3) {
2159
+        	    return '';
2160
+        	}
1894 2161
 		if (empty($hidedetails) || $hidedetails > 1)
1895 2162
 		{
1896 2163
 			if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF)
@@ -1901,9 +2168,9 @@  discard block
 block discarded – undo
1901 2168
 			 		$prev_progress = $object->lines[$i]->get_prev_progress($object->id);
1902 2169
 				}
1903 2170
 			 	$result = ($object->lines[$i]->situation_percent - $prev_progress) . '%';
2171
+			} else {
2172
+							$result = $object->lines[$i]->situation_percent . '%';
1904 2173
 			}
1905
-			else
1906
-				$result = $object->lines[$i]->situation_percent . '%';
1907 2174
 	  	}
1908 2175
 	}
1909 2176
 	return $result;
@@ -1923,20 +2190,28 @@  discard block
 block discarded – undo
1923 2190
 	global $conf, $hookmanager;
1924 2191
 
1925 2192
 	$sign=1;
1926
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
2193
+	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
2194
+	    $sign=-1;
2195
+	}
1927 2196
 
1928 2197
 	$reshook=0;
1929 2198
 	$result='';
1930 2199
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1931
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
2200
+	if (is_object($hookmanager)) {
2201
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1932 2202
 	{
1933 2203
 		$special_code = $object->lines[$i]->special_code;
1934
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2204
+	}
2205
+		if (! empty($object->lines[$i]->fk_parent_line)) {
2206
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2207
+		}
1935 2208
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code, 'sign'=>$sign);
1936 2209
 		$action='';
1937 2210
 		$reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1938 2211
 
1939
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
2212
+		if(!empty($hookmanager->resPrint)) {
2213
+		    $result.=$hookmanager->resPrint;
2214
+		}
1940 2215
 	}
1941 2216
     if (empty($reshook))
1942 2217
     {
@@ -1957,9 +2232,9 @@  discard block
 block discarded – undo
1957 2232
 					$progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100;
1958 2233
         		}
1959 2234
 				$result.=price($sign * ($total_ht/($object->lines[$i]->situation_percent/100)) * $progress, 0, $outputlangs);
2235
+        	} else {
2236
+        				$result.=price($sign * $total_ht, 0, $outputlangs);
1960 2237
         	}
1961
-        	else
1962
-			$result.=price($sign * $total_ht, 0, $outputlangs);
1963 2238
 	}
1964 2239
     }
1965 2240
 	return $result;
@@ -1979,28 +2254,37 @@  discard block
 block discarded – undo
1979 2254
 	global $hookmanager,$conf;
1980 2255
 
1981 2256
 	$sign=1;
1982
-	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1;
2257
+	if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) {
2258
+	    $sign=-1;
2259
+	}
1983 2260
 
1984 2261
 	$reshook=0;
1985 2262
 	$result='';
1986 2263
 	//if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) )
1987
-	if (is_object($hookmanager))   // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
2264
+	if (is_object($hookmanager)) {
2265
+	    // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run
1988 2266
 	{
1989 2267
 		$special_code = $object->lines[$i]->special_code;
1990
-		if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2268
+	}
2269
+		if (! empty($object->lines[$i]->fk_parent_line)) {
2270
+		    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2271
+		}
1991 2272
 		$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
1992 2273
 		$action='';
1993 2274
 		$reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
1994 2275
 
1995
-		if(!empty($hookmanager->resPrint)) $result.=$hookmanager->resPrint;
2276
+		if(!empty($hookmanager->resPrint)) {
2277
+		    $result.=$hookmanager->resPrint;
2278
+		}
1996 2279
 	}
1997 2280
 	if (empty($reshook))
1998 2281
 	{
1999 2282
 		if ($object->lines[$i]->special_code == 3)
2000 2283
     	{
2001 2284
     		$result.=$outputlangs->transnoentities("Option");
2002
-    	}
2003
-		elseif (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht)*($object->lines[$i]->tva_tx)/100, 0, $outputlangs);
2285
+    	} elseif (empty($hidedetails) || $hidedetails > 1) {
2286
+		    $result.=price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht)*($object->lines[$i]->tva_tx)/100, 0, $outputlangs);
2287
+		}
2004 2288
 	}
2005 2289
 	return $result;
2006 2290
 }
@@ -2029,21 +2313,20 @@  discard block
 block discarded – undo
2029 2313
 			if ($type=='all')
2030 2314
 			{
2031 2315
 				$total += $object->lines[$i]->qty;
2032
-			}
2033
-			else if ($type==9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line)))
2316
+			} else if ($type==9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line)))
2034 2317
 			{
2035 2318
 				$special_code = $object->lines[$i]->special_code;
2036
-				if (! empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2319
+				if (! empty($object->lines[$i]->fk_parent_line)) {
2320
+				    $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line);
2321
+				}
2037 2322
 				$parameters = array('i'=>$i,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'special_code'=>$special_code);
2038 2323
 				$action='';
2039 2324
 				$reshook = $hookmanager->executeHooks('pdf_getTotalQty',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2040 2325
 				return $hookmanager->resPrint;
2041
-			}
2042
-			else if ($type==0 && $object->lines[$i]->product_type == 0)
2326
+			} else if ($type==0 && $object->lines[$i]->product_type == 0)
2043 2327
 			{
2044 2328
 				$total += $object->lines[$i]->qty;
2045
-			}
2046
-			else if ($type==1 && $object->lines[$i]->product_type == 1)
2329
+			} else if ($type==1 && $object->lines[$i]->product_type == 1)
2047 2330
 			{
2048 2331
 				$total += $object->lines[$i]->qty;
2049 2332
 			}
@@ -2074,8 +2357,7 @@  discard block
 block discarded – undo
2074 2357
 	    if ($objecttype == 'facture')
2075 2358
 	    {
2076 2359
 	       // For invoice, we don't want to have a reference line on document. Image we are using recuring invoice, we will have a line longer than document width.
2077
-	    }
2078
-	    elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal')
2360
+	    } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal')
2079 2361
 		{
2080 2362
 			$outputlangs->load('propal');
2081 2363
 
@@ -2086,8 +2368,7 @@  discard block
 block discarded – undo
2086 2368
 				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal");
2087 2369
 				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2088 2370
 			}
2089
-		}
2090
-		else if ($objecttype == 'commande' || $objecttype == 'supplier_order')
2371
+		} else if ($objecttype == 'commande' || $objecttype == 'supplier_order')
2091 2372
 		{
2092 2373
 			$outputlangs->load('orders');
2093 2374
 			foreach($objects as $elementobject)
@@ -2097,8 +2378,7 @@  discard block
 block discarded – undo
2097 2378
 				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate");
2098 2379
 				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date,'day','',$outputlangs);
2099 2380
 			}
2100
-		}
2101
-		else if ($objecttype == 'contrat')
2381
+		} else if ($objecttype == 'contrat')
2102 2382
 		{
2103 2383
 			$outputlangs->load('contracts');
2104 2384
 			foreach($objects as $elementobject)
@@ -2108,8 +2388,7 @@  discard block
 block discarded – undo
2108 2388
 				$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract");
2109 2389
 				$linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat,'day','',$outputlangs);
2110 2390
 			}
2111
-		}
2112
-		else if ($objecttype == 'shipping')
2391
+		} else if ($objecttype == 'shipping')
2113 2392
 		{
2114 2393
 			$outputlangs->loadLangs(array("orders", "sendings"));
2115 2394
 
@@ -2117,24 +2396,31 @@  discard block
 block discarded – undo
2117 2396
 			{
2118 2397
 			    $order=null;
2119 2398
 			    // We concat this record info into fields xxx_value. title is overwrote.
2120
-			    if (empty($object->linkedObjects['commande']) && $object->element != 'commande')	// There is not already a link to order and object is not the order, so we show also info with order
2399
+			    if (empty($object->linkedObjects['commande']) && $object->element != 'commande') {
2400
+			        // There is not already a link to order and object is not the order, so we show also info with order
2121 2401
 			    {
2122 2402
 			        $elementobject->fetchObjectLinked();
2123
-			        if (! empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']);
2403
+			    }
2404
+			        if (! empty($elementobject->linkedObjects['commande'])) {
2405
+			            $order = reset($elementobject->linkedObjects['commande']);
2406
+			        }
2124 2407
 			    }
2125 2408
 			    if (! is_object($order))
2126 2409
 			    {
2127 2410
 			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending");
2128
-			        if (! empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'].=' / ';
2411
+			        if (! empty($linkedobjects[$objecttype]['ref_value'])) {
2412
+			            $linkedobjects[$objecttype]['ref_value'].=' / ';
2413
+			        }
2129 2414
 			        $linkedobjects[$objecttype]['ref_value'].= $outputlangs->transnoentities($elementobject->ref);
2130 2415
 			        //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment");
2131 2416
 			        //if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / ';
2132 2417
 			        //$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs);
2133
-			    }
2134
-			    else
2418
+			    } else
2135 2419
 			    {
2136 2420
 			        $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder") . ' / ' . $outputlangs->transnoentities("RefSending");
2137
-			        if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref) . ($order->ref_client ? ' ('.$order->ref_client.')' : '');
2421
+			        if (empty($linkedobjects[$objecttype]['ref_value'])) {
2422
+			            $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref) . ($order->ref_client ? ' ('.$order->ref_client.')' : '');
2423
+			        }
2138 2424
 			        $linkedobjects[$objecttype]['ref_value'].= ' / ' . $outputlangs->transnoentities($elementobject->ref);
2139 2425
 			        //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : '');
2140 2426
 			        //if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs);
@@ -2150,7 +2436,9 @@  discard block
 block discarded – undo
2150 2436
 		$parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs);
2151 2437
 		$action='';
2152 2438
 		$hookmanager->executeHooks('pdf_getLinkedObjects',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
2153
-		if (! empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray;
2439
+		if (! empty($hookmanager->resArray)) {
2440
+		    $linkedobjects = $hookmanager->resArray;
2441
+		}
2154 2442
 	}
2155 2443
 
2156 2444
 	return $linkedobjects;
@@ -2174,12 +2462,13 @@  discard block
 block discarded – undo
2174 2462
 	if ($tmp['height'])
2175 2463
 	{
2176 2464
 		$width=(int) round($maxheight*$tmp['width']/$tmp['height']);	// I try to use maxheight
2177
-		if ($width > $maxwidth)	// Pb with maxheight, so i use maxwidth
2465
+		if ($width > $maxwidth) {
2466
+		    // Pb with maxheight, so i use maxwidth
2178 2467
 		{
2179 2468
 			$width=$maxwidth;
2180
-			$height=(int) round($maxwidth*$tmp['height']/$tmp['width']);
2181 2469
 		}
2182
-		else	// No pb with maxheight
2470
+			$height=(int) round($maxwidth*$tmp['height']/$tmp['width']);
2471
+		} else	// No pb with maxheight
2183 2472
 		{
2184 2473
 			$height=$maxheight;
2185 2474
 		}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/price.lib.php 3 patches
Indentation   +248 added lines, -248 removed lines patch added patch discarded remove patch
@@ -84,330 +84,330 @@
 block discarded – undo
84 84
  */
85 85
 function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller = '', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0)
86 86
 {
87
-	global $conf,$mysoc,$db;
88
-
89
-	$result=array();
90
-
91
-	// Clean parameters
92
-	if (empty($info_bits)) $info_bits=0;
93
-	if (empty($txtva)) $txtva=0;
94
-	if (empty($seller) || ! is_object($seller))
95
-	{
96
-		dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING);
97
-		if (! is_object($mysoc))	// mysoc may be not defined (during migration process)
98
-		{
99
-			$mysoc=new Societe($db);
100
-			$mysoc->setMysoc($conf);
101
-		}
102
-		$seller=$mysoc;	// If sell is done to a customer, $seller is not provided, we use $mysoc
103
-		//var_dump($seller->country_id);exit;
104
-	}
105
-	if (empty($localtaxes_array) || ! is_array($localtaxes_array))
106
-	{
107
-		dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing", LOG_WARNING);
108
-	}
109
-	// Too verbose. Enable for debug only
110
-	//dol_syslog("Price.lib::calcul_price_total qty=".$qty." pu=".$pu." remiserpercent_ligne=".$remise_percent_ligne." txtva=".$txtva." uselocaltax1_rate=".$uselocaltax1_rate." uselocaltax2_rate=".$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$ice_base_type.' type='.$type.' progress='.$progress);
111
-
112
-	$countryid=$seller->country_id;
113
-
114
-	if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate=(float) $uselocaltax1_rate;
115
-	if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate=(float) $uselocaltax2_rate;
116
-
117
-	if ($uselocaltax1_rate < 0) $uselocaltax1_rate=$seller->localtax1_assuj;
118
-	if ($uselocaltax2_rate < 0) $uselocaltax2_rate=$seller->localtax2_assuj;
119
-
120
-	//var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate);
121
-	dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress);
87
+    global $conf,$mysoc,$db;
88
+
89
+    $result=array();
90
+
91
+    // Clean parameters
92
+    if (empty($info_bits)) $info_bits=0;
93
+    if (empty($txtva)) $txtva=0;
94
+    if (empty($seller) || ! is_object($seller))
95
+    {
96
+        dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING);
97
+        if (! is_object($mysoc))	// mysoc may be not defined (during migration process)
98
+        {
99
+            $mysoc=new Societe($db);
100
+            $mysoc->setMysoc($conf);
101
+        }
102
+        $seller=$mysoc;	// If sell is done to a customer, $seller is not provided, we use $mysoc
103
+        //var_dump($seller->country_id);exit;
104
+    }
105
+    if (empty($localtaxes_array) || ! is_array($localtaxes_array))
106
+    {
107
+        dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing", LOG_WARNING);
108
+    }
109
+    // Too verbose. Enable for debug only
110
+    //dol_syslog("Price.lib::calcul_price_total qty=".$qty." pu=".$pu." remiserpercent_ligne=".$remise_percent_ligne." txtva=".$txtva." uselocaltax1_rate=".$uselocaltax1_rate." uselocaltax2_rate=".$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$ice_base_type.' type='.$type.' progress='.$progress);
111
+
112
+    $countryid=$seller->country_id;
113
+
114
+    if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate=(float) $uselocaltax1_rate;
115
+    if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate=(float) $uselocaltax2_rate;
116
+
117
+    if ($uselocaltax1_rate < 0) $uselocaltax1_rate=$seller->localtax1_assuj;
118
+    if ($uselocaltax2_rate < 0) $uselocaltax2_rate=$seller->localtax2_assuj;
119
+
120
+    //var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate);
121
+    dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress);
122 122
 
123 123
     // Now we search localtaxes information ourself (rates and types).
124
-	$localtax1_type=0;
125
-	$localtax2_type=0;
126
-
127
-	if (is_array($localtaxes_array))
128
-	{
129
-		$localtax1_type = $localtaxes_array[0];
130
-		$localtax1_rate = $localtaxes_array[1];
131
-		$localtax2_type = $localtaxes_array[2];
132
-		$localtax2_rate = $localtaxes_array[3];
133
-	}
134
-	else	// deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate
135
-	{
136
-		$sql = "SELECT taux, localtax1, localtax2, localtax1_type, localtax2_type";
137
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as cv";
138
-		$sql.= " WHERE cv.taux = ".$txtva;
139
-		$sql.= " AND cv.fk_pays = ".$countryid;
140
-		dol_syslog("Price.lib::calcul_price_total search vat information using old deprecated method", LOG_WARNING);
141
-		$resql = $db->query($sql);
142
-		if ($resql)
143
-		{
144
-			$obj = $db->fetch_object($resql);
145
-			if ($obj)
146
-			{
147
-				$localtax1_rate=$obj->localtax1;
148
-				$localtax2_rate=$obj->localtax2;
149
-				$localtax1_type=$obj->localtax1_type;
150
-				$localtax2_type=$obj->localtax2_type;
151
-				//var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type);exit;
152
-			}
153
-		}
154
-		else dol_print_error($db);
155
-	}
156
-
157
-	// pu calculation from pu_devise if pu empty
158
-	if (empty($pu) && !empty($pu_devise)) {
159
-		if (! empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx;
160
-		else
161
-		{
162
-			dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR);
163
-			return array();
164
-		}
165
-	}
166
-	if ($pu === '') $pu=0;
167
-	// pu_devise calculation from pu
168
-	if (empty($pu_devise) && !empty($multicurrency_tx)) {
169
-		if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx;
170
-		else
171
-		{
172
-			dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (pu or multicurrency_tx are not numeric)', LOG_ERR);
173
-			return array();
174
-		}
175
-	}
176
-
177
-	// initialize total (may be HT or TTC depending on price_base_type)
178
-	$tot_sans_remise = $pu * $qty * $progress / 100;
179
-	$tot_avec_remise_ligne = $tot_sans_remise       * (1 - ($remise_percent_ligne / 100));
180
-	$tot_avec_remise       = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100));
181
-
182
-	// initialize result array
183
-	for ($i=0; $i <= 15; $i++) $result[$i] = 0;
184
-
185
-	// if there's some localtax including vat, we calculate localtaxes (we will add later)
124
+    $localtax1_type=0;
125
+    $localtax2_type=0;
126
+
127
+    if (is_array($localtaxes_array))
128
+    {
129
+        $localtax1_type = $localtaxes_array[0];
130
+        $localtax1_rate = $localtaxes_array[1];
131
+        $localtax2_type = $localtaxes_array[2];
132
+        $localtax2_rate = $localtaxes_array[3];
133
+    }
134
+    else	// deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate
135
+    {
136
+        $sql = "SELECT taux, localtax1, localtax2, localtax1_type, localtax2_type";
137
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as cv";
138
+        $sql.= " WHERE cv.taux = ".$txtva;
139
+        $sql.= " AND cv.fk_pays = ".$countryid;
140
+        dol_syslog("Price.lib::calcul_price_total search vat information using old deprecated method", LOG_WARNING);
141
+        $resql = $db->query($sql);
142
+        if ($resql)
143
+        {
144
+            $obj = $db->fetch_object($resql);
145
+            if ($obj)
146
+            {
147
+                $localtax1_rate=$obj->localtax1;
148
+                $localtax2_rate=$obj->localtax2;
149
+                $localtax1_type=$obj->localtax1_type;
150
+                $localtax2_type=$obj->localtax2_type;
151
+                //var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type);exit;
152
+            }
153
+        }
154
+        else dol_print_error($db);
155
+    }
156
+
157
+    // pu calculation from pu_devise if pu empty
158
+    if (empty($pu) && !empty($pu_devise)) {
159
+        if (! empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx;
160
+        else
161
+        {
162
+            dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR);
163
+            return array();
164
+        }
165
+    }
166
+    if ($pu === '') $pu=0;
167
+    // pu_devise calculation from pu
168
+    if (empty($pu_devise) && !empty($multicurrency_tx)) {
169
+        if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx;
170
+        else
171
+        {
172
+            dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (pu or multicurrency_tx are not numeric)', LOG_ERR);
173
+            return array();
174
+        }
175
+    }
176
+
177
+    // initialize total (may be HT or TTC depending on price_base_type)
178
+    $tot_sans_remise = $pu * $qty * $progress / 100;
179
+    $tot_avec_remise_ligne = $tot_sans_remise       * (1 - ($remise_percent_ligne / 100));
180
+    $tot_avec_remise       = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100));
181
+
182
+    // initialize result array
183
+    for ($i=0; $i <= 15; $i++) $result[$i] = 0;
184
+
185
+    // if there's some localtax including vat, we calculate localtaxes (we will add later)
186 186
 
187 187
     //If input unit price is 'HT', we need to have the totals with main VAT for a correct calculation
188 188
     if ($price_base_type != 'TTC')
189 189
     {
190
-    	$tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)),'MU');
191
-    	$tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)),'MU');
192
-    	$pu_wt = price2num($pu * (1 + ($txtva / 100)),'MU');
190
+        $tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)),'MU');
191
+        $tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)),'MU');
192
+        $pu_wt = price2num($pu * (1 + ($txtva / 100)),'MU');
193 193
     }
194 194
     else
195 195
     {
196
-    	$tot_sans_remise_wt = $tot_sans_remise;
197
-    	$tot_avec_remise_wt = $tot_avec_remise;
198
-    	$pu_wt = $pu;
196
+        $tot_sans_remise_wt = $tot_sans_remise;
197
+        $tot_avec_remise_wt = $tot_avec_remise;
198
+        $pu_wt = $pu;
199 199
     }
200 200
 
201
-	//print 'rr'.$price_base_type.'-'.$txtva.'-'.$tot_sans_remise_wt."-".$pu_wt."-".$uselocaltax1_rate."-".$localtax1_rate."-".$localtax1_type."\n";
201
+    //print 'rr'.$price_base_type.'-'.$txtva.'-'.$tot_sans_remise_wt."-".$pu_wt."-".$uselocaltax1_rate."-".$localtax1_rate."-".$localtax1_type."\n";
202 202
 
203 203
     $localtaxes = array(0,0,0);
204 204
     $apply_tax = false;
205
-  	switch($localtax1_type) {
206
-      case '2':     // localtax on product or service
205
+        switch($localtax1_type) {
206
+        case '2':     // localtax on product or service
207 207
         $apply_tax = true;
208 208
         break;
209
-      case '4':     // localtax on product
209
+        case '4':     // localtax on product
210 210
         if ($type == 0) $apply_tax = true;
211 211
         break;
212
-      case '6':     // localtax on service
212
+        case '6':     // localtax on service
213 213
         if ($type == 1) $apply_tax = true;
214 214
         break;
215 215
     }
216 216
 
217 217
     if ($uselocaltax1_rate && $apply_tax) {
218
-  		$result[14] = price2num(($tot_sans_remise_wt * (1 + ( $localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT');
219
-  		$localtaxes[0] += $result[14];
218
+            $result[14] = price2num(($tot_sans_remise_wt * (1 + ( $localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT');
219
+            $localtaxes[0] += $result[14];
220 220
 
221
-  		$result[9] = price2num(($tot_avec_remise_wt * (1 + ( $localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT');
222
-  		$localtaxes[1] += $result[9];
221
+            $result[9] = price2num(($tot_avec_remise_wt * (1 + ( $localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT');
222
+            $localtaxes[1] += $result[9];
223 223
 
224
-  		$result[11] = price2num(($pu_wt * (1 + ( $localtax1_rate / 100))) - $pu_wt, 'MU');
225
-  		$localtaxes[2] += $result[11];
224
+            $result[11] = price2num(($pu_wt * (1 + ( $localtax1_rate / 100))) - $pu_wt, 'MU');
225
+            $localtaxes[2] += $result[11];
226 226
     }
227 227
 
228 228
     $apply_tax = false;
229
-  	switch($localtax2_type) {
230
-      case '2':     // localtax on product or service
229
+        switch($localtax2_type) {
230
+        case '2':     // localtax on product or service
231 231
         $apply_tax = true;
232 232
         break;
233
-      case '4':     // localtax on product
233
+        case '4':     // localtax on product
234 234
         if ($type == 0) $apply_tax = true;
235 235
         break;
236
-      case '6':     // localtax on service
236
+        case '6':     // localtax on service
237 237
         if ($type == 1) $apply_tax = true;
238 238
         break;
239 239
     }
240 240
     if ($uselocaltax2_rate && $apply_tax) {
241
-  		$result[15] = price2num(($tot_sans_remise_wt * (1 + ( $localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT');
242
-  		$localtaxes[0] += $result[15];
241
+            $result[15] = price2num(($tot_sans_remise_wt * (1 + ( $localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT');
242
+            $localtaxes[0] += $result[15];
243
+
244
+            $result[10] = price2num(($tot_avec_remise_wt * (1 + ( $localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT');
245
+            $localtaxes[1] += $result[10];
243 246
 
244
-  		$result[10] = price2num(($tot_avec_remise_wt * (1 + ( $localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT');
245
-  		$localtaxes[1] += $result[10];
247
+            $result[12] = price2num(($pu_wt * (1 + ( $localtax2_rate / 100))) - $pu_wt, 'MU');
248
+            $localtaxes[2] += $result[12];
249
+    }
246 250
 
247
-  		$result[12] = price2num(($pu_wt * (1 + ( $localtax2_rate / 100))) - $pu_wt, 'MU');
248
-  		$localtaxes[2] += $result[12];
251
+    //dol_syslog("price.lib::calcul_price_total $qty, $pu, $remise_percent_ligne, $txtva, $price_base_type $info_bits");
252
+    if ($price_base_type == 'HT')
253
+    {
254
+        // We work to define prices using the price without tax
255
+        $result[6] = price2num($tot_sans_remise, 'MT');
256
+        $result[8] = price2num($tot_sans_remise * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[0], 'MT');	// Selon TVA NPR ou non
257
+        $result8bis= price2num($tot_sans_remise * (1 + ( $txtva / 100)) + $localtaxes[0], 'MT');	// Si TVA consideree normale (non NPR)
258
+        $result[7] = price2num($result8bis - ($result[6] + $localtaxes[0]), 'MT');
259
+
260
+        $result[0] = price2num($tot_avec_remise, 'MT');
261
+        $result[2] = price2num($tot_avec_remise * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[1], 'MT');	// Selon TVA NPR ou non
262
+        $result2bis= price2num($tot_avec_remise * (1 + ( $txtva / 100)) + $localtaxes[1], 'MT');	// Si TVA consideree normale (non NPR)
263
+        $result[1] = price2num($result2bis - ($result[0] + $localtaxes[1]), 'MT');	// Total VAT = TTC - (HT + localtax)
264
+
265
+        $result[3] = price2num($pu, 'MU');
266
+        $result[5] = price2num($pu * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[2], 'MU');	// Selon TVA NPR ou non
267
+        $result5bis= price2num($pu * (1 + ($txtva / 100)) + $localtaxes[2], 'MU');	// Si TVA consideree normale (non NPR)
268
+        $result[4] = price2num($result5bis - ($result[3] + $localtaxes[2]), 'MU');
269
+    }
270
+    else
271
+    {
272
+        // We work to define prices using the price with tax
273
+        $result[8] = price2num($tot_sans_remise + $localtaxes[0], 'MT');
274
+        $result[6] = price2num($tot_sans_remise / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MT');	// Selon TVA NPR ou non
275
+        $result6bis= price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MT');	// Si TVA consideree normale (non NPR)
276
+        $result[7] = price2num($result[8] - ($result6bis + $localtaxes[0]), 'MT');
277
+
278
+        $result[2] = price2num($tot_avec_remise + $localtaxes[1], 'MT');
279
+        $result[0] = price2num($tot_avec_remise / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MT');	// Selon TVA NPR ou non
280
+        $result0bis= price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MT');	// Si TVA consideree normale (non NPR)
281
+        $result[1] = price2num($result[2] - ($result0bis + $localtaxes[1]), 'MT');	// Total VAT = TTC - (HT + localtax)
282
+
283
+        $result[5] = price2num($pu + $localtaxes[2], 'MU');
284
+        $result[3] = price2num($pu / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MU');	// Selon TVA NPR ou non
285
+        $result3bis= price2num($pu / (1 + ($txtva / 100)), 'MU');	// Si TVA consideree normale (non NPR)
286
+        $result[4] = price2num($result[5] - ($result3bis + $localtaxes[2]), 'MU');
249 287
     }
250 288
 
251
-	//dol_syslog("price.lib::calcul_price_total $qty, $pu, $remise_percent_ligne, $txtva, $price_base_type $info_bits");
252
-	if ($price_base_type == 'HT')
253
-	{
254
-		// We work to define prices using the price without tax
255
-		$result[6] = price2num($tot_sans_remise, 'MT');
256
-		$result[8] = price2num($tot_sans_remise * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[0], 'MT');	// Selon TVA NPR ou non
257
-		$result8bis= price2num($tot_sans_remise * (1 + ( $txtva / 100)) + $localtaxes[0], 'MT');	// Si TVA consideree normale (non NPR)
258
-		$result[7] = price2num($result8bis - ($result[6] + $localtaxes[0]), 'MT');
259
-
260
-		$result[0] = price2num($tot_avec_remise, 'MT');
261
-		$result[2] = price2num($tot_avec_remise * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[1], 'MT');	// Selon TVA NPR ou non
262
-		$result2bis= price2num($tot_avec_remise * (1 + ( $txtva / 100)) + $localtaxes[1], 'MT');	// Si TVA consideree normale (non NPR)
263
-		$result[1] = price2num($result2bis - ($result[0] + $localtaxes[1]), 'MT');	// Total VAT = TTC - (HT + localtax)
264
-
265
-		$result[3] = price2num($pu, 'MU');
266
-		$result[5] = price2num($pu * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[2], 'MU');	// Selon TVA NPR ou non
267
-		$result5bis= price2num($pu * (1 + ($txtva / 100)) + $localtaxes[2], 'MU');	// Si TVA consideree normale (non NPR)
268
-		$result[4] = price2num($result5bis - ($result[3] + $localtaxes[2]), 'MU');
269
-	}
270
-	else
271
-	{
272
-		// We work to define prices using the price with tax
273
-		$result[8] = price2num($tot_sans_remise + $localtaxes[0], 'MT');
274
-		$result[6] = price2num($tot_sans_remise / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MT');	// Selon TVA NPR ou non
275
-		$result6bis= price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MT');	// Si TVA consideree normale (non NPR)
276
-		$result[7] = price2num($result[8] - ($result6bis + $localtaxes[0]), 'MT');
277
-
278
-		$result[2] = price2num($tot_avec_remise + $localtaxes[1], 'MT');
279
-		$result[0] = price2num($tot_avec_remise / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MT');	// Selon TVA NPR ou non
280
-		$result0bis= price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MT');	// Si TVA consideree normale (non NPR)
281
-		$result[1] = price2num($result[2] - ($result0bis + $localtaxes[1]), 'MT');	// Total VAT = TTC - (HT + localtax)
282
-
283
-		$result[5] = price2num($pu + $localtaxes[2], 'MU');
284
-		$result[3] = price2num($pu / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MU');	// Selon TVA NPR ou non
285
-		$result3bis= price2num($pu / (1 + ($txtva / 100)), 'MU');	// Si TVA consideree normale (non NPR)
286
-		$result[4] = price2num($result[5] - ($result3bis + $localtaxes[2]), 'MU');
287
-	}
288
-
289
-	// if there's some localtax without vat, we calculate localtaxes (we will add them at end)
289
+    // if there's some localtax without vat, we calculate localtaxes (we will add them at end)
290 290
 
291 291
     //If input unit price is 'TTC', we need to have the totals without main VAT for a correct calculation
292 292
     if ($price_base_type == 'TTC')
293 293
     {
294
-    	$tot_sans_remise= price2num($tot_sans_remise / (1 + ($txtva / 100)),'MU');
295
-    	$tot_avec_remise= price2num($tot_avec_remise / (1 + ($txtva / 100)),'MU');
296
-    	$pu = price2num($pu / (1 + ($txtva / 100)),'MU');
294
+        $tot_sans_remise= price2num($tot_sans_remise / (1 + ($txtva / 100)),'MU');
295
+        $tot_avec_remise= price2num($tot_avec_remise / (1 + ($txtva / 100)),'MU');
296
+        $pu = price2num($pu / (1 + ($txtva / 100)),'MU');
297 297
     }
298 298
 
299
-	$apply_tax = false;
299
+    $apply_tax = false;
300 300
     switch($localtax1_type) {
301
-      case '1':     // localtax on product or service
301
+        case '1':     // localtax on product or service
302 302
         $apply_tax = true;
303 303
         break;
304
-      case '3':     // localtax on product
304
+        case '3':     // localtax on product
305 305
         if ($type == 0) $apply_tax = true;
306 306
         break;
307
-      case '5':     // localtax on service
307
+        case '5':     // localtax on service
308 308
         if ($type == 1) $apply_tax = true;
309 309
         break;
310 310
     }
311 311
     if ($uselocaltax1_rate && $apply_tax) {
312
-  		$result[14] = price2num(($tot_sans_remise * (1 + ( $localtax1_rate / 100))) - $tot_sans_remise, 'MT');	// amount tax1 for total_ht_without_discount
313
-  		$result[8] += $result[14];																				// total_ttc_without_discount + tax1
312
+            $result[14] = price2num(($tot_sans_remise * (1 + ( $localtax1_rate / 100))) - $tot_sans_remise, 'MT');	// amount tax1 for total_ht_without_discount
313
+            $result[8] += $result[14];																				// total_ttc_without_discount + tax1
314 314
 
315
-  		$result[9] = price2num(($tot_avec_remise * (1 + ( $localtax1_rate / 100))) - $tot_avec_remise, 'MT');	// amount tax1 for total_ht
316
-  		$result[2] += $result[9];																				// total_ttc + tax1
315
+            $result[9] = price2num(($tot_avec_remise * (1 + ( $localtax1_rate / 100))) - $tot_avec_remise, 'MT');	// amount tax1 for total_ht
316
+            $result[2] += $result[9];																				// total_ttc + tax1
317 317
 
318
-  		$result[11] = price2num(($pu * (1 + ( $localtax1_rate / 100))) - $pu, 'MU');							// amount tax1 for pu_ht
319
-  		$result[5] += $result[11];																				// pu_ht + tax1
318
+            $result[11] = price2num(($pu * (1 + ( $localtax1_rate / 100))) - $pu, 'MU');							// amount tax1 for pu_ht
319
+            $result[5] += $result[11];																				// pu_ht + tax1
320 320
     }
321 321
 
322 322
     $apply_tax = false;
323
-  	switch($localtax2_type) {
324
-      case '1':     // localtax on product or service
323
+        switch($localtax2_type) {
324
+        case '1':     // localtax on product or service
325 325
         $apply_tax = true;
326 326
         break;
327
-      case '3':     // localtax on product
327
+        case '3':     // localtax on product
328 328
         if ($type == 0) $apply_tax = true;
329 329
         break;
330
-      case '5':     // localtax on service
330
+        case '5':     // localtax on service
331 331
         if ($type == 1) $apply_tax = true;
332 332
         break;
333 333
     }
334 334
     if ($uselocaltax2_rate && $apply_tax) {
335
-  		$result[15] = price2num(($tot_sans_remise * (1 + ( $localtax2_rate / 100))) - $tot_sans_remise, 'MT');	// amount tax2 for total_ht_without_discount
336
-  		$result[8] += $result[15];																				// total_ttc_without_discount + tax2
335
+            $result[15] = price2num(($tot_sans_remise * (1 + ( $localtax2_rate / 100))) - $tot_sans_remise, 'MT');	// amount tax2 for total_ht_without_discount
336
+            $result[8] += $result[15];																				// total_ttc_without_discount + tax2
337 337
 
338
-  		$result[10] = price2num(($tot_avec_remise * (1 + ( $localtax2_rate / 100))) - $tot_avec_remise, 'MT');	// amount tax2 for total_ht
339
-  		$result[2] += $result[10];																				// total_ttc + tax2
338
+            $result[10] = price2num(($tot_avec_remise * (1 + ( $localtax2_rate / 100))) - $tot_avec_remise, 'MT');	// amount tax2 for total_ht
339
+            $result[2] += $result[10];																				// total_ttc + tax2
340 340
 
341
-  		$result[12] = price2num(($pu * (1 + ( $localtax2_rate / 100))) - $pu, 'MU');							// amount tax2 for pu_ht
342
-  		$result[5] += $result[12];																				// pu_ht + tax2
341
+            $result[12] = price2num(($pu * (1 + ( $localtax2_rate / 100))) - $pu, 'MU');							// amount tax2 for pu_ht
342
+            $result[5] += $result[12];																				// pu_ht + tax2
343 343
     }
344 344
 
345
-	// If rounding is not using base 10 (rare)
346
-	if (! empty($conf->global->MAIN_ROUNDING_RULE_TOT))
347
-	{
348
-		if ($price_base_type == 'HT')
349
-		{
350
-			$result[0]=round($result[0]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
351
-			$result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
352
-			$result[2]=price2num($result[0]+$result[1], 'MT');
353
-			$result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
354
-			$result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
355
-		}
356
-		else
357
-		{
358
-			$result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
359
-			$result[2]=round($result[2]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
360
-			$result[0]=price2num($result[2]-$result[1], 'MT');
361
-			$result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
362
-			$result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
363
-		}
364
-	}
365
-
366
-	// Multicurrency
367
-	if ($multicurrency_tx != 1)
368
-	{
369
-		// Recal function using the multicurrency price as reference price. We must set param $multicurrency_tx to 1 to avoid infinite loop.
370
-		$newresult = calcul_price_total($qty, $pu_devise, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller, $localtaxes_array, $progress, 1, 0);
371
-
372
-		$result[16] = $newresult[0];
373
-		$result[17] = $newresult[1];
374
-		$result[18] = $newresult[2];
375
-		$result[19] = $newresult[3];
376
-		$result[20] = $newresult[4];
377
-		$result[21] = $newresult[5];
378
-		$result[22] = $newresult[6];
379
-		$result[23] = $newresult[7];
380
-		$result[24] = $newresult[8];
381
-		$result[25] = $newresult[9];
382
-		$result[26] = $newresult[10];
383
-		/*
345
+    // If rounding is not using base 10 (rare)
346
+    if (! empty($conf->global->MAIN_ROUNDING_RULE_TOT))
347
+    {
348
+        if ($price_base_type == 'HT')
349
+        {
350
+            $result[0]=round($result[0]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
351
+            $result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
352
+            $result[2]=price2num($result[0]+$result[1], 'MT');
353
+            $result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
354
+            $result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
355
+        }
356
+        else
357
+        {
358
+            $result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
359
+            $result[2]=round($result[2]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
360
+            $result[0]=price2num($result[2]-$result[1], 'MT');
361
+            $result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
362
+            $result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
363
+        }
364
+    }
365
+
366
+    // Multicurrency
367
+    if ($multicurrency_tx != 1)
368
+    {
369
+        // Recal function using the multicurrency price as reference price. We must set param $multicurrency_tx to 1 to avoid infinite loop.
370
+        $newresult = calcul_price_total($qty, $pu_devise, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller, $localtaxes_array, $progress, 1, 0);
371
+
372
+        $result[16] = $newresult[0];
373
+        $result[17] = $newresult[1];
374
+        $result[18] = $newresult[2];
375
+        $result[19] = $newresult[3];
376
+        $result[20] = $newresult[4];
377
+        $result[21] = $newresult[5];
378
+        $result[22] = $newresult[6];
379
+        $result[23] = $newresult[7];
380
+        $result[24] = $newresult[8];
381
+        $result[25] = $newresult[9];
382
+        $result[26] = $newresult[10];
383
+        /*
384 384
 		$result[16] = price2num($result[0] * $multicurrency_tx, 'MT');
385 385
 		$result[17] = price2num($result[1] * $multicurrency_tx, 'MT');
386 386
 		$result[18] = price2num($result[2] * $multicurrency_tx, 'MT');
387 387
 		$result[19] = price2num($pu_devise, 'MU');
388 388
 		*/
389
-	}
390
-	else
391
-	{
392
-		$result[16] = $result[0];
393
-		$result[17] = $result[1];
394
-		$result[18] = $result[2];
395
-		$result[19] = $result[3];
396
-		$result[20] = $result[4];
397
-		$result[21] = $result[5];
398
-		$result[22] = $result[6];
399
-		$result[23] = $result[7];
400
-		$result[24] = $result[8];
401
-		$result[25] = $result[9];
402
-		$result[26] = $result[10];
403
-	}
404
-
405
-	//var_dump($result);
406
-	// initialize result array
407
-	//for ($i=0; $i <= 18; $i++) $result[$i] = (float) $result[$i];
408
-
409
-	dol_syslog('Price.lib::calcul_price_total MAIN_ROUNDING_RULE_TOT='.$conf->global->MAIN_ROUNDING_RULE_TOT.' pu='.$pu.' qty='.$qty.' price_base_type='.$price_base_type.' total_ht='.$result[0].'-total_vat='.$result[1].'-total_ttc='.$result[2]);
410
-
411
-	return $result;
389
+    }
390
+    else
391
+    {
392
+        $result[16] = $result[0];
393
+        $result[17] = $result[1];
394
+        $result[18] = $result[2];
395
+        $result[19] = $result[3];
396
+        $result[20] = $result[4];
397
+        $result[21] = $result[5];
398
+        $result[22] = $result[6];
399
+        $result[23] = $result[7];
400
+        $result[24] = $result[8];
401
+        $result[25] = $result[9];
402
+        $result[26] = $result[10];
403
+    }
404
+
405
+    //var_dump($result);
406
+    // initialize result array
407
+    //for ($i=0; $i <= 18; $i++) $result[$i] = (float) $result[$i];
408
+
409
+    dol_syslog('Price.lib::calcul_price_total MAIN_ROUNDING_RULE_TOT='.$conf->global->MAIN_ROUNDING_RULE_TOT.' pu='.$pu.' qty='.$qty.' price_base_type='.$price_base_type.' total_ht='.$result[0].'-total_vat='.$result[1].'-total_ttc='.$result[2]);
410
+
411
+    return $result;
412 412
 }
413 413
 
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -82,47 +82,47 @@  discard block
 block discarded – undo
82 82
  * 						25=multicurrency_total_tax1 for total_ht
83 83
  *                      26=multicurrency_total_tax2 for total_ht
84 84
  */
85
-function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller = '', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0)
85
+function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller = '', $localtaxes_array = '', $progress = 100, $multicurrency_tx = 1, $pu_devise = 0)
86 86
 {
87
-	global $conf,$mysoc,$db;
87
+	global $conf, $mysoc, $db;
88 88
 
89
-	$result=array();
89
+	$result = array();
90 90
 
91 91
 	// Clean parameters
92
-	if (empty($info_bits)) $info_bits=0;
93
-	if (empty($txtva)) $txtva=0;
94
-	if (empty($seller) || ! is_object($seller))
92
+	if (empty($info_bits)) $info_bits = 0;
93
+	if (empty($txtva)) $txtva = 0;
94
+	if (empty($seller) || !is_object($seller))
95 95
 	{
96 96
 		dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING);
97
-		if (! is_object($mysoc))	// mysoc may be not defined (during migration process)
97
+		if (!is_object($mysoc))	// mysoc may be not defined (during migration process)
98 98
 		{
99
-			$mysoc=new Societe($db);
99
+			$mysoc = new Societe($db);
100 100
 			$mysoc->setMysoc($conf);
101 101
 		}
102
-		$seller=$mysoc;	// If sell is done to a customer, $seller is not provided, we use $mysoc
102
+		$seller = $mysoc; // If sell is done to a customer, $seller is not provided, we use $mysoc
103 103
 		//var_dump($seller->country_id);exit;
104 104
 	}
105
-	if (empty($localtaxes_array) || ! is_array($localtaxes_array))
105
+	if (empty($localtaxes_array) || !is_array($localtaxes_array))
106 106
 	{
107 107
 		dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing", LOG_WARNING);
108 108
 	}
109 109
 	// Too verbose. Enable for debug only
110 110
 	//dol_syslog("Price.lib::calcul_price_total qty=".$qty." pu=".$pu." remiserpercent_ligne=".$remise_percent_ligne." txtva=".$txtva." uselocaltax1_rate=".$uselocaltax1_rate." uselocaltax2_rate=".$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$ice_base_type.' type='.$type.' progress='.$progress);
111 111
 
112
-	$countryid=$seller->country_id;
112
+	$countryid = $seller->country_id;
113 113
 
114
-	if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate=(float) $uselocaltax1_rate;
115
-	if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate=(float) $uselocaltax2_rate;
114
+	if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate = (float) $uselocaltax1_rate;
115
+	if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate = (float) $uselocaltax2_rate;
116 116
 
117
-	if ($uselocaltax1_rate < 0) $uselocaltax1_rate=$seller->localtax1_assuj;
118
-	if ($uselocaltax2_rate < 0) $uselocaltax2_rate=$seller->localtax2_assuj;
117
+	if ($uselocaltax1_rate < 0) $uselocaltax1_rate = $seller->localtax1_assuj;
118
+	if ($uselocaltax2_rate < 0) $uselocaltax2_rate = $seller->localtax2_assuj;
119 119
 
120 120
 	//var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate);
121 121
 	dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress);
122 122
 
123 123
     // Now we search localtaxes information ourself (rates and types).
124
-	$localtax1_type=0;
125
-	$localtax2_type=0;
124
+	$localtax1_type = 0;
125
+	$localtax2_type = 0;
126 126
 
127 127
 	if (is_array($localtaxes_array))
128 128
 	{
@@ -134,9 +134,9 @@  discard block
 block discarded – undo
134 134
 	else	// deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate
135 135
 	{
136 136
 		$sql = "SELECT taux, localtax1, localtax2, localtax1_type, localtax2_type";
137
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as cv";
138
-		$sql.= " WHERE cv.taux = ".$txtva;
139
-		$sql.= " AND cv.fk_pays = ".$countryid;
137
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as cv";
138
+		$sql .= " WHERE cv.taux = ".$txtva;
139
+		$sql .= " AND cv.fk_pays = ".$countryid;
140 140
 		dol_syslog("Price.lib::calcul_price_total search vat information using old deprecated method", LOG_WARNING);
141 141
 		$resql = $db->query($sql);
142 142
 		if ($resql)
@@ -144,10 +144,10 @@  discard block
 block discarded – undo
144 144
 			$obj = $db->fetch_object($resql);
145 145
 			if ($obj)
146 146
 			{
147
-				$localtax1_rate=$obj->localtax1;
148
-				$localtax2_rate=$obj->localtax2;
149
-				$localtax1_type=$obj->localtax1_type;
150
-				$localtax2_type=$obj->localtax2_type;
147
+				$localtax1_rate = $obj->localtax1;
148
+				$localtax2_rate = $obj->localtax2;
149
+				$localtax1_type = $obj->localtax1_type;
150
+				$localtax2_type = $obj->localtax2_type;
151 151
 				//var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type);exit;
152 152
 			}
153 153
 		}
@@ -156,14 +156,14 @@  discard block
 block discarded – undo
156 156
 
157 157
 	// pu calculation from pu_devise if pu empty
158 158
 	if (empty($pu) && !empty($pu_devise)) {
159
-		if (! empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx;
159
+		if (!empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx;
160 160
 		else
161 161
 		{
162 162
 			dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR);
163 163
 			return array();
164 164
 		}
165 165
 	}
166
-	if ($pu === '') $pu=0;
166
+	if ($pu === '') $pu = 0;
167 167
 	// pu_devise calculation from pu
168 168
 	if (empty($pu_devise) && !empty($multicurrency_tx)) {
169 169
 		if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx;
@@ -176,20 +176,20 @@  discard block
 block discarded – undo
176 176
 
177 177
 	// initialize total (may be HT or TTC depending on price_base_type)
178 178
 	$tot_sans_remise = $pu * $qty * $progress / 100;
179
-	$tot_avec_remise_ligne = $tot_sans_remise       * (1 - ($remise_percent_ligne / 100));
179
+	$tot_avec_remise_ligne = $tot_sans_remise * (1 - ($remise_percent_ligne / 100));
180 180
 	$tot_avec_remise       = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100));
181 181
 
182 182
 	// initialize result array
183
-	for ($i=0; $i <= 15; $i++) $result[$i] = 0;
183
+	for ($i = 0; $i <= 15; $i++) $result[$i] = 0;
184 184
 
185 185
 	// if there's some localtax including vat, we calculate localtaxes (we will add later)
186 186
 
187 187
     //If input unit price is 'HT', we need to have the totals with main VAT for a correct calculation
188 188
     if ($price_base_type != 'TTC')
189 189
     {
190
-    	$tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)),'MU');
191
-    	$tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)),'MU');
192
-    	$pu_wt = price2num($pu * (1 + ($txtva / 100)),'MU');
190
+    	$tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)), 'MU');
191
+    	$tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)), 'MU');
192
+    	$pu_wt = price2num($pu * (1 + ($txtva / 100)), 'MU');
193 193
     }
194 194
     else
195 195
     {
@@ -200,9 +200,9 @@  discard block
 block discarded – undo
200 200
 
201 201
 	//print 'rr'.$price_base_type.'-'.$txtva.'-'.$tot_sans_remise_wt."-".$pu_wt."-".$uselocaltax1_rate."-".$localtax1_rate."-".$localtax1_type."\n";
202 202
 
203
-    $localtaxes = array(0,0,0);
203
+    $localtaxes = array(0, 0, 0);
204 204
     $apply_tax = false;
205
-  	switch($localtax1_type) {
205
+  	switch ($localtax1_type) {
206 206
       case '2':     // localtax on product or service
207 207
         $apply_tax = true;
208 208
         break;
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
     }
216 216
 
217 217
     if ($uselocaltax1_rate && $apply_tax) {
218
-  		$result[14] = price2num(($tot_sans_remise_wt * (1 + ( $localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT');
218
+  		$result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT');
219 219
   		$localtaxes[0] += $result[14];
220 220
 
221
-  		$result[9] = price2num(($tot_avec_remise_wt * (1 + ( $localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT');
221
+  		$result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT');
222 222
   		$localtaxes[1] += $result[9];
223 223
 
224
-  		$result[11] = price2num(($pu_wt * (1 + ( $localtax1_rate / 100))) - $pu_wt, 'MU');
224
+  		$result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU');
225 225
   		$localtaxes[2] += $result[11];
226 226
     }
227 227
 
228 228
     $apply_tax = false;
229
-  	switch($localtax2_type) {
229
+  	switch ($localtax2_type) {
230 230
       case '2':     // localtax on product or service
231 231
         $apply_tax = true;
232 232
         break;
@@ -238,13 +238,13 @@  discard block
 block discarded – undo
238 238
         break;
239 239
     }
240 240
     if ($uselocaltax2_rate && $apply_tax) {
241
-  		$result[15] = price2num(($tot_sans_remise_wt * (1 + ( $localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT');
241
+  		$result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT');
242 242
   		$localtaxes[0] += $result[15];
243 243
 
244
-  		$result[10] = price2num(($tot_avec_remise_wt * (1 + ( $localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT');
244
+  		$result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT');
245 245
   		$localtaxes[1] += $result[10];
246 246
 
247
-  		$result[12] = price2num(($pu_wt * (1 + ( $localtax2_rate / 100))) - $pu_wt, 'MU');
247
+  		$result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU');
248 248
   		$localtaxes[2] += $result[12];
249 249
     }
250 250
 
@@ -253,36 +253,36 @@  discard block
 block discarded – undo
253 253
 	{
254 254
 		// We work to define prices using the price without tax
255 255
 		$result[6] = price2num($tot_sans_remise, 'MT');
256
-		$result[8] = price2num($tot_sans_remise * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[0], 'MT');	// Selon TVA NPR ou non
257
-		$result8bis= price2num($tot_sans_remise * (1 + ( $txtva / 100)) + $localtaxes[0], 'MT');	// Si TVA consideree normale (non NPR)
256
+		$result[8] = price2num($tot_sans_remise * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[0], 'MT'); // Selon TVA NPR ou non
257
+		$result8bis = price2num($tot_sans_remise * (1 + ($txtva / 100)) + $localtaxes[0], 'MT'); // Si TVA consideree normale (non NPR)
258 258
 		$result[7] = price2num($result8bis - ($result[6] + $localtaxes[0]), 'MT');
259 259
 
260 260
 		$result[0] = price2num($tot_avec_remise, 'MT');
261
-		$result[2] = price2num($tot_avec_remise * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[1], 'MT');	// Selon TVA NPR ou non
262
-		$result2bis= price2num($tot_avec_remise * (1 + ( $txtva / 100)) + $localtaxes[1], 'MT');	// Si TVA consideree normale (non NPR)
263
-		$result[1] = price2num($result2bis - ($result[0] + $localtaxes[1]), 'MT');	// Total VAT = TTC - (HT + localtax)
261
+		$result[2] = price2num($tot_avec_remise * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[1], 'MT'); // Selon TVA NPR ou non
262
+		$result2bis = price2num($tot_avec_remise * (1 + ($txtva / 100)) + $localtaxes[1], 'MT'); // Si TVA consideree normale (non NPR)
263
+		$result[1] = price2num($result2bis - ($result[0] + $localtaxes[1]), 'MT'); // Total VAT = TTC - (HT + localtax)
264 264
 
265 265
 		$result[3] = price2num($pu, 'MU');
266
-		$result[5] = price2num($pu * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[2], 'MU');	// Selon TVA NPR ou non
267
-		$result5bis= price2num($pu * (1 + ($txtva / 100)) + $localtaxes[2], 'MU');	// Si TVA consideree normale (non NPR)
266
+		$result[5] = price2num($pu * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[2], 'MU'); // Selon TVA NPR ou non
267
+		$result5bis = price2num($pu * (1 + ($txtva / 100)) + $localtaxes[2], 'MU'); // Si TVA consideree normale (non NPR)
268 268
 		$result[4] = price2num($result5bis - ($result[3] + $localtaxes[2]), 'MU');
269 269
 	}
270 270
 	else
271 271
 	{
272 272
 		// We work to define prices using the price with tax
273 273
 		$result[8] = price2num($tot_sans_remise + $localtaxes[0], 'MT');
274
-		$result[6] = price2num($tot_sans_remise / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MT');	// Selon TVA NPR ou non
275
-		$result6bis= price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MT');	// Si TVA consideree normale (non NPR)
274
+		$result[6] = price2num($tot_sans_remise / (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)), 'MT'); // Selon TVA NPR ou non
275
+		$result6bis = price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MT'); // Si TVA consideree normale (non NPR)
276 276
 		$result[7] = price2num($result[8] - ($result6bis + $localtaxes[0]), 'MT');
277 277
 
278 278
 		$result[2] = price2num($tot_avec_remise + $localtaxes[1], 'MT');
279
-		$result[0] = price2num($tot_avec_remise / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MT');	// Selon TVA NPR ou non
280
-		$result0bis= price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MT');	// Si TVA consideree normale (non NPR)
281
-		$result[1] = price2num($result[2] - ($result0bis + $localtaxes[1]), 'MT');	// Total VAT = TTC - (HT + localtax)
279
+		$result[0] = price2num($tot_avec_remise / (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)), 'MT'); // Selon TVA NPR ou non
280
+		$result0bis = price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MT'); // Si TVA consideree normale (non NPR)
281
+		$result[1] = price2num($result[2] - ($result0bis + $localtaxes[1]), 'MT'); // Total VAT = TTC - (HT + localtax)
282 282
 
283 283
 		$result[5] = price2num($pu + $localtaxes[2], 'MU');
284
-		$result[3] = price2num($pu / (1 + ((($info_bits & 1)?0:$txtva) / 100)), 'MU');	// Selon TVA NPR ou non
285
-		$result3bis= price2num($pu / (1 + ($txtva / 100)), 'MU');	// Si TVA consideree normale (non NPR)
284
+		$result[3] = price2num($pu / (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)), 'MU'); // Selon TVA NPR ou non
285
+		$result3bis = price2num($pu / (1 + ($txtva / 100)), 'MU'); // Si TVA consideree normale (non NPR)
286 286
 		$result[4] = price2num($result[5] - ($result3bis + $localtaxes[2]), 'MU');
287 287
 	}
288 288
 
@@ -291,13 +291,13 @@  discard block
 block discarded – undo
291 291
     //If input unit price is 'TTC', we need to have the totals without main VAT for a correct calculation
292 292
     if ($price_base_type == 'TTC')
293 293
     {
294
-    	$tot_sans_remise= price2num($tot_sans_remise / (1 + ($txtva / 100)),'MU');
295
-    	$tot_avec_remise= price2num($tot_avec_remise / (1 + ($txtva / 100)),'MU');
296
-    	$pu = price2num($pu / (1 + ($txtva / 100)),'MU');
294
+    	$tot_sans_remise = price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MU');
295
+    	$tot_avec_remise = price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MU');
296
+    	$pu = price2num($pu / (1 + ($txtva / 100)), 'MU');
297 297
     }
298 298
 
299 299
 	$apply_tax = false;
300
-    switch($localtax1_type) {
300
+    switch ($localtax1_type) {
301 301
       case '1':     // localtax on product or service
302 302
         $apply_tax = true;
303 303
         break;
@@ -309,18 +309,18 @@  discard block
 block discarded – undo
309 309
         break;
310 310
     }
311 311
     if ($uselocaltax1_rate && $apply_tax) {
312
-  		$result[14] = price2num(($tot_sans_remise * (1 + ( $localtax1_rate / 100))) - $tot_sans_remise, 'MT');	// amount tax1 for total_ht_without_discount
313
-  		$result[8] += $result[14];																				// total_ttc_without_discount + tax1
312
+  		$result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount
313
+  		$result[8] += $result[14]; // total_ttc_without_discount + tax1
314 314
 
315
-  		$result[9] = price2num(($tot_avec_remise * (1 + ( $localtax1_rate / 100))) - $tot_avec_remise, 'MT');	// amount tax1 for total_ht
316
-  		$result[2] += $result[9];																				// total_ttc + tax1
315
+  		$result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht
316
+  		$result[2] += $result[9]; // total_ttc + tax1
317 317
 
318
-  		$result[11] = price2num(($pu * (1 + ( $localtax1_rate / 100))) - $pu, 'MU');							// amount tax1 for pu_ht
319
-  		$result[5] += $result[11];																				// pu_ht + tax1
318
+  		$result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht
319
+  		$result[5] += $result[11]; // pu_ht + tax1
320 320
     }
321 321
 
322 322
     $apply_tax = false;
323
-  	switch($localtax2_type) {
323
+  	switch ($localtax2_type) {
324 324
       case '1':     // localtax on product or service
325 325
         $apply_tax = true;
326 326
         break;
@@ -332,34 +332,34 @@  discard block
 block discarded – undo
332 332
         break;
333 333
     }
334 334
     if ($uselocaltax2_rate && $apply_tax) {
335
-  		$result[15] = price2num(($tot_sans_remise * (1 + ( $localtax2_rate / 100))) - $tot_sans_remise, 'MT');	// amount tax2 for total_ht_without_discount
336
-  		$result[8] += $result[15];																				// total_ttc_without_discount + tax2
335
+  		$result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount
336
+  		$result[8] += $result[15]; // total_ttc_without_discount + tax2
337 337
 
338
-  		$result[10] = price2num(($tot_avec_remise * (1 + ( $localtax2_rate / 100))) - $tot_avec_remise, 'MT');	// amount tax2 for total_ht
339
-  		$result[2] += $result[10];																				// total_ttc + tax2
338
+  		$result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht
339
+  		$result[2] += $result[10]; // total_ttc + tax2
340 340
 
341
-  		$result[12] = price2num(($pu * (1 + ( $localtax2_rate / 100))) - $pu, 'MU');							// amount tax2 for pu_ht
342
-  		$result[5] += $result[12];																				// pu_ht + tax2
341
+  		$result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht
342
+  		$result[5] += $result[12]; // pu_ht + tax2
343 343
     }
344 344
 
345 345
 	// If rounding is not using base 10 (rare)
346
-	if (! empty($conf->global->MAIN_ROUNDING_RULE_TOT))
346
+	if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT))
347 347
 	{
348 348
 		if ($price_base_type == 'HT')
349 349
 		{
350
-			$result[0]=round($result[0]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
351
-			$result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
352
-			$result[2]=price2num($result[0]+$result[1], 'MT');
353
-			$result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
354
-			$result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
350
+			$result[0] = round($result[0] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
351
+			$result[1] = round($result[1] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
352
+			$result[2] = price2num($result[0] + $result[1], 'MT');
353
+			$result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
354
+			$result[10] = round($result[10] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
355 355
 		}
356 356
 		else
357 357
 		{
358
-			$result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
359
-			$result[2]=round($result[2]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
360
-			$result[0]=price2num($result[2]-$result[1], 'MT');
361
-			$result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
362
-			$result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
358
+			$result[1] = round($result[1] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
359
+			$result[2] = round($result[2] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
360
+			$result[0] = price2num($result[2] - $result[1], 'MT');
361
+			$result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
362
+			$result[10] = round($result[10] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT;
363 363
 		}
364 364
 	}
365 365
 
Please login to merge, or discard this patch.
Braces   +64 added lines, -32 removed lines patch added patch discarded remove patch
@@ -89,14 +89,20 @@  discard block
 block discarded – undo
89 89
 	$result=array();
90 90
 
91 91
 	// Clean parameters
92
-	if (empty($info_bits)) $info_bits=0;
93
-	if (empty($txtva)) $txtva=0;
92
+	if (empty($info_bits)) {
93
+	    $info_bits=0;
94
+	}
95
+	if (empty($txtva)) {
96
+	    $txtva=0;
97
+	}
94 98
 	if (empty($seller) || ! is_object($seller))
95 99
 	{
96 100
 		dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING);
97
-		if (! is_object($mysoc))	// mysoc may be not defined (during migration process)
101
+		if (! is_object($mysoc)) {
102
+		    // mysoc may be not defined (during migration process)
98 103
 		{
99 104
 			$mysoc=new Societe($db);
105
+		}
100 106
 			$mysoc->setMysoc($conf);
101 107
 		}
102 108
 		$seller=$mysoc;	// If sell is done to a customer, $seller is not provided, we use $mysoc
@@ -111,11 +117,19 @@  discard block
 block discarded – undo
111 117
 
112 118
 	$countryid=$seller->country_id;
113 119
 
114
-	if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate=(float) $uselocaltax1_rate;
115
-	if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate=(float) $uselocaltax2_rate;
120
+	if (is_numeric($uselocaltax1_rate)) {
121
+	    $uselocaltax1_rate=(float) $uselocaltax1_rate;
122
+	}
123
+	if (is_numeric($uselocaltax2_rate)) {
124
+	    $uselocaltax2_rate=(float) $uselocaltax2_rate;
125
+	}
116 126
 
117
-	if ($uselocaltax1_rate < 0) $uselocaltax1_rate=$seller->localtax1_assuj;
118
-	if ($uselocaltax2_rate < 0) $uselocaltax2_rate=$seller->localtax2_assuj;
127
+	if ($uselocaltax1_rate < 0) {
128
+	    $uselocaltax1_rate=$seller->localtax1_assuj;
129
+	}
130
+	if ($uselocaltax2_rate < 0) {
131
+	    $uselocaltax2_rate=$seller->localtax2_assuj;
132
+	}
119 133
 
120 134
 	//var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate);
121 135
 	dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress);
@@ -130,8 +144,7 @@  discard block
 block discarded – undo
130 144
 		$localtax1_rate = $localtaxes_array[1];
131 145
 		$localtax2_type = $localtaxes_array[2];
132 146
 		$localtax2_rate = $localtaxes_array[3];
133
-	}
134
-	else	// deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate
147
+	} else	// deprecated method. values and type for localtaxes must be provided by caller and loaded with getLocalTaxesFromRate
135 148
 	{
136 149
 		$sql = "SELECT taux, localtax1, localtax2, localtax1_type, localtax2_type";
137 150
 		$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as cv";
@@ -150,24 +163,29 @@  discard block
 block discarded – undo
150 163
 				$localtax2_type=$obj->localtax2_type;
151 164
 				//var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type);exit;
152 165
 			}
166
+		} else {
167
+		    dol_print_error($db);
153 168
 		}
154
-		else dol_print_error($db);
155 169
 	}
156 170
 
157 171
 	// pu calculation from pu_devise if pu empty
158 172
 	if (empty($pu) && !empty($pu_devise)) {
159
-		if (! empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx;
160
-		else
173
+		if (! empty($multicurrency_tx)) {
174
+		    $pu = $pu_devise / $multicurrency_tx;
175
+		} else
161 176
 		{
162 177
 			dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR);
163 178
 			return array();
164 179
 		}
165 180
 	}
166
-	if ($pu === '') $pu=0;
181
+	if ($pu === '') {
182
+	    $pu=0;
183
+	}
167 184
 	// pu_devise calculation from pu
168 185
 	if (empty($pu_devise) && !empty($multicurrency_tx)) {
169
-		if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx;
170
-		else
186
+		if (is_numeric($pu) && is_numeric($multicurrency_tx)) {
187
+		    $pu_devise = $pu * $multicurrency_tx;
188
+		} else
171 189
 		{
172 190
 			dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (pu or multicurrency_tx are not numeric)', LOG_ERR);
173 191
 			return array();
@@ -180,7 +198,9 @@  discard block
 block discarded – undo
180 198
 	$tot_avec_remise       = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100));
181 199
 
182 200
 	// initialize result array
183
-	for ($i=0; $i <= 15; $i++) $result[$i] = 0;
201
+	for ($i=0; $i <= 15; $i++) {
202
+	    $result[$i] = 0;
203
+	}
184 204
 
185 205
 	// if there's some localtax including vat, we calculate localtaxes (we will add later)
186 206
 
@@ -190,8 +210,7 @@  discard block
 block discarded – undo
190 210
     	$tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)),'MU');
191 211
     	$tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)),'MU');
192 212
     	$pu_wt = price2num($pu * (1 + ($txtva / 100)),'MU');
193
-    }
194
-    else
213
+    } else
195 214
     {
196 215
     	$tot_sans_remise_wt = $tot_sans_remise;
197 216
     	$tot_avec_remise_wt = $tot_avec_remise;
@@ -207,10 +226,14 @@  discard block
 block discarded – undo
207 226
         $apply_tax = true;
208 227
         break;
209 228
       case '4':     // localtax on product
210
-        if ($type == 0) $apply_tax = true;
229
+        if ($type == 0) {
230
+            $apply_tax = true;
231
+        }
211 232
         break;
212 233
       case '6':     // localtax on service
213
-        if ($type == 1) $apply_tax = true;
234
+        if ($type == 1) {
235
+            $apply_tax = true;
236
+        }
214 237
         break;
215 238
     }
216 239
 
@@ -231,10 +254,14 @@  discard block
 block discarded – undo
231 254
         $apply_tax = true;
232 255
         break;
233 256
       case '4':     // localtax on product
234
-        if ($type == 0) $apply_tax = true;
257
+        if ($type == 0) {
258
+            $apply_tax = true;
259
+        }
235 260
         break;
236 261
       case '6':     // localtax on service
237
-        if ($type == 1) $apply_tax = true;
262
+        if ($type == 1) {
263
+            $apply_tax = true;
264
+        }
238 265
         break;
239 266
     }
240 267
     if ($uselocaltax2_rate && $apply_tax) {
@@ -266,8 +293,7 @@  discard block
 block discarded – undo
266 293
 		$result[5] = price2num($pu * (1 + ( (($info_bits & 1)?0:$txtva) / 100)) + $localtaxes[2], 'MU');	// Selon TVA NPR ou non
267 294
 		$result5bis= price2num($pu * (1 + ($txtva / 100)) + $localtaxes[2], 'MU');	// Si TVA consideree normale (non NPR)
268 295
 		$result[4] = price2num($result5bis - ($result[3] + $localtaxes[2]), 'MU');
269
-	}
270
-	else
296
+	} else
271 297
 	{
272 298
 		// We work to define prices using the price with tax
273 299
 		$result[8] = price2num($tot_sans_remise + $localtaxes[0], 'MT');
@@ -302,10 +328,14 @@  discard block
 block discarded – undo
302 328
         $apply_tax = true;
303 329
         break;
304 330
       case '3':     // localtax on product
305
-        if ($type == 0) $apply_tax = true;
331
+        if ($type == 0) {
332
+            $apply_tax = true;
333
+        }
306 334
         break;
307 335
       case '5':     // localtax on service
308
-        if ($type == 1) $apply_tax = true;
336
+        if ($type == 1) {
337
+            $apply_tax = true;
338
+        }
309 339
         break;
310 340
     }
311 341
     if ($uselocaltax1_rate && $apply_tax) {
@@ -325,10 +355,14 @@  discard block
 block discarded – undo
325 355
         $apply_tax = true;
326 356
         break;
327 357
       case '3':     // localtax on product
328
-        if ($type == 0) $apply_tax = true;
358
+        if ($type == 0) {
359
+            $apply_tax = true;
360
+        }
329 361
         break;
330 362
       case '5':     // localtax on service
331
-        if ($type == 1) $apply_tax = true;
363
+        if ($type == 1) {
364
+            $apply_tax = true;
365
+        }
332 366
         break;
333 367
     }
334 368
     if ($uselocaltax2_rate && $apply_tax) {
@@ -352,8 +386,7 @@  discard block
 block discarded – undo
352 386
 			$result[2]=price2num($result[0]+$result[1], 'MT');
353 387
 			$result[9]=round($result[9]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
354 388
 			$result[10]=round($result[10]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
355
-		}
356
-		else
389
+		} else
357 390
 		{
358 391
 			$result[1]=round($result[1]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
359 392
 			$result[2]=round($result[2]/$conf->global->MAIN_ROUNDING_RULE_TOT, 0)*$conf->global->MAIN_ROUNDING_RULE_TOT;
@@ -386,8 +419,7 @@  discard block
 block discarded – undo
386 419
 		$result[18] = price2num($result[2] * $multicurrency_tx, 'MT');
387 420
 		$result[19] = price2num($pu_devise, 'MU');
388 421
 		*/
389
-	}
390
-	else
422
+	} else
391 423
 	{
392 424
 		$result[16] = $result[0];
393 425
 		$result[17] = $result[1];
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/ldap.lib.php 3 patches
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -30,66 +30,66 @@  discard block
 block discarded – undo
30 30
  */
31 31
 function ldap_prepare_head()
32 32
 {
33
-	global $langs, $conf, $user;
34
-
35
-	$langs->load("ldap");
36
-
37
-	// Onglets
38
-	$head=array();
39
-	$h = 0;
40
-
41
-	$head[$h][0] = DOL_URL_ROOT."/admin/ldap.php";
42
-	$head[$h][1] = $langs->trans("LDAPGlobalParameters");
43
-	$head[$h][2] = 'ldap';
44
-	$h++;
45
-
46
-	if (! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
47
-	{
48
-		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php";
49
-		$head[$h][1] = $langs->trans("LDAPUsersSynchro");
50
-		$head[$h][2] = 'users';
51
-		$h++;
52
-	}
53
-
54
-	if (! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
55
-	{
56
-		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php";
57
-		$head[$h][1] = $langs->trans("LDAPGroupsSynchro");
58
-		$head[$h][2] = 'groups';
59
-		$h++;
60
-	}
61
-
62
-	if (! empty($conf->societe->enabled) && ! empty($conf->global->LDAP_CONTACT_ACTIVE))
63
-	{
64
-		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php";
65
-		$head[$h][1] = $langs->trans("LDAPContactsSynchro");
66
-		$head[$h][2] = 'contacts';
67
-		$h++;
68
-	}
69
-
70
-	if (! empty($conf->adherent->enabled) && ! empty($conf->global->LDAP_MEMBER_ACTIVE))
71
-	{
72
-		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php";
73
-		$head[$h][1] = $langs->trans("LDAPMembersSynchro");
74
-		$head[$h][2] = 'members';
75
-		$h++;
76
-	}
77
-
78
-	if (! empty($conf->adherent->enabled) && ! empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
79
-	{
80
-		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php";
81
-		$head[$h][1] = $langs->trans("LDAPMembersTypesSynchro");
82
-		$head[$h][2] = 'memberstypes';
83
-		$h++;
84
-	}
85
-
86
-	// Show more tabs from modules
87
-	// Entries must be declared in modules descriptor with line
88
-	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
89
-	// $this->tabs = array('entity:-tabname);   												to remove a tab
90
-	complete_head_from_modules($conf,$langs,'',$head,$h,'ldap');
91
-
92
-	return $head;
33
+    global $langs, $conf, $user;
34
+
35
+    $langs->load("ldap");
36
+
37
+    // Onglets
38
+    $head=array();
39
+    $h = 0;
40
+
41
+    $head[$h][0] = DOL_URL_ROOT."/admin/ldap.php";
42
+    $head[$h][1] = $langs->trans("LDAPGlobalParameters");
43
+    $head[$h][2] = 'ldap';
44
+    $h++;
45
+
46
+    if (! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
47
+    {
48
+        $head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php";
49
+        $head[$h][1] = $langs->trans("LDAPUsersSynchro");
50
+        $head[$h][2] = 'users';
51
+        $h++;
52
+    }
53
+
54
+    if (! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
55
+    {
56
+        $head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php";
57
+        $head[$h][1] = $langs->trans("LDAPGroupsSynchro");
58
+        $head[$h][2] = 'groups';
59
+        $h++;
60
+    }
61
+
62
+    if (! empty($conf->societe->enabled) && ! empty($conf->global->LDAP_CONTACT_ACTIVE))
63
+    {
64
+        $head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php";
65
+        $head[$h][1] = $langs->trans("LDAPContactsSynchro");
66
+        $head[$h][2] = 'contacts';
67
+        $h++;
68
+    }
69
+
70
+    if (! empty($conf->adherent->enabled) && ! empty($conf->global->LDAP_MEMBER_ACTIVE))
71
+    {
72
+        $head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php";
73
+        $head[$h][1] = $langs->trans("LDAPMembersSynchro");
74
+        $head[$h][2] = 'members';
75
+        $h++;
76
+    }
77
+
78
+    if (! empty($conf->adherent->enabled) && ! empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
79
+    {
80
+        $head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php";
81
+        $head[$h][1] = $langs->trans("LDAPMembersTypesSynchro");
82
+        $head[$h][2] = 'memberstypes';
83
+        $h++;
84
+    }
85
+
86
+    // Show more tabs from modules
87
+    // Entries must be declared in modules descriptor with line
88
+    // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
89
+    // $this->tabs = array('entity:-tabname);   												to remove a tab
90
+    complete_head_from_modules($conf,$langs,'',$head,$h,'ldap');
91
+
92
+    return $head;
93 93
 }
94 94
 
95 95
 
@@ -105,28 +105,28 @@  discard block
 block discarded – undo
105 105
  */
106 106
 function show_ldap_test_button($butlabel,$testlabel,$key,$dn,$objectclass)
107 107
 {
108
-	global $langs, $conf, $user;
109
-	//print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass;
110
-
111
-	print '<br>';
112
-	if (! function_exists("ldap_connect"))
113
-	{
114
-		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPFunctionsNotAvailableOnPHP').'">'.$butlabel.'</a>';
115
-	}
116
-	else if (empty($conf->global->LDAP_SERVER_HOST))
117
-	{
118
-		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPSetupNotComplete').'">'.$butlabel.'</a>';
119
-	}
120
-	else if (empty($key) || empty($dn) || empty($objectclass))
121
-	{
122
-		$langs->load("errors");
123
-		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('ErrorLDAPSetupNotComplete').'">'.$butlabel.'</a>';
124
-	}
125
-	else
126
-	{
127
-		print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action='.$testlabel.'">'.$butlabel.'</a>';
128
-	}
129
-	print '<br><br>';
108
+    global $langs, $conf, $user;
109
+    //print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass;
110
+
111
+    print '<br>';
112
+    if (! function_exists("ldap_connect"))
113
+    {
114
+        print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPFunctionsNotAvailableOnPHP').'">'.$butlabel.'</a>';
115
+    }
116
+    else if (empty($conf->global->LDAP_SERVER_HOST))
117
+    {
118
+        print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPSetupNotComplete').'">'.$butlabel.'</a>';
119
+    }
120
+    else if (empty($key) || empty($dn) || empty($objectclass))
121
+    {
122
+        $langs->load("errors");
123
+        print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('ErrorLDAPSetupNotComplete').'">'.$butlabel.'</a>';
124
+    }
125
+    else
126
+    {
127
+        print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action='.$testlabel.'">'.$butlabel.'</a>';
128
+    }
129
+    print '<br><br>';
130 130
 }
131 131
 
132 132
 
@@ -143,45 +143,45 @@  discard block
 block discarded – undo
143 143
  */
144 144
 function show_ldap_content($result,$level,$count,$var,$hide=0,$subcount=0)
145 145
 {
146
-	global $bc, $conf;
147
-
148
-	$count--;
149
-	if ($count == 0) return -1;	// To stop loop
150
-	if (! is_array($result)) return -1;
151
-
152
-	foreach($result as $key => $val)
153
-	{
154
-		if ("$key" == "objectclass") continue;
155
-		if ("$key" == "count") continue;
156
-		if ("$key" == "dn") continue;
157
-		if ("$val" == "objectclass") continue;
158
-
159
-		$lastkey[$level]=$key;
160
-
161
-		if (is_array($val))
162
-		{
163
-			$hide=0;
164
-			if (! is_numeric($key))
165
-			{
166
-
167
-				print '<tr '.$bc[$var].' valign="top">';
168
-				print '<td>';
169
-				print $key;
170
-				print '</td><td>';
171
-				if (strtolower($key) == 'userpassword') $hide=1;
172
-			}
173
-			show_ldap_content($val,$level+1,$count,$var,$hide,$val["count"]);
174
-		}
175
-		else if ($subcount)
176
-		{
177
-			$subcount--;
178
-			$newstring=dol_htmlentitiesbr($val);
179
-			if ($hide) print preg_replace('/./i','*',$newstring);
180
-			else print $newstring;
181
-			print '<br>';
182
-		}
183
-		if ("$val" != $lastkey[$level] && !$subcount) print '</td></tr>';
184
-	}
185
-	return 1;
146
+    global $bc, $conf;
147
+
148
+    $count--;
149
+    if ($count == 0) return -1;	// To stop loop
150
+    if (! is_array($result)) return -1;
151
+
152
+    foreach($result as $key => $val)
153
+    {
154
+        if ("$key" == "objectclass") continue;
155
+        if ("$key" == "count") continue;
156
+        if ("$key" == "dn") continue;
157
+        if ("$val" == "objectclass") continue;
158
+
159
+        $lastkey[$level]=$key;
160
+
161
+        if (is_array($val))
162
+        {
163
+            $hide=0;
164
+            if (! is_numeric($key))
165
+            {
166
+
167
+                print '<tr '.$bc[$var].' valign="top">';
168
+                print '<td>';
169
+                print $key;
170
+                print '</td><td>';
171
+                if (strtolower($key) == 'userpassword') $hide=1;
172
+            }
173
+            show_ldap_content($val,$level+1,$count,$var,$hide,$val["count"]);
174
+        }
175
+        else if ($subcount)
176
+        {
177
+            $subcount--;
178
+            $newstring=dol_htmlentitiesbr($val);
179
+            if ($hide) print preg_replace('/./i','*',$newstring);
180
+            else print $newstring;
181
+            print '<br>';
182
+        }
183
+        if ("$val" != $lastkey[$level] && !$subcount) print '</td></tr>';
184
+    }
185
+    return 1;
186 186
 }
187 187
 
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	$langs->load("ldap");
36 36
 
37 37
 	// Onglets
38
-	$head=array();
38
+	$head = array();
39 39
 	$h = 0;
40 40
 
41 41
 	$head[$h][0] = DOL_URL_ROOT."/admin/ldap.php";
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 	$head[$h][2] = 'ldap';
44 44
 	$h++;
45 45
 
46
-	if (! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
46
+	if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE))
47 47
 	{
48 48
 		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php";
49 49
 		$head[$h][1] = $langs->trans("LDAPUsersSynchro");
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		$h++;
52 52
 	}
53 53
 
54
-	if (! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
54
+	if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE))
55 55
 	{
56 56
 		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php";
57 57
 		$head[$h][1] = $langs->trans("LDAPGroupsSynchro");
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 		$h++;
60 60
 	}
61 61
 
62
-	if (! empty($conf->societe->enabled) && ! empty($conf->global->LDAP_CONTACT_ACTIVE))
62
+	if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE))
63 63
 	{
64 64
 		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php";
65 65
 		$head[$h][1] = $langs->trans("LDAPContactsSynchro");
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 		$h++;
68 68
 	}
69 69
 
70
-	if (! empty($conf->adherent->enabled) && ! empty($conf->global->LDAP_MEMBER_ACTIVE))
70
+	if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE))
71 71
 	{
72 72
 		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php";
73 73
 		$head[$h][1] = $langs->trans("LDAPMembersSynchro");
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 		$h++;
76 76
 	}
77 77
 
78
-	if (! empty($conf->adherent->enabled) && ! empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
78
+	if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE))
79 79
 	{
80 80
 		$head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php";
81 81
 		$head[$h][1] = $langs->trans("LDAPMembersTypesSynchro");
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	// Entries must be declared in modules descriptor with line
88 88
 	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
89 89
 	// $this->tabs = array('entity:-tabname);   												to remove a tab
90
-	complete_head_from_modules($conf,$langs,'',$head,$h,'ldap');
90
+	complete_head_from_modules($conf, $langs, '', $head, $h, 'ldap');
91 91
 
92 92
 	return $head;
93 93
 }
@@ -103,13 +103,13 @@  discard block
 block discarded – undo
103 103
  *  @param	string	$objectclass	Class
104 104
  *  @return	void
105 105
  */
106
-function show_ldap_test_button($butlabel,$testlabel,$key,$dn,$objectclass)
106
+function show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass)
107 107
 {
108 108
 	global $langs, $conf, $user;
109 109
 	//print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass;
110 110
 
111 111
 	print '<br>';
112
-	if (! function_exists("ldap_connect"))
112
+	if (!function_exists("ldap_connect"))
113 113
 	{
114 114
 		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPFunctionsNotAvailableOnPHP').'">'.$butlabel.'</a>';
115 115
 	}
@@ -141,42 +141,42 @@  discard block
 block discarded – undo
141 141
  * @param   int		$subcount	Subcount
142 142
  * @return  int
143 143
  */
144
-function show_ldap_content($result,$level,$count,$var,$hide=0,$subcount=0)
144
+function show_ldap_content($result, $level, $count, $var, $hide = 0, $subcount = 0)
145 145
 {
146 146
 	global $bc, $conf;
147 147
 
148 148
 	$count--;
149
-	if ($count == 0) return -1;	// To stop loop
150
-	if (! is_array($result)) return -1;
149
+	if ($count == 0) return -1; // To stop loop
150
+	if (!is_array($result)) return -1;
151 151
 
152
-	foreach($result as $key => $val)
152
+	foreach ($result as $key => $val)
153 153
 	{
154 154
 		if ("$key" == "objectclass") continue;
155 155
 		if ("$key" == "count") continue;
156 156
 		if ("$key" == "dn") continue;
157 157
 		if ("$val" == "objectclass") continue;
158 158
 
159
-		$lastkey[$level]=$key;
159
+		$lastkey[$level] = $key;
160 160
 
161 161
 		if (is_array($val))
162 162
 		{
163
-			$hide=0;
164
-			if (! is_numeric($key))
163
+			$hide = 0;
164
+			if (!is_numeric($key))
165 165
 			{
166 166
 
167 167
 				print '<tr '.$bc[$var].' valign="top">';
168 168
 				print '<td>';
169 169
 				print $key;
170 170
 				print '</td><td>';
171
-				if (strtolower($key) == 'userpassword') $hide=1;
171
+				if (strtolower($key) == 'userpassword') $hide = 1;
172 172
 			}
173
-			show_ldap_content($val,$level+1,$count,$var,$hide,$val["count"]);
173
+			show_ldap_content($val, $level + 1, $count, $var, $hide, $val["count"]);
174 174
 		}
175 175
 		else if ($subcount)
176 176
 		{
177 177
 			$subcount--;
178
-			$newstring=dol_htmlentitiesbr($val);
179
-			if ($hide) print preg_replace('/./i','*',$newstring);
178
+			$newstring = dol_htmlentitiesbr($val);
179
+			if ($hide) print preg_replace('/./i', '*', $newstring);
180 180
 			else print $newstring;
181 181
 			print '<br>';
182 182
 		}
Please login to merge, or discard this patch.
Braces   +34 added lines, -18 removed lines patch added patch discarded remove patch
@@ -112,17 +112,14 @@  discard block
 block discarded – undo
112 112
 	if (! function_exists("ldap_connect"))
113 113
 	{
114 114
 		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPFunctionsNotAvailableOnPHP').'">'.$butlabel.'</a>';
115
-	}
116
-	else if (empty($conf->global->LDAP_SERVER_HOST))
115
+	} else if (empty($conf->global->LDAP_SERVER_HOST))
117 116
 	{
118 117
 		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('LDAPSetupNotComplete').'">'.$butlabel.'</a>';
119
-	}
120
-	else if (empty($key) || empty($dn) || empty($objectclass))
118
+	} else if (empty($key) || empty($dn) || empty($objectclass))
121 119
 	{
122 120
 		$langs->load("errors");
123 121
 		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans('ErrorLDAPSetupNotComplete').'">'.$butlabel.'</a>';
124
-	}
125
-	else
122
+	} else
126 123
 	{
127 124
 		print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action='.$testlabel.'">'.$butlabel.'</a>';
128 125
 	}
@@ -146,15 +143,28 @@  discard block
 block discarded – undo
146 143
 	global $bc, $conf;
147 144
 
148 145
 	$count--;
149
-	if ($count == 0) return -1;	// To stop loop
150
-	if (! is_array($result)) return -1;
146
+	if ($count == 0) {
147
+	    return -1;
148
+	}
149
+	// To stop loop
150
+	if (! is_array($result)) {
151
+	    return -1;
152
+	}
151 153
 
152 154
 	foreach($result as $key => $val)
153 155
 	{
154
-		if ("$key" == "objectclass") continue;
155
-		if ("$key" == "count") continue;
156
-		if ("$key" == "dn") continue;
157
-		if ("$val" == "objectclass") continue;
156
+		if ("$key" == "objectclass") {
157
+		    continue;
158
+		}
159
+		if ("$key" == "count") {
160
+		    continue;
161
+		}
162
+		if ("$key" == "dn") {
163
+		    continue;
164
+		}
165
+		if ("$val" == "objectclass") {
166
+		    continue;
167
+		}
158 168
 
159 169
 		$lastkey[$level]=$key;
160 170
 
@@ -168,19 +178,25 @@  discard block
 block discarded – undo
168 178
 				print '<td>';
169 179
 				print $key;
170 180
 				print '</td><td>';
171
-				if (strtolower($key) == 'userpassword') $hide=1;
181
+				if (strtolower($key) == 'userpassword') {
182
+				    $hide=1;
183
+				}
172 184
 			}
173 185
 			show_ldap_content($val,$level+1,$count,$var,$hide,$val["count"]);
174
-		}
175
-		else if ($subcount)
186
+		} else if ($subcount)
176 187
 		{
177 188
 			$subcount--;
178 189
 			$newstring=dol_htmlentitiesbr($val);
179
-			if ($hide) print preg_replace('/./i','*',$newstring);
180
-			else print $newstring;
190
+			if ($hide) {
191
+			    print preg_replace('/./i','*',$newstring);
192
+			} else {
193
+			    print $newstring;
194
+			}
181 195
 			print '<br>';
182 196
 		}
183
-		if ("$val" != $lastkey[$level] && !$subcount) print '</td></tr>';
197
+		if ("$val" != $lastkey[$level] && !$subcount) {
198
+		    print '</td></tr>';
199
+		}
184 200
 	}
185 201
 	return 1;
186 202
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/security.lib.php 3 patches
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -36,29 +36,29 @@  discard block
 block discarded – undo
36 36
  */
37 37
 function dol_encode($chain, $key='1')
38 38
 {
39
-	if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
40
-	{
41
-		$output_tab=array();
42
-		$strlength=dol_strlen($chain);
43
-		for ($i=0; $i < $strlength; $i++)
44
-		{
45
-			$output_tab[$i] = chr(ord(substr($chain,$i,1))+17);
46
-		}
47
-		$chain = implode("",$output_tab);
48
-	}
49
-	elseif ($key)
50
-	{
51
-		$result='';
52
-		$strlength=dol_strlen($chain);
53
-		for ($i=0; $i < $strlength; $i++)
54
-		{
55
-			$keychar = substr($key, ($i % strlen($key))-1, 1);
56
-			$result.= chr(ord(substr($chain,$i,1))+(ord($keychar)-65));
57
-		}
58
-		$chain=$result;
59
-	}
60
-
61
-	return base64_encode($chain);
39
+    if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
40
+    {
41
+        $output_tab=array();
42
+        $strlength=dol_strlen($chain);
43
+        for ($i=0; $i < $strlength; $i++)
44
+        {
45
+            $output_tab[$i] = chr(ord(substr($chain,$i,1))+17);
46
+        }
47
+        $chain = implode("",$output_tab);
48
+    }
49
+    elseif ($key)
50
+    {
51
+        $result='';
52
+        $strlength=dol_strlen($chain);
53
+        for ($i=0; $i < $strlength; $i++)
54
+        {
55
+            $keychar = substr($key, ($i % strlen($key))-1, 1);
56
+            $result.= chr(ord(substr($chain,$i,1))+(ord($keychar)-65));
57
+        }
58
+        $chain=$result;
59
+    }
60
+
61
+    return base64_encode($chain);
62 62
 }
63 63
 
64 64
 /**
@@ -72,32 +72,32 @@  discard block
 block discarded – undo
72 72
  */
73 73
 function dol_decode($chain, $key='1')
74 74
 {
75
-	$chain = base64_decode($chain);
76
-
77
-	if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
78
-	{
79
-		$output_tab=array();
80
-		$strlength=dol_strlen($chain);
81
-		for ($i=0; $i < $strlength;$i++)
82
-		{
83
-			$output_tab[$i] = chr(ord(substr($chain,$i,1))-17);
84
-		}
85
-
86
-		$chain = implode("",$output_tab);
87
-	}
88
-	elseif ($key)
89
-	{
90
-		$result='';
91
-		$strlength=dol_strlen($chain);
92
-		for ($i=0; $i < $strlength; $i++)
93
-		{
94
-			$keychar = substr($key, ($i % strlen($key))-1, 1);
95
-			$result.= chr(ord(substr($chain, $i, 1))-(ord($keychar)-65));
96
-		}
97
-		$chain=$result;
98
-	}
99
-
100
-	return $chain;
75
+    $chain = base64_decode($chain);
76
+
77
+    if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
78
+    {
79
+        $output_tab=array();
80
+        $strlength=dol_strlen($chain);
81
+        for ($i=0; $i < $strlength;$i++)
82
+        {
83
+            $output_tab[$i] = chr(ord(substr($chain,$i,1))-17);
84
+        }
85
+
86
+        $chain = implode("",$output_tab);
87
+    }
88
+    elseif ($key)
89
+    {
90
+        $result='';
91
+        $strlength=dol_strlen($chain);
92
+        for ($i=0; $i < $strlength; $i++)
93
+        {
94
+            $keychar = substr($key, ($i % strlen($key))-1, 1);
95
+            $result.= chr(ord(substr($chain, $i, 1))-(ord($keychar)-65));
96
+        }
97
+        $chain=$result;
98
+    }
99
+
100
+    return $chain;
101 101
 }
102 102
 
103 103
 
@@ -113,27 +113,27 @@  discard block
 block discarded – undo
113 113
  */
114 114
 function dol_hash($chain, $type='0')
115 115
 {
116
-	global $conf;
117
-
118
-	// No need to add salt for password_hash
119
-	if (($type == '0' || $type == 'auto') && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash'))
120
-	{
121
-		return password_hash($chain, PASSWORD_DEFAULT);
122
-	}
123
-
124
-	// Salt value
125
-	if (! empty($conf->global->MAIN_SECURITY_SALT)) $chain=$conf->global->MAIN_SECURITY_SALT.$chain;
126
-
127
-	if ($type == '1' || $type == 'sha1') return sha1($chain);
128
-	else if ($type == '2' || $type == 'sha1md5') return sha1(md5($chain));
129
-	else if ($type == '3' || $type == 'md5') return md5($chain);
130
-	else if ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
131
-	else if ($type == '5') return hash('sha256',$chain);
132
-	else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain);
133
-	else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain));
134
-
135
-	// No particular encoding defined, use default
136
-	return md5($chain);
116
+    global $conf;
117
+
118
+    // No need to add salt for password_hash
119
+    if (($type == '0' || $type == 'auto') && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash'))
120
+    {
121
+        return password_hash($chain, PASSWORD_DEFAULT);
122
+    }
123
+
124
+    // Salt value
125
+    if (! empty($conf->global->MAIN_SECURITY_SALT)) $chain=$conf->global->MAIN_SECURITY_SALT.$chain;
126
+
127
+    if ($type == '1' || $type == 'sha1') return sha1($chain);
128
+    else if ($type == '2' || $type == 'sha1md5') return sha1(md5($chain));
129
+    else if ($type == '3' || $type == 'md5') return md5($chain);
130
+    else if ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
131
+    else if ($type == '5') return hash('sha256',$chain);
132
+    else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain);
133
+    else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain));
134
+
135
+    // No particular encoding defined, use default
136
+    return md5($chain);
137 137
 }
138 138
 
139 139
 /**
@@ -149,17 +149,17 @@  discard block
 block discarded – undo
149 149
  */
150 150
 function dol_verifyHash($chain, $hash, $type='0')
151 151
 {
152
-	global $conf;
152
+    global $conf;
153 153
 
154
-	if ($type == '0' && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
155
-		if ($hash[0] == '$') return password_verify($chain, $hash);
156
-		else if(strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5
157
-		else if(strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5
154
+    if ($type == '0' && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
155
+        if ($hash[0] == '$') return password_verify($chain, $hash);
156
+        else if(strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5
157
+        else if(strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5
158 158
 
159
-		return false;
160
-	}
159
+        return false;
160
+    }
161 161
 
162
-	return dol_hash($chain, $type) == $hash;
162
+    return dol_hash($chain, $type) == $hash;
163 163
 }
164 164
 
165 165
 
@@ -180,242 +180,242 @@  discard block
 block discarded – undo
180 180
  */
181 181
 function restrictedArea($user, $features, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0)
182 182
 {
183
-	global $db, $conf;
184
-	global $hookmanager;
185
-
186
-	//dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename,$feature2,$dbt_socfield,$dbt_select");
187
-	//print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
188
-	//print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
189
-	//print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
190
-
191
-	// Get more permissions checks from hooks
192
-	$parameters=array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select);
193
-	$reshook=$hookmanager->executeHooks('restrictedArea',$parameters);
194
-	if (! empty($hookmanager->resArray['result'])) return true;
195
-	if ($reshook > 0) return false;
196
-
197
-	if ($dbt_select != 'rowid' && $dbt_select != 'id') $objectid = "'".$objectid."'";
198
-
199
-	// Features/modules to check
200
-	$featuresarray = array($features);
201
-	if (preg_match('/&/', $features)) $featuresarray = explode("&", $features);
202
-	else if (preg_match('/\|/', $features)) $featuresarray = explode("|", $features);
203
-
204
-	// More subfeatures to check
205
-	if (! empty($feature2)) $feature2 = explode("|", $feature2);
206
-
207
-	// More parameters
208
-	$params = explode('&', $tableandshare);
209
-	$dbtablename=(! empty($params[0]) ? $params[0] : '');
210
-	$sharedelement=(! empty($params[1]) ? $params[1] : $dbtablename);
211
-
212
-	$listofmodules=explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL);
213
-
214
-	// Check read permission from module
215
-	$readok=1; $nbko=0;
216
-	foreach ($featuresarray as $feature)	// first we check nb of test ko
217
-	{
218
-		$featureforlistofmodule=$feature;
219
-		if ($featureforlistofmodule == 'produit') $featureforlistofmodule='product';
220
-		if (! empty($user->societe_id) && ! empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && ! in_array($featureforlistofmodule,$listofmodules))	// If limits on modules for external users, module must be into list of modules for external users
221
-		{
222
-			$readok=0; $nbko++;
223
-			continue;
224
-		}
225
-
226
-		if ($feature == 'societe')
227
-		{
228
-			if (! $user->rights->societe->lire && ! $user->rights->fournisseur->lire) { $readok=0; $nbko++; }
229
-		}
230
-		else if ($feature == 'contact')
231
-		{
232
-			if (! $user->rights->societe->contact->lire) { $readok=0; $nbko++; }
233
-		}
234
-		else if ($feature == 'produit|service')
235
-		{
236
-			if (! $user->rights->produit->lire && ! $user->rights->service->lire) { $readok=0; $nbko++; }
237
-		}
238
-		else if ($feature == 'prelevement')
239
-		{
240
-			if (! $user->rights->prelevement->bons->lire) { $readok=0; $nbko++; }
241
-		}
242
-		else if ($feature == 'cheque')
243
-		{
244
-			if (! $user->rights->banque->cheque) { $readok=0; $nbko++; }
245
-		}
246
-		else if ($feature == 'projet')
247
-		{
248
-			if (! $user->rights->projet->lire && ! $user->rights->projet->all->lire) { $readok=0; $nbko++; }
249
-		}
250
-		else if (! empty($feature2))	// This should be used for future changes
251
-		{
252
-			$tmpreadok=1;
253
-			foreach($feature2 as $subfeature)
254
-			{
255
-				if (! empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok=0; }
256
-				else if (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok=0; }
257
-				else { $tmpreadok=1; break; } // Break is to bypass second test if the first is ok
258
-			}
259
-			if (! $tmpreadok)	// We found a test on feature that is ko
260
-			{
261
-				$readok=0;	// All tests are ko (we manage here the and, the or will be managed later using $nbko).
262
-				$nbko++;
263
-			}
264
-		}
265
-		else if (! empty($feature) && ($feature!='user' && $feature!='usergroup'))		// This is for old permissions
266
-		{
267
-			if (empty($user->rights->$feature->lire)
268
-				&& empty($user->rights->$feature->read)
269
-				&& empty($user->rights->$feature->run)) { $readok=0; $nbko++; }
270
-		}
271
-	}
272
-
273
-	// If a or and at least one ok
274
-	if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok=1;
275
-
276
-	if (! $readok) accessforbidden();
277
-	//print "Read access is ok";
278
-
279
-	// Check write permission from module (we need to know write permission to create but also to delete drafts record)
280
-	$createok=1; $nbko=0;
281
-	if (GETPOST('action','aZ09')  == 'create' || ((GETPOST("action","aZ09")  == 'confirm_delete' && GETPOST("confirm","aZ09") == 'yes') || GETPOST("action","aZ09")  == 'delete'))
282
-	{
283
-		foreach ($featuresarray as $feature)
284
-		{
285
-			if ($feature == 'contact')
286
-			{
287
-				if (! $user->rights->societe->contact->creer) { $createok=0; $nbko++; }
288
-			}
289
-			else if ($feature == 'produit|service')
290
-			{
291
-				if (! $user->rights->produit->creer && ! $user->rights->service->creer) { $createok=0; $nbko++; }
292
-			}
293
-			else if ($feature == 'prelevement')
294
-			{
295
-				if (! $user->rights->prelevement->bons->creer) { $createok=0; $nbko++; }
296
-			}
297
-			else if ($feature == 'commande_fournisseur')
298
-			{
299
-				if (! $user->rights->fournisseur->commande->creer) { $createok=0; $nbko++; }
300
-			}
301
-			else if ($feature == 'banque')
302
-			{
303
-				if (! $user->rights->banque->modifier) { $createok=0; $nbko++; }
304
-			}
305
-			else if ($feature == 'cheque')
306
-			{
307
-				if (! $user->rights->banque->cheque) { $createok=0; $nbko++; }
308
-			}
309
-			else if (! empty($feature2))	// This should be used
310
-			{
311
-				foreach($feature2 as $subfeature)
312
-				{
313
-					if (empty($user->rights->$feature->$subfeature->creer)
314
-						&& empty($user->rights->$feature->$subfeature->write)
315
-						&& empty($user->rights->$feature->$subfeature->create)) { $createok=0; $nbko++; }
316
-						else { $createok=1; break; } // Break to bypass second test if the first is ok
317
-				}
318
-			}
319
-			else if (! empty($feature))		// This is for old permissions ('creer' or 'write')
320
-			{
321
-				//print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write;
322
-				if (empty($user->rights->$feature->creer)
323
-					&& empty($user->rights->$feature->write)
324
-					&& empty($user->rights->$feature->create)) { $createok=0; $nbko++; }
325
-			}
326
-		}
327
-
328
-		// If a or and at least one ok
329
-		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok=1;
330
-
331
-		if (GETPOST('action','aZ09') == 'create' && ! $createok) accessforbidden();
332
-		//print "Write access is ok";
333
-	}
334
-
335
-	// Check create user permission
336
-	$createuserok=1;
337
-	if (GETPOST('action','aZ09') == 'confirm_create_user' && GETPOST("confirm",'aZ09') == 'yes')
338
-	{
339
-		if (! $user->rights->user->user->creer) $createuserok=0;
340
-
341
-		if (! $createuserok) accessforbidden();
342
-		//print "Create user access is ok";
343
-	}
344
-
345
-	// Check delete permission from module
346
-	$deleteok=1; $nbko=0;
347
-	if ((GETPOST("action","aZ09")  == 'confirm_delete' && GETPOST("confirm","aZ09") == 'yes') || GETPOST("action","aZ09")  == 'delete')
348
-	{
349
-		foreach ($featuresarray as $feature)
350
-		{
351
-			if ($feature == 'contact')
352
-			{
353
-				if (! $user->rights->societe->contact->supprimer) $deleteok=0;
354
-			}
355
-			else if ($feature == 'produit|service')
356
-			{
357
-				if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) $deleteok=0;
358
-			}
359
-			else if ($feature == 'commande_fournisseur')
360
-			{
361
-				if (! $user->rights->fournisseur->commande->supprimer) $deleteok=0;
362
-			}
363
-			else if ($feature == 'banque')
364
-			{
365
-				if (! $user->rights->banque->modifier) $deleteok=0;
366
-			}
367
-			else if ($feature == 'cheque')
368
-			{
369
-				if (! $user->rights->banque->cheque) $deleteok=0;
370
-			}
371
-			else if ($feature == 'ecm')
372
-			{
373
-				if (! $user->rights->ecm->upload) $deleteok=0;
374
-			}
375
-			else if ($feature == 'ftp')
376
-			{
377
-				if (! $user->rights->ftp->write) $deleteok=0;
378
-			}else if ($feature == 'salaries')
379
-			{
380
-				if (! $user->rights->salaries->delete) $deleteok=0;
381
-			}
382
-			else if ($feature == 'salaries')
383
-			{
384
-				if (! $user->rights->salaries->delete) $deleteok=0;
385
-			}
386
-			else if (! empty($feature2))	// This should be used for permissions on 2 levels
387
-			{
388
-				foreach($feature2 as $subfeature)
389
-				{
390
-					if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok=0;
391
-					else { $deleteok=1; break; } // For bypass the second test if the first is ok
392
-				}
393
-			}
394
-			else if (! empty($feature))		// This is used for permissions on 1 level
395
-			{
396
-				//print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
397
-				if (empty($user->rights->$feature->supprimer)
398
-					&& empty($user->rights->$feature->delete)
399
-					&& empty($user->rights->$feature->run)) $deleteok=0;
400
-			}
401
-		}
402
-
403
-		// If a or and at least one ok
404
-		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok=1;
405
-
406
-		if (! $deleteok && ! ($isdraft && $createok)) accessforbidden();
407
-		//print "Delete access is ok";
408
-	}
409
-
410
-	// If we have a particular object to check permissions on, we check this object
411
-	// is linked to a company allowed to $user.
412
-	if (! empty($objectid) && $objectid > 0)
413
-	{
414
-		$ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select);
415
-		return $ok ? 1 : accessforbidden();
416
-	}
417
-
418
-	return 1;
183
+    global $db, $conf;
184
+    global $hookmanager;
185
+
186
+    //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename,$feature2,$dbt_socfield,$dbt_select");
187
+    //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
188
+    //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
189
+    //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
190
+
191
+    // Get more permissions checks from hooks
192
+    $parameters=array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select);
193
+    $reshook=$hookmanager->executeHooks('restrictedArea',$parameters);
194
+    if (! empty($hookmanager->resArray['result'])) return true;
195
+    if ($reshook > 0) return false;
196
+
197
+    if ($dbt_select != 'rowid' && $dbt_select != 'id') $objectid = "'".$objectid."'";
198
+
199
+    // Features/modules to check
200
+    $featuresarray = array($features);
201
+    if (preg_match('/&/', $features)) $featuresarray = explode("&", $features);
202
+    else if (preg_match('/\|/', $features)) $featuresarray = explode("|", $features);
203
+
204
+    // More subfeatures to check
205
+    if (! empty($feature2)) $feature2 = explode("|", $feature2);
206
+
207
+    // More parameters
208
+    $params = explode('&', $tableandshare);
209
+    $dbtablename=(! empty($params[0]) ? $params[0] : '');
210
+    $sharedelement=(! empty($params[1]) ? $params[1] : $dbtablename);
211
+
212
+    $listofmodules=explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL);
213
+
214
+    // Check read permission from module
215
+    $readok=1; $nbko=0;
216
+    foreach ($featuresarray as $feature)	// first we check nb of test ko
217
+    {
218
+        $featureforlistofmodule=$feature;
219
+        if ($featureforlistofmodule == 'produit') $featureforlistofmodule='product';
220
+        if (! empty($user->societe_id) && ! empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && ! in_array($featureforlistofmodule,$listofmodules))	// If limits on modules for external users, module must be into list of modules for external users
221
+        {
222
+            $readok=0; $nbko++;
223
+            continue;
224
+        }
225
+
226
+        if ($feature == 'societe')
227
+        {
228
+            if (! $user->rights->societe->lire && ! $user->rights->fournisseur->lire) { $readok=0; $nbko++; }
229
+        }
230
+        else if ($feature == 'contact')
231
+        {
232
+            if (! $user->rights->societe->contact->lire) { $readok=0; $nbko++; }
233
+        }
234
+        else if ($feature == 'produit|service')
235
+        {
236
+            if (! $user->rights->produit->lire && ! $user->rights->service->lire) { $readok=0; $nbko++; }
237
+        }
238
+        else if ($feature == 'prelevement')
239
+        {
240
+            if (! $user->rights->prelevement->bons->lire) { $readok=0; $nbko++; }
241
+        }
242
+        else if ($feature == 'cheque')
243
+        {
244
+            if (! $user->rights->banque->cheque) { $readok=0; $nbko++; }
245
+        }
246
+        else if ($feature == 'projet')
247
+        {
248
+            if (! $user->rights->projet->lire && ! $user->rights->projet->all->lire) { $readok=0; $nbko++; }
249
+        }
250
+        else if (! empty($feature2))	// This should be used for future changes
251
+        {
252
+            $tmpreadok=1;
253
+            foreach($feature2 as $subfeature)
254
+            {
255
+                if (! empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok=0; }
256
+                else if (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok=0; }
257
+                else { $tmpreadok=1; break; } // Break is to bypass second test if the first is ok
258
+            }
259
+            if (! $tmpreadok)	// We found a test on feature that is ko
260
+            {
261
+                $readok=0;	// All tests are ko (we manage here the and, the or will be managed later using $nbko).
262
+                $nbko++;
263
+            }
264
+        }
265
+        else if (! empty($feature) && ($feature!='user' && $feature!='usergroup'))		// This is for old permissions
266
+        {
267
+            if (empty($user->rights->$feature->lire)
268
+                && empty($user->rights->$feature->read)
269
+                && empty($user->rights->$feature->run)) { $readok=0; $nbko++; }
270
+        }
271
+    }
272
+
273
+    // If a or and at least one ok
274
+    if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok=1;
275
+
276
+    if (! $readok) accessforbidden();
277
+    //print "Read access is ok";
278
+
279
+    // Check write permission from module (we need to know write permission to create but also to delete drafts record)
280
+    $createok=1; $nbko=0;
281
+    if (GETPOST('action','aZ09')  == 'create' || ((GETPOST("action","aZ09")  == 'confirm_delete' && GETPOST("confirm","aZ09") == 'yes') || GETPOST("action","aZ09")  == 'delete'))
282
+    {
283
+        foreach ($featuresarray as $feature)
284
+        {
285
+            if ($feature == 'contact')
286
+            {
287
+                if (! $user->rights->societe->contact->creer) { $createok=0; $nbko++; }
288
+            }
289
+            else if ($feature == 'produit|service')
290
+            {
291
+                if (! $user->rights->produit->creer && ! $user->rights->service->creer) { $createok=0; $nbko++; }
292
+            }
293
+            else if ($feature == 'prelevement')
294
+            {
295
+                if (! $user->rights->prelevement->bons->creer) { $createok=0; $nbko++; }
296
+            }
297
+            else if ($feature == 'commande_fournisseur')
298
+            {
299
+                if (! $user->rights->fournisseur->commande->creer) { $createok=0; $nbko++; }
300
+            }
301
+            else if ($feature == 'banque')
302
+            {
303
+                if (! $user->rights->banque->modifier) { $createok=0; $nbko++; }
304
+            }
305
+            else if ($feature == 'cheque')
306
+            {
307
+                if (! $user->rights->banque->cheque) { $createok=0; $nbko++; }
308
+            }
309
+            else if (! empty($feature2))	// This should be used
310
+            {
311
+                foreach($feature2 as $subfeature)
312
+                {
313
+                    if (empty($user->rights->$feature->$subfeature->creer)
314
+                        && empty($user->rights->$feature->$subfeature->write)
315
+                        && empty($user->rights->$feature->$subfeature->create)) { $createok=0; $nbko++; }
316
+                        else { $createok=1; break; } // Break to bypass second test if the first is ok
317
+                }
318
+            }
319
+            else if (! empty($feature))		// This is for old permissions ('creer' or 'write')
320
+            {
321
+                //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write;
322
+                if (empty($user->rights->$feature->creer)
323
+                    && empty($user->rights->$feature->write)
324
+                    && empty($user->rights->$feature->create)) { $createok=0; $nbko++; }
325
+            }
326
+        }
327
+
328
+        // If a or and at least one ok
329
+        if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok=1;
330
+
331
+        if (GETPOST('action','aZ09') == 'create' && ! $createok) accessforbidden();
332
+        //print "Write access is ok";
333
+    }
334
+
335
+    // Check create user permission
336
+    $createuserok=1;
337
+    if (GETPOST('action','aZ09') == 'confirm_create_user' && GETPOST("confirm",'aZ09') == 'yes')
338
+    {
339
+        if (! $user->rights->user->user->creer) $createuserok=0;
340
+
341
+        if (! $createuserok) accessforbidden();
342
+        //print "Create user access is ok";
343
+    }
344
+
345
+    // Check delete permission from module
346
+    $deleteok=1; $nbko=0;
347
+    if ((GETPOST("action","aZ09")  == 'confirm_delete' && GETPOST("confirm","aZ09") == 'yes') || GETPOST("action","aZ09")  == 'delete')
348
+    {
349
+        foreach ($featuresarray as $feature)
350
+        {
351
+            if ($feature == 'contact')
352
+            {
353
+                if (! $user->rights->societe->contact->supprimer) $deleteok=0;
354
+            }
355
+            else if ($feature == 'produit|service')
356
+            {
357
+                if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) $deleteok=0;
358
+            }
359
+            else if ($feature == 'commande_fournisseur')
360
+            {
361
+                if (! $user->rights->fournisseur->commande->supprimer) $deleteok=0;
362
+            }
363
+            else if ($feature == 'banque')
364
+            {
365
+                if (! $user->rights->banque->modifier) $deleteok=0;
366
+            }
367
+            else if ($feature == 'cheque')
368
+            {
369
+                if (! $user->rights->banque->cheque) $deleteok=0;
370
+            }
371
+            else if ($feature == 'ecm')
372
+            {
373
+                if (! $user->rights->ecm->upload) $deleteok=0;
374
+            }
375
+            else if ($feature == 'ftp')
376
+            {
377
+                if (! $user->rights->ftp->write) $deleteok=0;
378
+            }else if ($feature == 'salaries')
379
+            {
380
+                if (! $user->rights->salaries->delete) $deleteok=0;
381
+            }
382
+            else if ($feature == 'salaries')
383
+            {
384
+                if (! $user->rights->salaries->delete) $deleteok=0;
385
+            }
386
+            else if (! empty($feature2))	// This should be used for permissions on 2 levels
387
+            {
388
+                foreach($feature2 as $subfeature)
389
+                {
390
+                    if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok=0;
391
+                    else { $deleteok=1; break; } // For bypass the second test if the first is ok
392
+                }
393
+            }
394
+            else if (! empty($feature))		// This is used for permissions on 1 level
395
+            {
396
+                //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
397
+                if (empty($user->rights->$feature->supprimer)
398
+                    && empty($user->rights->$feature->delete)
399
+                    && empty($user->rights->$feature->run)) $deleteok=0;
400
+            }
401
+        }
402
+
403
+        // If a or and at least one ok
404
+        if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok=1;
405
+
406
+        if (! $deleteok && ! ($isdraft && $createok)) accessforbidden();
407
+        //print "Delete access is ok";
408
+    }
409
+
410
+    // If we have a particular object to check permissions on, we check this object
411
+    // is linked to a company allowed to $user.
412
+    if (! empty($objectid) && $objectid > 0)
413
+    {
414
+        $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select);
415
+        return $ok ? 1 : accessforbidden();
416
+    }
417
+
418
+    return 1;
419 419
 }
420 420
 
421 421
 /**
@@ -434,216 +434,216 @@  discard block
 block discarded – undo
434 434
  */
435 435
 function checkUserAccessToObject($user, $featuresarray, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid')
436 436
 {
437
-	global $db, $conf;
438
-
439
-	// More parameters
440
-	$params = explode('&', $tableandshare);
441
-	$dbtablename=(! empty($params[0]) ? $params[0] : '');
442
-	$sharedelement=(! empty($params[1]) ? $params[1] : $dbtablename);
443
-
444
-	foreach ($featuresarray as $feature)
445
-	{
446
-		$sql='';
447
-
448
-		// For backward compatibility
449
-		if ($feature == 'member')  $feature='adherent';
450
-		if ($feature == 'project') $feature='projet';
451
-		if ($feature == 'task')    $feature='projet_task';
452
-
453
-		$check = array('adherent','banque','don','user','usergroup','product','produit','service','produit|service','categorie','resource'); // Test on entity only (Objects with no link to company)
454
-		$checksoc = array('societe');	 // Test for societe object
455
-		$checkother = array('contact','agenda');	 // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...).
456
-		$checkproject = array('projet','project'); // Test for project object
457
-		$checktask = array('projet_task');
458
-		$nocheck = array('barcode','stock');	// No test
459
-		$checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...).
460
-
461
-		// If dbtablename not defined, we use same name for table than module name
462
-		if (empty($dbtablename))
463
-		{
464
-			$dbtablename = $feature;
465
-			$sharedelement = (! empty($params[1]) ? $params[1] : $dbtablename);		// We change dbtablename, so we set sharedelement too.
466
-		}
467
-
468
-		// Check permission for object with entity
469
-		if (in_array($feature,$check))
470
-		{
471
-			$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
472
-			$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
473
-			if (($feature == 'user' || $feature == 'usergroup') && ! empty($conf->multicompany->enabled))
474
-			{
475
-				if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
476
-				{
477
-					if ($conf->entity == 1 && $user->admin && ! $user->entity)
478
-					{
479
-						$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
480
-						$sql.= " AND dbt.entity IS NOT NULL";
481
-					}
482
-					else
483
-					{
484
-						$sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
485
-						$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
486
-						$sql.= " AND (ug.fk_user = dbt.rowid";
487
-						$sql.= " AND ug.entity IN (".getEntity('user')."))";
488
-						$sql.= " OR dbt.entity = 0"; // Show always superadmin
489
-					}
490
-				}
491
-				else {
492
-					$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
493
-					$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
494
-				}
495
-			}
496
-			else
497
-			{
498
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
499
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
500
-			}
501
-		}
502
-		else if (in_array($feature,$checksoc))	// We check feature = checksoc
503
-		{
504
-			// If external user: Check permission for external users
505
-			if ($user->socid > 0)
506
-			{
507
-				if ($user->socid <> $objectid) return false;
508
-			}
509
-			// If internal user: Check permission for internal users that are restricted on their objects
510
-			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
511
-			{
512
-				$sql = "SELECT COUNT(sc.fk_soc) as nb";
513
-				$sql.= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
514
-				$sql.= ", ".MAIN_DB_PREFIX."societe as s)";
515
-				$sql.= " WHERE sc.fk_soc IN (".$objectid.")";
516
-				$sql.= " AND sc.fk_user = ".$user->id;
517
-				$sql.= " AND sc.fk_soc = s.rowid";
518
-				$sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
519
-			}
520
-			// If multicompany and internal users with all permissions, check user is in correct entity
521
-			else if (! empty($conf->multicompany->enabled))
522
-			{
523
-				$sql = "SELECT COUNT(s.rowid) as nb";
524
-				$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
525
-				$sql.= " WHERE s.rowid IN (".$objectid.")";
526
-				$sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
527
-			}
528
-		}
529
-		else if (in_array($feature,$checkother))	// Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
530
-		{
531
-			// If external user: Check permission for external users
532
-			if ($user->socid > 0)
533
-			{
534
-				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
535
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
536
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
537
-				$sql.= " AND dbt.fk_soc = ".$user->socid;
538
-			}
539
-			// If internal user: Check permission for internal users that are restricted on their objects
540
-			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
541
-			{
542
-				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
543
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
544
-				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
545
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
546
-				$sql.= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)";	// Contact not linked to a company or to a company of user
547
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
548
-			}
549
-			// If multicompany and internal users with all permissions, check user is in correct entity
550
-			else if (! empty($conf->multicompany->enabled))
551
-			{
552
-				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
553
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
554
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
555
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
556
-			}
557
-		}
558
-		else if (in_array($feature,$checkproject))
559
-		{
560
-			if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
561
-			{
562
-				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
563
-				$projectstatic=new Project($db);
564
-				$tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
565
-				$tmparray=explode(',',$tmps);
566
-				if (! in_array($objectid,$tmparray)) return false;
567
-			}
568
-			else
569
-			{
570
-				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
571
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
572
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
573
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
574
-			}
575
-		}
576
-		else if (in_array($feature,$checktask))
577
-		{
578
-			if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
579
-			{
580
-				$task = new Task($db);
581
-				$task->fetch($objectid);
582
-
583
-				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
584
-				$projectstatic=new Project($db);
585
-				$tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
586
-				$tmparray=explode(',',$tmps);
587
-				if (! in_array($task->fk_project,$tmparray)) return false;
588
-			}
589
-			else
590
-			{
591
-				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
592
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
593
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
594
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
595
-			}
596
-		}
597
-		else if (! in_array($feature,$nocheck))		// By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
598
-		{
599
-			// If external user: Check permission for external users
600
-			if ($user->socid > 0)
601
-			{
602
-				if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
603
-				$sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
604
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
605
-				$sql.= " WHERE dbt.rowid IN (".$objectid.")";
606
-				$sql.= " AND dbt.".$dbt_keyfield." = ".$user->socid;
607
-			}
608
-			// If internal user: Check permission for internal users that are restricted on their objects
609
-			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
610
-			{
611
-				if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
612
-				$sql = "SELECT COUNT(sc.fk_soc) as nb";
613
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
614
-				$sql.= ", ".MAIN_DB_PREFIX."societe as s";
615
-				$sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
616
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
617
-				$sql.= " AND sc.fk_soc = dbt.".$dbt_keyfield;
618
-				$sql.= " AND dbt.".$dbt_keyfield." = s.rowid";
619
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
620
-				$sql.= " AND sc.fk_user = ".$user->id;
621
-			}
622
-			// If multicompany and internal users with all permissions, check user is in correct entity
623
-			else if (! empty($conf->multicompany->enabled))
624
-			{
625
-				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
626
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
627
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
628
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
629
-			}
630
-		}
631
-
632
-		if ($sql)
633
-		{
634
-			$resql=$db->query($sql);
635
-			if ($resql)
636
-			{
637
-				$obj = $db->fetch_object($resql);
638
-				if (! $obj || $obj->nb < count(explode(',', $objectid))) return false;
639
-			}
640
-			else
641
-			{
642
-				return false;
643
-			}
644
-		}
645
-	}
646
-	return true;
437
+    global $db, $conf;
438
+
439
+    // More parameters
440
+    $params = explode('&', $tableandshare);
441
+    $dbtablename=(! empty($params[0]) ? $params[0] : '');
442
+    $sharedelement=(! empty($params[1]) ? $params[1] : $dbtablename);
443
+
444
+    foreach ($featuresarray as $feature)
445
+    {
446
+        $sql='';
447
+
448
+        // For backward compatibility
449
+        if ($feature == 'member')  $feature='adherent';
450
+        if ($feature == 'project') $feature='projet';
451
+        if ($feature == 'task')    $feature='projet_task';
452
+
453
+        $check = array('adherent','banque','don','user','usergroup','product','produit','service','produit|service','categorie','resource'); // Test on entity only (Objects with no link to company)
454
+        $checksoc = array('societe');	 // Test for societe object
455
+        $checkother = array('contact','agenda');	 // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...).
456
+        $checkproject = array('projet','project'); // Test for project object
457
+        $checktask = array('projet_task');
458
+        $nocheck = array('barcode','stock');	// No test
459
+        $checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...).
460
+
461
+        // If dbtablename not defined, we use same name for table than module name
462
+        if (empty($dbtablename))
463
+        {
464
+            $dbtablename = $feature;
465
+            $sharedelement = (! empty($params[1]) ? $params[1] : $dbtablename);		// We change dbtablename, so we set sharedelement too.
466
+        }
467
+
468
+        // Check permission for object with entity
469
+        if (in_array($feature,$check))
470
+        {
471
+            $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
472
+            $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
473
+            if (($feature == 'user' || $feature == 'usergroup') && ! empty($conf->multicompany->enabled))
474
+            {
475
+                if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
476
+                {
477
+                    if ($conf->entity == 1 && $user->admin && ! $user->entity)
478
+                    {
479
+                        $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
480
+                        $sql.= " AND dbt.entity IS NOT NULL";
481
+                    }
482
+                    else
483
+                    {
484
+                        $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
485
+                        $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
486
+                        $sql.= " AND (ug.fk_user = dbt.rowid";
487
+                        $sql.= " AND ug.entity IN (".getEntity('user')."))";
488
+                        $sql.= " OR dbt.entity = 0"; // Show always superadmin
489
+                    }
490
+                }
491
+                else {
492
+                    $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
493
+                    $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
494
+                }
495
+            }
496
+            else
497
+            {
498
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
499
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
500
+            }
501
+        }
502
+        else if (in_array($feature,$checksoc))	// We check feature = checksoc
503
+        {
504
+            // If external user: Check permission for external users
505
+            if ($user->socid > 0)
506
+            {
507
+                if ($user->socid <> $objectid) return false;
508
+            }
509
+            // If internal user: Check permission for internal users that are restricted on their objects
510
+            else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
511
+            {
512
+                $sql = "SELECT COUNT(sc.fk_soc) as nb";
513
+                $sql.= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
514
+                $sql.= ", ".MAIN_DB_PREFIX."societe as s)";
515
+                $sql.= " WHERE sc.fk_soc IN (".$objectid.")";
516
+                $sql.= " AND sc.fk_user = ".$user->id;
517
+                $sql.= " AND sc.fk_soc = s.rowid";
518
+                $sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
519
+            }
520
+            // If multicompany and internal users with all permissions, check user is in correct entity
521
+            else if (! empty($conf->multicompany->enabled))
522
+            {
523
+                $sql = "SELECT COUNT(s.rowid) as nb";
524
+                $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
525
+                $sql.= " WHERE s.rowid IN (".$objectid.")";
526
+                $sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
527
+            }
528
+        }
529
+        else if (in_array($feature,$checkother))	// Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
530
+        {
531
+            // If external user: Check permission for external users
532
+            if ($user->socid > 0)
533
+            {
534
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
535
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
536
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
537
+                $sql.= " AND dbt.fk_soc = ".$user->socid;
538
+            }
539
+            // If internal user: Check permission for internal users that are restricted on their objects
540
+            else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
541
+            {
542
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
543
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
544
+                $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
545
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
546
+                $sql.= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)";	// Contact not linked to a company or to a company of user
547
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
548
+            }
549
+            // If multicompany and internal users with all permissions, check user is in correct entity
550
+            else if (! empty($conf->multicompany->enabled))
551
+            {
552
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
553
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
554
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
555
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
556
+            }
557
+        }
558
+        else if (in_array($feature,$checkproject))
559
+        {
560
+            if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
561
+            {
562
+                include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
563
+                $projectstatic=new Project($db);
564
+                $tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
565
+                $tmparray=explode(',',$tmps);
566
+                if (! in_array($objectid,$tmparray)) return false;
567
+            }
568
+            else
569
+            {
570
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
571
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
572
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
573
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
574
+            }
575
+        }
576
+        else if (in_array($feature,$checktask))
577
+        {
578
+            if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
579
+            {
580
+                $task = new Task($db);
581
+                $task->fetch($objectid);
582
+
583
+                include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
584
+                $projectstatic=new Project($db);
585
+                $tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
586
+                $tmparray=explode(',',$tmps);
587
+                if (! in_array($task->fk_project,$tmparray)) return false;
588
+            }
589
+            else
590
+            {
591
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
592
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
593
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
594
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
595
+            }
596
+        }
597
+        else if (! in_array($feature,$nocheck))		// By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
598
+        {
599
+            // If external user: Check permission for external users
600
+            if ($user->socid > 0)
601
+            {
602
+                if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
603
+                $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
604
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
605
+                $sql.= " WHERE dbt.rowid IN (".$objectid.")";
606
+                $sql.= " AND dbt.".$dbt_keyfield." = ".$user->socid;
607
+            }
608
+            // If internal user: Check permission for internal users that are restricted on their objects
609
+            else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
610
+            {
611
+                if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
612
+                $sql = "SELECT COUNT(sc.fk_soc) as nb";
613
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
614
+                $sql.= ", ".MAIN_DB_PREFIX."societe as s";
615
+                $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
616
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
617
+                $sql.= " AND sc.fk_soc = dbt.".$dbt_keyfield;
618
+                $sql.= " AND dbt.".$dbt_keyfield." = s.rowid";
619
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
620
+                $sql.= " AND sc.fk_user = ".$user->id;
621
+            }
622
+            // If multicompany and internal users with all permissions, check user is in correct entity
623
+            else if (! empty($conf->multicompany->enabled))
624
+            {
625
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
626
+                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
627
+                $sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
628
+                $sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
629
+            }
630
+        }
631
+
632
+        if ($sql)
633
+        {
634
+            $resql=$db->query($sql);
635
+            if ($resql)
636
+            {
637
+                $obj = $db->fetch_object($resql);
638
+                if (! $obj || $obj->nb < count(explode(',', $objectid))) return false;
639
+            }
640
+            else
641
+            {
642
+                return false;
643
+            }
644
+        }
645
+    }
646
+    return true;
647 647
 }
648 648
 
649 649
 /**
@@ -666,30 +666,30 @@  discard block
 block discarded – undo
666 666
         $langs->setDefaultLang();
667 667
     }
668 668
 
669
-	$langs->load("errors");
670
-
671
-	if ($printheader)
672
-	{
673
-		if (function_exists("llxHeader")) llxHeader('');
674
-		else if (function_exists("llxHeaderVierge")) llxHeaderVierge('');
675
-	}
676
-	print '<div class="error">';
677
-	if (! $message) print $langs->trans("ErrorForbidden");
678
-	else print $message;
679
-	print '</div>';
680
-	print '<br>';
681
-	if (empty($showonlymessage))
682
-	{
683
-		if ($user->login)
684
-		{
685
-			print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
686
-			print $langs->trans("ErrorForbidden2",$langs->trans("Home"),$langs->trans("Users"));
687
-		}
688
-		else
689
-		{
690
-			print $langs->trans("ErrorForbidden3");
691
-		}
692
-	}
693
-	if ($printfooter && function_exists("llxFooter")) llxFooter();
694
-	exit(0);
669
+    $langs->load("errors");
670
+
671
+    if ($printheader)
672
+    {
673
+        if (function_exists("llxHeader")) llxHeader('');
674
+        else if (function_exists("llxHeaderVierge")) llxHeaderVierge('');
675
+    }
676
+    print '<div class="error">';
677
+    if (! $message) print $langs->trans("ErrorForbidden");
678
+    else print $message;
679
+    print '</div>';
680
+    print '<br>';
681
+    if (empty($showonlymessage))
682
+    {
683
+        if ($user->login)
684
+        {
685
+            print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
686
+            print $langs->trans("ErrorForbidden2",$langs->trans("Home"),$langs->trans("Users"));
687
+        }
688
+        else
689
+        {
690
+            print $langs->trans("ErrorForbidden3");
691
+        }
692
+    }
693
+    if ($printfooter && function_exists("llxFooter")) llxFooter();
694
+    exit(0);
695 695
 }
Please login to merge, or discard this patch.
Spacing   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -34,28 +34,28 @@  discard block
 block discarded – undo
34 34
  *	@return  string					encoded string
35 35
  *  @see dol_decode
36 36
  */
37
-function dol_encode($chain, $key='1')
37
+function dol_encode($chain, $key = '1')
38 38
 {
39 39
 	if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
40 40
 	{
41
-		$output_tab=array();
42
-		$strlength=dol_strlen($chain);
43
-		for ($i=0; $i < $strlength; $i++)
41
+		$output_tab = array();
42
+		$strlength = dol_strlen($chain);
43
+		for ($i = 0; $i < $strlength; $i++)
44 44
 		{
45
-			$output_tab[$i] = chr(ord(substr($chain,$i,1))+17);
45
+			$output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17);
46 46
 		}
47
-		$chain = implode("",$output_tab);
47
+		$chain = implode("", $output_tab);
48 48
 	}
49 49
 	elseif ($key)
50 50
 	{
51
-		$result='';
52
-		$strlength=dol_strlen($chain);
53
-		for ($i=0; $i < $strlength; $i++)
51
+		$result = '';
52
+		$strlength = dol_strlen($chain);
53
+		for ($i = 0; $i < $strlength; $i++)
54 54
 		{
55
-			$keychar = substr($key, ($i % strlen($key))-1, 1);
56
-			$result.= chr(ord(substr($chain,$i,1))+(ord($keychar)-65));
55
+			$keychar = substr($key, ($i % strlen($key)) - 1, 1);
56
+			$result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65));
57 57
 		}
58
-		$chain=$result;
58
+		$chain = $result;
59 59
 	}
60 60
 
61 61
 	return base64_encode($chain);
@@ -70,31 +70,31 @@  discard block
 block discarded – undo
70 70
  *	@return  string					decoded string
71 71
  *  @see dol_encode
72 72
  */
73
-function dol_decode($chain, $key='1')
73
+function dol_decode($chain, $key = '1')
74 74
 {
75 75
 	$chain = base64_decode($chain);
76 76
 
77 77
 	if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
78 78
 	{
79
-		$output_tab=array();
80
-		$strlength=dol_strlen($chain);
81
-		for ($i=0; $i < $strlength;$i++)
79
+		$output_tab = array();
80
+		$strlength = dol_strlen($chain);
81
+		for ($i = 0; $i < $strlength; $i++)
82 82
 		{
83
-			$output_tab[$i] = chr(ord(substr($chain,$i,1))-17);
83
+			$output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17);
84 84
 		}
85 85
 
86
-		$chain = implode("",$output_tab);
86
+		$chain = implode("", $output_tab);
87 87
 	}
88 88
 	elseif ($key)
89 89
 	{
90
-		$result='';
91
-		$strlength=dol_strlen($chain);
92
-		for ($i=0; $i < $strlength; $i++)
90
+		$result = '';
91
+		$strlength = dol_strlen($chain);
92
+		for ($i = 0; $i < $strlength; $i++)
93 93
 		{
94
-			$keychar = substr($key, ($i % strlen($key))-1, 1);
95
-			$result.= chr(ord(substr($chain, $i, 1))-(ord($keychar)-65));
94
+			$keychar = substr($key, ($i % strlen($key)) - 1, 1);
95
+			$result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65));
96 96
 		}
97
-		$chain=$result;
97
+		$chain = $result;
98 98
 	}
99 99
 
100 100
 	return $chain;
@@ -111,26 +111,26 @@  discard block
 block discarded – undo
111 111
  * 	@return		string					Hash of string
112 112
  *  @getRandomPassword
113 113
  */
114
-function dol_hash($chain, $type='0')
114
+function dol_hash($chain, $type = '0')
115 115
 {
116 116
 	global $conf;
117 117
 
118 118
 	// No need to add salt for password_hash
119
-	if (($type == '0' || $type == 'auto') && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash'))
119
+	if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash'))
120 120
 	{
121 121
 		return password_hash($chain, PASSWORD_DEFAULT);
122 122
 	}
123 123
 
124 124
 	// Salt value
125
-	if (! empty($conf->global->MAIN_SECURITY_SALT)) $chain=$conf->global->MAIN_SECURITY_SALT.$chain;
125
+	if (!empty($conf->global->MAIN_SECURITY_SALT)) $chain = $conf->global->MAIN_SECURITY_SALT.$chain;
126 126
 
127 127
 	if ($type == '1' || $type == 'sha1') return sha1($chain);
128 128
 	else if ($type == '2' || $type == 'sha1md5') return sha1(md5($chain));
129 129
 	else if ($type == '3' || $type == 'md5') return md5($chain);
130
-	else if ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
131
-	else if ($type == '5') return hash('sha256',$chain);
132
-	else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain);
133
-	else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain));
130
+	else if ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
131
+	else if ($type == '5') return hash('sha256', $chain);
132
+	else if (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain);
133
+	else if (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain));
134 134
 
135 135
 	// No particular encoding defined, use default
136 136
 	return md5($chain);
@@ -147,14 +147,14 @@  discard block
 block discarded – undo
147 147
  * 	@param		string		$type		Type of hash ('0':auto, '1':sha1, '2':sha1+md5, '3':md5, '4':md5 for OpenLdap, '5':sha256). Use '3' here, if hash is not needed for security purpose, for security need, prefer '0'.
148 148
  * 	@return		bool					True if the computed hash is the same as the given one
149 149
  */
150
-function dol_verifyHash($chain, $hash, $type='0')
150
+function dol_verifyHash($chain, $hash, $type = '0')
151 151
 {
152 152
 	global $conf;
153 153
 
154
-	if ($type == '0' && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
154
+	if ($type == '0' && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
155 155
 		if ($hash[0] == '$') return password_verify($chain, $hash);
156
-		else if(strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5
157
-		else if(strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5
156
+		else if (strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5
157
+		else if (strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5
158 158
 
159 159
 		return false;
160 160
 	}
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
  * 	@return	int						Always 1, die process if not allowed
179 179
  *  @see dol_check_secure_access_document
180 180
  */
181
-function restrictedArea($user, $features, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0)
181
+function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0)
182 182
 {
183 183
 	global $db, $conf;
184 184
 	global $hookmanager;
@@ -189,9 +189,9 @@  discard block
 block discarded – undo
189 189
 	//print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
190 190
 
191 191
 	// Get more permissions checks from hooks
192
-	$parameters=array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select);
193
-	$reshook=$hookmanager->executeHooks('restrictedArea',$parameters);
194
-	if (! empty($hookmanager->resArray['result'])) return true;
192
+	$parameters = array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select);
193
+	$reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
194
+	if (!empty($hookmanager->resArray['result'])) return true;
195 195
 	if ($reshook > 0) return false;
196 196
 
197 197
 	if ($dbt_select != 'rowid' && $dbt_select != 'id') $objectid = "'".$objectid."'";
@@ -202,214 +202,214 @@  discard block
 block discarded – undo
202 202
 	else if (preg_match('/\|/', $features)) $featuresarray = explode("|", $features);
203 203
 
204 204
 	// More subfeatures to check
205
-	if (! empty($feature2)) $feature2 = explode("|", $feature2);
205
+	if (!empty($feature2)) $feature2 = explode("|", $feature2);
206 206
 
207 207
 	// More parameters
208 208
 	$params = explode('&', $tableandshare);
209
-	$dbtablename=(! empty($params[0]) ? $params[0] : '');
210
-	$sharedelement=(! empty($params[1]) ? $params[1] : $dbtablename);
209
+	$dbtablename = (!empty($params[0]) ? $params[0] : '');
210
+	$sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
211 211
 
212
-	$listofmodules=explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL);
212
+	$listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL);
213 213
 
214 214
 	// Check read permission from module
215
-	$readok=1; $nbko=0;
215
+	$readok = 1; $nbko = 0;
216 216
 	foreach ($featuresarray as $feature)	// first we check nb of test ko
217 217
 	{
218
-		$featureforlistofmodule=$feature;
219
-		if ($featureforlistofmodule == 'produit') $featureforlistofmodule='product';
220
-		if (! empty($user->societe_id) && ! empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && ! in_array($featureforlistofmodule,$listofmodules))	// If limits on modules for external users, module must be into list of modules for external users
218
+		$featureforlistofmodule = $feature;
219
+		if ($featureforlistofmodule == 'produit') $featureforlistofmodule = 'product';
220
+		if (!empty($user->societe_id) && !empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && !in_array($featureforlistofmodule, $listofmodules))	// If limits on modules for external users, module must be into list of modules for external users
221 221
 		{
222
-			$readok=0; $nbko++;
222
+			$readok = 0; $nbko++;
223 223
 			continue;
224 224
 		}
225 225
 
226 226
 		if ($feature == 'societe')
227 227
 		{
228
-			if (! $user->rights->societe->lire && ! $user->rights->fournisseur->lire) { $readok=0; $nbko++; }
228
+			if (!$user->rights->societe->lire && !$user->rights->fournisseur->lire) { $readok = 0; $nbko++; }
229 229
 		}
230 230
 		else if ($feature == 'contact')
231 231
 		{
232
-			if (! $user->rights->societe->contact->lire) { $readok=0; $nbko++; }
232
+			if (!$user->rights->societe->contact->lire) { $readok = 0; $nbko++; }
233 233
 		}
234 234
 		else if ($feature == 'produit|service')
235 235
 		{
236
-			if (! $user->rights->produit->lire && ! $user->rights->service->lire) { $readok=0; $nbko++; }
236
+			if (!$user->rights->produit->lire && !$user->rights->service->lire) { $readok = 0; $nbko++; }
237 237
 		}
238 238
 		else if ($feature == 'prelevement')
239 239
 		{
240
-			if (! $user->rights->prelevement->bons->lire) { $readok=0; $nbko++; }
240
+			if (!$user->rights->prelevement->bons->lire) { $readok = 0; $nbko++; }
241 241
 		}
242 242
 		else if ($feature == 'cheque')
243 243
 		{
244
-			if (! $user->rights->banque->cheque) { $readok=0; $nbko++; }
244
+			if (!$user->rights->banque->cheque) { $readok = 0; $nbko++; }
245 245
 		}
246 246
 		else if ($feature == 'projet')
247 247
 		{
248
-			if (! $user->rights->projet->lire && ! $user->rights->projet->all->lire) { $readok=0; $nbko++; }
248
+			if (!$user->rights->projet->lire && !$user->rights->projet->all->lire) { $readok = 0; $nbko++; }
249 249
 		}
250
-		else if (! empty($feature2))	// This should be used for future changes
250
+		else if (!empty($feature2))	// This should be used for future changes
251 251
 		{
252
-			$tmpreadok=1;
253
-			foreach($feature2 as $subfeature)
252
+			$tmpreadok = 1;
253
+			foreach ($feature2 as $subfeature)
254 254
 			{
255
-				if (! empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok=0; }
256
-				else if (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok=0; }
257
-				else { $tmpreadok=1; break; } // Break is to bypass second test if the first is ok
255
+				if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok = 0; }
256
+				else if (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok = 0; }
257
+				else { $tmpreadok = 1; break; } // Break is to bypass second test if the first is ok
258 258
 			}
259
-			if (! $tmpreadok)	// We found a test on feature that is ko
259
+			if (!$tmpreadok)	// We found a test on feature that is ko
260 260
 			{
261
-				$readok=0;	// All tests are ko (we manage here the and, the or will be managed later using $nbko).
261
+				$readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
262 262
 				$nbko++;
263 263
 			}
264 264
 		}
265
-		else if (! empty($feature) && ($feature!='user' && $feature!='usergroup'))		// This is for old permissions
265
+		else if (!empty($feature) && ($feature != 'user' && $feature != 'usergroup'))		// This is for old permissions
266 266
 		{
267 267
 			if (empty($user->rights->$feature->lire)
268 268
 				&& empty($user->rights->$feature->read)
269
-				&& empty($user->rights->$feature->run)) { $readok=0; $nbko++; }
269
+				&& empty($user->rights->$feature->run)) { $readok = 0; $nbko++; }
270 270
 		}
271 271
 	}
272 272
 
273 273
 	// If a or and at least one ok
274
-	if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok=1;
274
+	if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok = 1;
275 275
 
276
-	if (! $readok) accessforbidden();
276
+	if (!$readok) accessforbidden();
277 277
 	//print "Read access is ok";
278 278
 
279 279
 	// Check write permission from module (we need to know write permission to create but also to delete drafts record)
280
-	$createok=1; $nbko=0;
281
-	if (GETPOST('action','aZ09')  == 'create' || ((GETPOST("action","aZ09")  == 'confirm_delete' && GETPOST("confirm","aZ09") == 'yes') || GETPOST("action","aZ09")  == 'delete'))
280
+	$createok = 1; $nbko = 0;
281
+	if (GETPOST('action', 'aZ09') == 'create' || ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete'))
282 282
 	{
283 283
 		foreach ($featuresarray as $feature)
284 284
 		{
285 285
 			if ($feature == 'contact')
286 286
 			{
287
-				if (! $user->rights->societe->contact->creer) { $createok=0; $nbko++; }
287
+				if (!$user->rights->societe->contact->creer) { $createok = 0; $nbko++; }
288 288
 			}
289 289
 			else if ($feature == 'produit|service')
290 290
 			{
291
-				if (! $user->rights->produit->creer && ! $user->rights->service->creer) { $createok=0; $nbko++; }
291
+				if (!$user->rights->produit->creer && !$user->rights->service->creer) { $createok = 0; $nbko++; }
292 292
 			}
293 293
 			else if ($feature == 'prelevement')
294 294
 			{
295
-				if (! $user->rights->prelevement->bons->creer) { $createok=0; $nbko++; }
295
+				if (!$user->rights->prelevement->bons->creer) { $createok = 0; $nbko++; }
296 296
 			}
297 297
 			else if ($feature == 'commande_fournisseur')
298 298
 			{
299
-				if (! $user->rights->fournisseur->commande->creer) { $createok=0; $nbko++; }
299
+				if (!$user->rights->fournisseur->commande->creer) { $createok = 0; $nbko++; }
300 300
 			}
301 301
 			else if ($feature == 'banque')
302 302
 			{
303
-				if (! $user->rights->banque->modifier) { $createok=0; $nbko++; }
303
+				if (!$user->rights->banque->modifier) { $createok = 0; $nbko++; }
304 304
 			}
305 305
 			else if ($feature == 'cheque')
306 306
 			{
307
-				if (! $user->rights->banque->cheque) { $createok=0; $nbko++; }
307
+				if (!$user->rights->banque->cheque) { $createok = 0; $nbko++; }
308 308
 			}
309
-			else if (! empty($feature2))	// This should be used
309
+			else if (!empty($feature2))	// This should be used
310 310
 			{
311
-				foreach($feature2 as $subfeature)
311
+				foreach ($feature2 as $subfeature)
312 312
 				{
313 313
 					if (empty($user->rights->$feature->$subfeature->creer)
314 314
 						&& empty($user->rights->$feature->$subfeature->write)
315
-						&& empty($user->rights->$feature->$subfeature->create)) { $createok=0; $nbko++; }
316
-						else { $createok=1; break; } // Break to bypass second test if the first is ok
315
+						&& empty($user->rights->$feature->$subfeature->create)) { $createok = 0; $nbko++; }
316
+						else { $createok = 1; break; } // Break to bypass second test if the first is ok
317 317
 				}
318 318
 			}
319
-			else if (! empty($feature))		// This is for old permissions ('creer' or 'write')
319
+			else if (!empty($feature))		// This is for old permissions ('creer' or 'write')
320 320
 			{
321 321
 				//print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write;
322 322
 				if (empty($user->rights->$feature->creer)
323 323
 					&& empty($user->rights->$feature->write)
324
-					&& empty($user->rights->$feature->create)) { $createok=0; $nbko++; }
324
+					&& empty($user->rights->$feature->create)) { $createok = 0; $nbko++; }
325 325
 			}
326 326
 		}
327 327
 
328 328
 		// If a or and at least one ok
329
-		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok=1;
329
+		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok = 1;
330 330
 
331
-		if (GETPOST('action','aZ09') == 'create' && ! $createok) accessforbidden();
331
+		if (GETPOST('action', 'aZ09') == 'create' && !$createok) accessforbidden();
332 332
 		//print "Write access is ok";
333 333
 	}
334 334
 
335 335
 	// Check create user permission
336
-	$createuserok=1;
337
-	if (GETPOST('action','aZ09') == 'confirm_create_user' && GETPOST("confirm",'aZ09') == 'yes')
336
+	$createuserok = 1;
337
+	if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes')
338 338
 	{
339
-		if (! $user->rights->user->user->creer) $createuserok=0;
339
+		if (!$user->rights->user->user->creer) $createuserok = 0;
340 340
 
341
-		if (! $createuserok) accessforbidden();
341
+		if (!$createuserok) accessforbidden();
342 342
 		//print "Create user access is ok";
343 343
 	}
344 344
 
345 345
 	// Check delete permission from module
346
-	$deleteok=1; $nbko=0;
347
-	if ((GETPOST("action","aZ09")  == 'confirm_delete' && GETPOST("confirm","aZ09") == 'yes') || GETPOST("action","aZ09")  == 'delete')
346
+	$deleteok = 1; $nbko = 0;
347
+	if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete')
348 348
 	{
349 349
 		foreach ($featuresarray as $feature)
350 350
 		{
351 351
 			if ($feature == 'contact')
352 352
 			{
353
-				if (! $user->rights->societe->contact->supprimer) $deleteok=0;
353
+				if (!$user->rights->societe->contact->supprimer) $deleteok = 0;
354 354
 			}
355 355
 			else if ($feature == 'produit|service')
356 356
 			{
357
-				if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) $deleteok=0;
357
+				if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) $deleteok = 0;
358 358
 			}
359 359
 			else if ($feature == 'commande_fournisseur')
360 360
 			{
361
-				if (! $user->rights->fournisseur->commande->supprimer) $deleteok=0;
361
+				if (!$user->rights->fournisseur->commande->supprimer) $deleteok = 0;
362 362
 			}
363 363
 			else if ($feature == 'banque')
364 364
 			{
365
-				if (! $user->rights->banque->modifier) $deleteok=0;
365
+				if (!$user->rights->banque->modifier) $deleteok = 0;
366 366
 			}
367 367
 			else if ($feature == 'cheque')
368 368
 			{
369
-				if (! $user->rights->banque->cheque) $deleteok=0;
369
+				if (!$user->rights->banque->cheque) $deleteok = 0;
370 370
 			}
371 371
 			else if ($feature == 'ecm')
372 372
 			{
373
-				if (! $user->rights->ecm->upload) $deleteok=0;
373
+				if (!$user->rights->ecm->upload) $deleteok = 0;
374 374
 			}
375 375
 			else if ($feature == 'ftp')
376 376
 			{
377
-				if (! $user->rights->ftp->write) $deleteok=0;
378
-			}else if ($feature == 'salaries')
377
+				if (!$user->rights->ftp->write) $deleteok = 0;
378
+			} else if ($feature == 'salaries')
379 379
 			{
380
-				if (! $user->rights->salaries->delete) $deleteok=0;
380
+				if (!$user->rights->salaries->delete) $deleteok = 0;
381 381
 			}
382 382
 			else if ($feature == 'salaries')
383 383
 			{
384
-				if (! $user->rights->salaries->delete) $deleteok=0;
384
+				if (!$user->rights->salaries->delete) $deleteok = 0;
385 385
 			}
386
-			else if (! empty($feature2))	// This should be used for permissions on 2 levels
386
+			else if (!empty($feature2))	// This should be used for permissions on 2 levels
387 387
 			{
388
-				foreach($feature2 as $subfeature)
388
+				foreach ($feature2 as $subfeature)
389 389
 				{
390
-					if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok=0;
391
-					else { $deleteok=1; break; } // For bypass the second test if the first is ok
390
+					if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok = 0;
391
+					else { $deleteok = 1; break; } // For bypass the second test if the first is ok
392 392
 				}
393 393
 			}
394
-			else if (! empty($feature))		// This is used for permissions on 1 level
394
+			else if (!empty($feature))		// This is used for permissions on 1 level
395 395
 			{
396 396
 				//print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
397 397
 				if (empty($user->rights->$feature->supprimer)
398 398
 					&& empty($user->rights->$feature->delete)
399
-					&& empty($user->rights->$feature->run)) $deleteok=0;
399
+					&& empty($user->rights->$feature->run)) $deleteok = 0;
400 400
 			}
401 401
 		}
402 402
 
403 403
 		// If a or and at least one ok
404
-		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok=1;
404
+		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok = 1;
405 405
 
406
-		if (! $deleteok && ! ($isdraft && $createok)) accessforbidden();
406
+		if (!$deleteok && !($isdraft && $createok)) accessforbidden();
407 407
 		//print "Delete access is ok";
408 408
 	}
409 409
 
410 410
 	// If we have a particular object to check permissions on, we check this object
411 411
 	// is linked to a company allowed to $user.
412
-	if (! empty($objectid) && $objectid > 0)
412
+	if (!empty($objectid) && $objectid > 0)
413 413
 	{
414 414
 		$ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select);
415 415
 		return $ok ? 1 : accessforbidden();
@@ -432,74 +432,74 @@  discard block
 block discarded – undo
432 432
  * @return	bool						True if user has access, False otherwise
433 433
  * @see restrictedArea
434 434
  */
435
-function checkUserAccessToObject($user, $featuresarray, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid')
435
+function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid')
436 436
 {
437 437
 	global $db, $conf;
438 438
 
439 439
 	// More parameters
440 440
 	$params = explode('&', $tableandshare);
441
-	$dbtablename=(! empty($params[0]) ? $params[0] : '');
442
-	$sharedelement=(! empty($params[1]) ? $params[1] : $dbtablename);
441
+	$dbtablename = (!empty($params[0]) ? $params[0] : '');
442
+	$sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
443 443
 
444 444
 	foreach ($featuresarray as $feature)
445 445
 	{
446
-		$sql='';
446
+		$sql = '';
447 447
 
448 448
 		// For backward compatibility
449
-		if ($feature == 'member')  $feature='adherent';
450
-		if ($feature == 'project') $feature='projet';
451
-		if ($feature == 'task')    $feature='projet_task';
452
-
453
-		$check = array('adherent','banque','don','user','usergroup','product','produit','service','produit|service','categorie','resource'); // Test on entity only (Objects with no link to company)
454
-		$checksoc = array('societe');	 // Test for societe object
455
-		$checkother = array('contact','agenda');	 // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...).
456
-		$checkproject = array('projet','project'); // Test for project object
449
+		if ($feature == 'member')  $feature = 'adherent';
450
+		if ($feature == 'project') $feature = 'projet';
451
+		if ($feature == 'task')    $feature = 'projet_task';
452
+
453
+		$check = array('adherent', 'banque', 'don', 'user', 'usergroup', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource'); // Test on entity only (Objects with no link to company)
454
+		$checksoc = array('societe'); // Test for societe object
455
+		$checkother = array('contact', 'agenda'); // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...).
456
+		$checkproject = array('projet', 'project'); // Test for project object
457 457
 		$checktask = array('projet_task');
458
-		$nocheck = array('barcode','stock');	// No test
458
+		$nocheck = array('barcode', 'stock'); // No test
459 459
 		$checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...).
460 460
 
461 461
 		// If dbtablename not defined, we use same name for table than module name
462 462
 		if (empty($dbtablename))
463 463
 		{
464 464
 			$dbtablename = $feature;
465
-			$sharedelement = (! empty($params[1]) ? $params[1] : $dbtablename);		// We change dbtablename, so we set sharedelement too.
465
+			$sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
466 466
 		}
467 467
 
468 468
 		// Check permission for object with entity
469
-		if (in_array($feature,$check))
469
+		if (in_array($feature, $check))
470 470
 		{
471 471
 			$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
472
-			$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
473
-			if (($feature == 'user' || $feature == 'usergroup') && ! empty($conf->multicompany->enabled))
472
+			$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
473
+			if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled))
474 474
 			{
475
-				if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
475
+				if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
476 476
 				{
477
-					if ($conf->entity == 1 && $user->admin && ! $user->entity)
477
+					if ($conf->entity == 1 && $user->admin && !$user->entity)
478 478
 					{
479
-						$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
480
-						$sql.= " AND dbt.entity IS NOT NULL";
479
+						$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
480
+						$sql .= " AND dbt.entity IS NOT NULL";
481 481
 					}
482 482
 					else
483 483
 					{
484
-						$sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
485
-						$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
486
-						$sql.= " AND (ug.fk_user = dbt.rowid";
487
-						$sql.= " AND ug.entity IN (".getEntity('user')."))";
488
-						$sql.= " OR dbt.entity = 0"; // Show always superadmin
484
+						$sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
485
+						$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
486
+						$sql .= " AND (ug.fk_user = dbt.rowid";
487
+						$sql .= " AND ug.entity IN (".getEntity('user')."))";
488
+						$sql .= " OR dbt.entity = 0"; // Show always superadmin
489 489
 					}
490 490
 				}
491 491
 				else {
492
-					$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
493
-					$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
492
+					$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
493
+					$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
494 494
 				}
495 495
 			}
496 496
 			else
497 497
 			{
498
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
499
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
498
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
499
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
500 500
 			}
501 501
 		}
502
-		else if (in_array($feature,$checksoc))	// We check feature = checksoc
502
+		else if (in_array($feature, $checksoc))	// We check feature = checksoc
503 503
 		{
504 504
 			// If external user: Check permission for external users
505 505
 			if ($user->socid > 0)
@@ -507,135 +507,135 @@  discard block
 block discarded – undo
507 507
 				if ($user->socid <> $objectid) return false;
508 508
 			}
509 509
 			// If internal user: Check permission for internal users that are restricted on their objects
510
-			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
510
+			else if (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir))
511 511
 			{
512 512
 				$sql = "SELECT COUNT(sc.fk_soc) as nb";
513
-				$sql.= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
514
-				$sql.= ", ".MAIN_DB_PREFIX."societe as s)";
515
-				$sql.= " WHERE sc.fk_soc IN (".$objectid.")";
516
-				$sql.= " AND sc.fk_user = ".$user->id;
517
-				$sql.= " AND sc.fk_soc = s.rowid";
518
-				$sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
513
+				$sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
514
+				$sql .= ", ".MAIN_DB_PREFIX."societe as s)";
515
+				$sql .= " WHERE sc.fk_soc IN (".$objectid.")";
516
+				$sql .= " AND sc.fk_user = ".$user->id;
517
+				$sql .= " AND sc.fk_soc = s.rowid";
518
+				$sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
519 519
 			}
520 520
 			// If multicompany and internal users with all permissions, check user is in correct entity
521
-			else if (! empty($conf->multicompany->enabled))
521
+			else if (!empty($conf->multicompany->enabled))
522 522
 			{
523 523
 				$sql = "SELECT COUNT(s.rowid) as nb";
524
-				$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
525
-				$sql.= " WHERE s.rowid IN (".$objectid.")";
526
-				$sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
524
+				$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
525
+				$sql .= " WHERE s.rowid IN (".$objectid.")";
526
+				$sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
527 527
 			}
528 528
 		}
529
-		else if (in_array($feature,$checkother))	// Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
529
+		else if (in_array($feature, $checkother))	// Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
530 530
 		{
531 531
 			// If external user: Check permission for external users
532 532
 			if ($user->socid > 0)
533 533
 			{
534 534
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
535
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
536
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
537
-				$sql.= " AND dbt.fk_soc = ".$user->socid;
535
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
536
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
537
+				$sql .= " AND dbt.fk_soc = ".$user->socid;
538 538
 			}
539 539
 			// If internal user: Check permission for internal users that are restricted on their objects
540
-			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
540
+			else if (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir))
541 541
 			{
542 542
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
543
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
544
-				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
545
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
546
-				$sql.= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)";	// Contact not linked to a company or to a company of user
547
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
543
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
544
+				$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
545
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
546
+				$sql .= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user
547
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
548 548
 			}
549 549
 			// If multicompany and internal users with all permissions, check user is in correct entity
550
-			else if (! empty($conf->multicompany->enabled))
550
+			else if (!empty($conf->multicompany->enabled))
551 551
 			{
552 552
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
553
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
554
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
555
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
553
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
554
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
555
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
556 556
 			}
557 557
 		}
558
-		else if (in_array($feature,$checkproject))
558
+		else if (in_array($feature, $checkproject))
559 559
 		{
560
-			if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
560
+			if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
561 561
 			{
562 562
 				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
563
-				$projectstatic=new Project($db);
564
-				$tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
565
-				$tmparray=explode(',',$tmps);
566
-				if (! in_array($objectid,$tmparray)) return false;
563
+				$projectstatic = new Project($db);
564
+				$tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
565
+				$tmparray = explode(',', $tmps);
566
+				if (!in_array($objectid, $tmparray)) return false;
567 567
 			}
568 568
 			else
569 569
 			{
570 570
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
571
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
572
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
573
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
571
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
572
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
573
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
574 574
 			}
575 575
 		}
576
-		else if (in_array($feature,$checktask))
576
+		else if (in_array($feature, $checktask))
577 577
 		{
578
-			if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
578
+			if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
579 579
 			{
580 580
 				$task = new Task($db);
581 581
 				$task->fetch($objectid);
582 582
 
583 583
 				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
584
-				$projectstatic=new Project($db);
585
-				$tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
586
-				$tmparray=explode(',',$tmps);
587
-				if (! in_array($task->fk_project,$tmparray)) return false;
584
+				$projectstatic = new Project($db);
585
+				$tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
586
+				$tmparray = explode(',', $tmps);
587
+				if (!in_array($task->fk_project, $tmparray)) return false;
588 588
 			}
589 589
 			else
590 590
 			{
591 591
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
592
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
593
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
594
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
592
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
593
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
594
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
595 595
 			}
596 596
 		}
597
-		else if (! in_array($feature,$nocheck))		// By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
597
+		else if (!in_array($feature, $nocheck))		// By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
598 598
 		{
599 599
 			// If external user: Check permission for external users
600 600
 			if ($user->socid > 0)
601 601
 			{
602
-				if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
602
+				if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined');
603 603
 				$sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
604
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
605
-				$sql.= " WHERE dbt.rowid IN (".$objectid.")";
606
-				$sql.= " AND dbt.".$dbt_keyfield." = ".$user->socid;
604
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
605
+				$sql .= " WHERE dbt.rowid IN (".$objectid.")";
606
+				$sql .= " AND dbt.".$dbt_keyfield." = ".$user->socid;
607 607
 			}
608 608
 			// If internal user: Check permission for internal users that are restricted on their objects
609
-			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
609
+			else if (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir))
610 610
 			{
611
-				if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
611
+				if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined');
612 612
 				$sql = "SELECT COUNT(sc.fk_soc) as nb";
613
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
614
-				$sql.= ", ".MAIN_DB_PREFIX."societe as s";
615
-				$sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
616
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
617
-				$sql.= " AND sc.fk_soc = dbt.".$dbt_keyfield;
618
-				$sql.= " AND dbt.".$dbt_keyfield." = s.rowid";
619
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
620
-				$sql.= " AND sc.fk_user = ".$user->id;
613
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
614
+				$sql .= ", ".MAIN_DB_PREFIX."societe as s";
615
+				$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
616
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
617
+				$sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield;
618
+				$sql .= " AND dbt.".$dbt_keyfield." = s.rowid";
619
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
620
+				$sql .= " AND sc.fk_user = ".$user->id;
621 621
 			}
622 622
 			// If multicompany and internal users with all permissions, check user is in correct entity
623
-			else if (! empty($conf->multicompany->enabled))
623
+			else if (!empty($conf->multicompany->enabled))
624 624
 			{
625 625
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
626
-				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
627
-				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
628
-				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
626
+				$sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
627
+				$sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
628
+				$sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
629 629
 			}
630 630
 		}
631 631
 
632 632
 		if ($sql)
633 633
 		{
634
-			$resql=$db->query($sql);
634
+			$resql = $db->query($sql);
635 635
 			if ($resql)
636 636
 			{
637 637
 				$obj = $db->fetch_object($resql);
638
-				if (! $obj || $obj->nb < count(explode(',', $objectid))) return false;
638
+				if (!$obj || $obj->nb < count(explode(',', $objectid))) return false;
639 639
 			}
640 640
 			else
641 641
 			{
@@ -656,13 +656,13 @@  discard block
 block discarded – undo
656 656
  *  @param  int		$showonlymessage     Show only message parameter. Otherwise add more information.
657 657
  *  @return	void
658 658
  */
659
-function accessforbidden($message='',$printheader=1,$printfooter=1,$showonlymessage=0)
659
+function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0)
660 660
 {
661 661
     global $conf, $db, $user, $langs;
662
-    if (! is_object($langs))
662
+    if (!is_object($langs))
663 663
     {
664 664
         include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
665
-        $langs=new Translate('',$conf);
665
+        $langs = new Translate('', $conf);
666 666
         $langs->setDefaultLang();
667 667
     }
668 668
 
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
 		else if (function_exists("llxHeaderVierge")) llxHeaderVierge('');
675 675
 	}
676 676
 	print '<div class="error">';
677
-	if (! $message) print $langs->trans("ErrorForbidden");
677
+	if (!$message) print $langs->trans("ErrorForbidden");
678 678
 	else print $message;
679 679
 	print '</div>';
680 680
 	print '<br>';
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
 		if ($user->login)
684 684
 		{
685 685
 			print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
686
-			print $langs->trans("ErrorForbidden2",$langs->trans("Home"),$langs->trans("Users"));
686
+			print $langs->trans("ErrorForbidden2", $langs->trans("Home"), $langs->trans("Users"));
687 687
 		}
688 688
 		else
689 689
 		{
Please login to merge, or discard this patch.
Braces   +217 added lines, -137 removed lines patch added patch discarded remove patch
@@ -36,17 +36,18 @@  discard block
 block discarded – undo
36 36
  */
37 37
 function dol_encode($chain, $key='1')
38 38
 {
39
-	if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
39
+	if (is_numeric($key) && $key == '1') {
40
+	    // rule 1 is offset of 17 for char
40 41
 	{
41 42
 		$output_tab=array();
43
+	}
42 44
 		$strlength=dol_strlen($chain);
43 45
 		for ($i=0; $i < $strlength; $i++)
44 46
 		{
45 47
 			$output_tab[$i] = chr(ord(substr($chain,$i,1))+17);
46 48
 		}
47 49
 		$chain = implode("",$output_tab);
48
-	}
49
-	elseif ($key)
50
+	} elseif ($key)
50 51
 	{
51 52
 		$result='';
52 53
 		$strlength=dol_strlen($chain);
@@ -74,9 +75,11 @@  discard block
 block discarded – undo
74 75
 {
75 76
 	$chain = base64_decode($chain);
76 77
 
77
-	if (is_numeric($key) && $key == '1')	// rule 1 is offset of 17 for char
78
+	if (is_numeric($key) && $key == '1') {
79
+	    // rule 1 is offset of 17 for char
78 80
 	{
79 81
 		$output_tab=array();
82
+	}
80 83
 		$strlength=dol_strlen($chain);
81 84
 		for ($i=0; $i < $strlength;$i++)
82 85
 		{
@@ -84,8 +87,7 @@  discard block
 block discarded – undo
84 87
 		}
85 88
 
86 89
 		$chain = implode("",$output_tab);
87
-	}
88
-	elseif ($key)
90
+	} elseif ($key)
89 91
 	{
90 92
 		$result='';
91 93
 		$strlength=dol_strlen($chain);
@@ -122,15 +124,27 @@  discard block
 block discarded – undo
122 124
 	}
123 125
 
124 126
 	// Salt value
125
-	if (! empty($conf->global->MAIN_SECURITY_SALT)) $chain=$conf->global->MAIN_SECURITY_SALT.$chain;
127
+	if (! empty($conf->global->MAIN_SECURITY_SALT)) {
128
+	    $chain=$conf->global->MAIN_SECURITY_SALT.$chain;
129
+	}
126 130
 
127
-	if ($type == '1' || $type == 'sha1') return sha1($chain);
128
-	else if ($type == '2' || $type == 'sha1md5') return sha1(md5($chain));
129
-	else if ($type == '3' || $type == 'md5') return md5($chain);
130
-	else if ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
131
-	else if ($type == '5') return hash('sha256',$chain);
132
-	else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain);
133
-	else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain));
131
+	if ($type == '1' || $type == 'sha1') {
132
+	    return sha1($chain);
133
+	} else if ($type == '2' || $type == 'sha1md5') {
134
+	    return sha1(md5($chain));
135
+	} else if ($type == '3' || $type == 'md5') {
136
+	    return md5($chain);
137
+	} else if ($type == '4' || $type == 'md5openldap') {
138
+	    return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain));
139
+	}
140
+	// For OpenLdap with md5 (based on an unencrypted password in base)
141
+	else if ($type == '5') {
142
+	    return hash('sha256',$chain);
143
+	} else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') {
144
+	    return sha1($chain);
145
+	} else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') {
146
+	    return sha1(md5($chain));
147
+	}
134 148
 
135 149
 	// No particular encoding defined, use default
136 150
 	return md5($chain);
@@ -152,9 +166,16 @@  discard block
 block discarded – undo
152 166
 	global $conf;
153 167
 
154 168
 	if ($type == '0' && ! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
155
-		if ($hash[0] == '$') return password_verify($chain, $hash);
156
-		else if(strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5
157
-		else if(strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5
169
+		if ($hash[0] == '$') {
170
+		    return password_verify($chain, $hash);
171
+		} else if(strlen($hash) == 32) {
172
+		    return dol_verifyHash($chain, $hash, '3');
173
+		}
174
+		// md5
175
+		else if(strlen($hash) == 40) {
176
+		    return dol_verifyHash($chain, $hash, '2');
177
+		}
178
+		// sha1md5
158 179
 
159 180
 		return false;
160 181
 	}
@@ -191,18 +212,29 @@  discard block
 block discarded – undo
191 212
 	// Get more permissions checks from hooks
192 213
 	$parameters=array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select);
193 214
 	$reshook=$hookmanager->executeHooks('restrictedArea',$parameters);
194
-	if (! empty($hookmanager->resArray['result'])) return true;
195
-	if ($reshook > 0) return false;
215
+	if (! empty($hookmanager->resArray['result'])) {
216
+	    return true;
217
+	}
218
+	if ($reshook > 0) {
219
+	    return false;
220
+	}
196 221
 
197
-	if ($dbt_select != 'rowid' && $dbt_select != 'id') $objectid = "'".$objectid."'";
222
+	if ($dbt_select != 'rowid' && $dbt_select != 'id') {
223
+	    $objectid = "'".$objectid."'";
224
+	}
198 225
 
199 226
 	// Features/modules to check
200 227
 	$featuresarray = array($features);
201
-	if (preg_match('/&/', $features)) $featuresarray = explode("&", $features);
202
-	else if (preg_match('/\|/', $features)) $featuresarray = explode("|", $features);
228
+	if (preg_match('/&/', $features)) {
229
+	    $featuresarray = explode("&", $features);
230
+	} else if (preg_match('/\|/', $features)) {
231
+	    $featuresarray = explode("|", $features);
232
+	}
203 233
 
204 234
 	// More subfeatures to check
205
-	if (! empty($feature2)) $feature2 = explode("|", $feature2);
235
+	if (! empty($feature2)) {
236
+	    $feature2 = explode("|", $feature2);
237
+	}
206 238
 
207 239
 	// More parameters
208 240
 	$params = explode('&', $tableandshare);
@@ -213,67 +245,77 @@  discard block
 block discarded – undo
213 245
 
214 246
 	// Check read permission from module
215 247
 	$readok=1; $nbko=0;
216
-	foreach ($featuresarray as $feature)	// first we check nb of test ko
248
+	foreach ($featuresarray as $feature) {
249
+	    // first we check nb of test ko
217 250
 	{
218 251
 		$featureforlistofmodule=$feature;
219
-		if ($featureforlistofmodule == 'produit') $featureforlistofmodule='product';
220
-		if (! empty($user->societe_id) && ! empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && ! in_array($featureforlistofmodule,$listofmodules))	// If limits on modules for external users, module must be into list of modules for external users
252
+	}
253
+		if ($featureforlistofmodule == 'produit') {
254
+		    $featureforlistofmodule='product';
255
+		}
256
+		if (! empty($user->societe_id) && ! empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && ! in_array($featureforlistofmodule,$listofmodules)) {
257
+		    // If limits on modules for external users, module must be into list of modules for external users
221 258
 		{
222
-			$readok=0; $nbko++;
259
+			$readok=0;
260
+		}
261
+		$nbko++;
223 262
 			continue;
224 263
 		}
225 264
 
226 265
 		if ($feature == 'societe')
227 266
 		{
228 267
 			if (! $user->rights->societe->lire && ! $user->rights->fournisseur->lire) { $readok=0; $nbko++; }
229
-		}
230
-		else if ($feature == 'contact')
268
+		} else if ($feature == 'contact')
231 269
 		{
232 270
 			if (! $user->rights->societe->contact->lire) { $readok=0; $nbko++; }
233
-		}
234
-		else if ($feature == 'produit|service')
271
+		} else if ($feature == 'produit|service')
235 272
 		{
236 273
 			if (! $user->rights->produit->lire && ! $user->rights->service->lire) { $readok=0; $nbko++; }
237
-		}
238
-		else if ($feature == 'prelevement')
274
+		} else if ($feature == 'prelevement')
239 275
 		{
240 276
 			if (! $user->rights->prelevement->bons->lire) { $readok=0; $nbko++; }
241
-		}
242
-		else if ($feature == 'cheque')
277
+		} else if ($feature == 'cheque')
243 278
 		{
244 279
 			if (! $user->rights->banque->cheque) { $readok=0; $nbko++; }
245
-		}
246
-		else if ($feature == 'projet')
280
+		} else if ($feature == 'projet')
247 281
 		{
248 282
 			if (! $user->rights->projet->lire && ! $user->rights->projet->all->lire) { $readok=0; $nbko++; }
249
-		}
250
-		else if (! empty($feature2))	// This should be used for future changes
283
+		} else if (! empty($feature2)) {
284
+		    // This should be used for future changes
251 285
 		{
252 286
 			$tmpreadok=1;
287
+		}
253 288
 			foreach($feature2 as $subfeature)
254 289
 			{
255
-				if (! empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok=0; }
256
-				else if (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok=0; }
257
-				else { $tmpreadok=1; break; } // Break is to bypass second test if the first is ok
290
+				if (! empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok=0; } else if (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok=0; } else { $tmpreadok=1; break; } // Break is to bypass second test if the first is ok
258 291
 			}
259
-			if (! $tmpreadok)	// We found a test on feature that is ko
292
+			if (! $tmpreadok) {
293
+			    // We found a test on feature that is ko
260 294
 			{
261
-				$readok=0;	// All tests are ko (we manage here the and, the or will be managed later using $nbko).
295
+				$readok=0;
296
+			}
297
+			// All tests are ko (we manage here the and, the or will be managed later using $nbko).
262 298
 				$nbko++;
263 299
 			}
264
-		}
265
-		else if (! empty($feature) && ($feature!='user' && $feature!='usergroup'))		// This is for old permissions
300
+		} else if (! empty($feature) && ($feature!='user' && $feature!='usergroup')) {
301
+		    // This is for old permissions
266 302
 		{
267 303
 			if (empty($user->rights->$feature->lire)
268 304
 				&& empty($user->rights->$feature->read)
269
-				&& empty($user->rights->$feature->run)) { $readok=0; $nbko++; }
305
+				&& empty($user->rights->$feature->run)) { $readok=0;
306
+		}
307
+		$nbko++; }
270 308
 		}
271 309
 	}
272 310
 
273 311
 	// If a or and at least one ok
274
-	if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok=1;
312
+	if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
313
+	    $readok=1;
314
+	}
275 315
 
276
-	if (! $readok) accessforbidden();
316
+	if (! $readok) {
317
+	    accessforbidden();
318
+	}
277 319
 	//print "Read access is ok";
278 320
 
279 321
 	// Check write permission from module (we need to know write permission to create but also to delete drafts record)
@@ -285,50 +327,52 @@  discard block
 block discarded – undo
285 327
 			if ($feature == 'contact')
286 328
 			{
287 329
 				if (! $user->rights->societe->contact->creer) { $createok=0; $nbko++; }
288
-			}
289
-			else if ($feature == 'produit|service')
330
+			} else if ($feature == 'produit|service')
290 331
 			{
291 332
 				if (! $user->rights->produit->creer && ! $user->rights->service->creer) { $createok=0; $nbko++; }
292
-			}
293
-			else if ($feature == 'prelevement')
333
+			} else if ($feature == 'prelevement')
294 334
 			{
295 335
 				if (! $user->rights->prelevement->bons->creer) { $createok=0; $nbko++; }
296
-			}
297
-			else if ($feature == 'commande_fournisseur')
336
+			} else if ($feature == 'commande_fournisseur')
298 337
 			{
299 338
 				if (! $user->rights->fournisseur->commande->creer) { $createok=0; $nbko++; }
300
-			}
301
-			else if ($feature == 'banque')
339
+			} else if ($feature == 'banque')
302 340
 			{
303 341
 				if (! $user->rights->banque->modifier) { $createok=0; $nbko++; }
304
-			}
305
-			else if ($feature == 'cheque')
342
+			} else if ($feature == 'cheque')
306 343
 			{
307 344
 				if (! $user->rights->banque->cheque) { $createok=0; $nbko++; }
308
-			}
309
-			else if (! empty($feature2))	// This should be used
345
+			} else if (! empty($feature2)) {
346
+			    // This should be used
310 347
 			{
311 348
 				foreach($feature2 as $subfeature)
312 349
 				{
313 350
 					if (empty($user->rights->$feature->$subfeature->creer)
314 351
 						&& empty($user->rights->$feature->$subfeature->write)
315
-						&& empty($user->rights->$feature->$subfeature->create)) { $createok=0; $nbko++; }
316
-						else { $createok=1; break; } // Break to bypass second test if the first is ok
317
-				}
352
+						&& empty($user->rights->$feature->$subfeature->create)) { $createok=0;
318 353
 			}
319
-			else if (! empty($feature))		// This is for old permissions ('creer' or 'write')
354
+			$nbko++; } else { $createok=1; break; } // Break to bypass second test if the first is ok
355
+				}
356
+			} else if (! empty($feature)) {
357
+			    // This is for old permissions ('creer' or 'write')
320 358
 			{
321 359
 				//print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write;
322 360
 				if (empty($user->rights->$feature->creer)
323 361
 					&& empty($user->rights->$feature->write)
324
-					&& empty($user->rights->$feature->create)) { $createok=0; $nbko++; }
362
+					&& empty($user->rights->$feature->create)) { $createok=0;
363
+			}
364
+			$nbko++; }
325 365
 			}
326 366
 		}
327 367
 
328 368
 		// If a or and at least one ok
329
-		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok=1;
369
+		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
370
+		    $createok=1;
371
+		}
330 372
 
331
-		if (GETPOST('action','aZ09') == 'create' && ! $createok) accessforbidden();
373
+		if (GETPOST('action','aZ09') == 'create' && ! $createok) {
374
+		    accessforbidden();
375
+		}
332 376
 		//print "Write access is ok";
333 377
 	}
334 378
 
@@ -336,9 +380,13 @@  discard block
 block discarded – undo
336 380
 	$createuserok=1;
337 381
 	if (GETPOST('action','aZ09') == 'confirm_create_user' && GETPOST("confirm",'aZ09') == 'yes')
338 382
 	{
339
-		if (! $user->rights->user->user->creer) $createuserok=0;
383
+		if (! $user->rights->user->user->creer) {
384
+		    $createuserok=0;
385
+		}
340 386
 
341
-		if (! $createuserok) accessforbidden();
387
+		if (! $createuserok) {
388
+		    accessforbidden();
389
+		}
342 390
 		//print "Create user access is ok";
343 391
 	}
344 392
 
@@ -350,60 +398,76 @@  discard block
 block discarded – undo
350 398
 		{
351 399
 			if ($feature == 'contact')
352 400
 			{
353
-				if (! $user->rights->societe->contact->supprimer) $deleteok=0;
354
-			}
355
-			else if ($feature == 'produit|service')
401
+				if (! $user->rights->societe->contact->supprimer) {
402
+				    $deleteok=0;
403
+				}
404
+			} else if ($feature == 'produit|service')
356 405
 			{
357
-				if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) $deleteok=0;
358
-			}
359
-			else if ($feature == 'commande_fournisseur')
406
+				if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) {
407
+				    $deleteok=0;
408
+				}
409
+			} else if ($feature == 'commande_fournisseur')
360 410
 			{
361
-				if (! $user->rights->fournisseur->commande->supprimer) $deleteok=0;
362
-			}
363
-			else if ($feature == 'banque')
411
+				if (! $user->rights->fournisseur->commande->supprimer) {
412
+				    $deleteok=0;
413
+				}
414
+			} else if ($feature == 'banque')
364 415
 			{
365
-				if (! $user->rights->banque->modifier) $deleteok=0;
366
-			}
367
-			else if ($feature == 'cheque')
416
+				if (! $user->rights->banque->modifier) {
417
+				    $deleteok=0;
418
+				}
419
+			} else if ($feature == 'cheque')
368 420
 			{
369
-				if (! $user->rights->banque->cheque) $deleteok=0;
370
-			}
371
-			else if ($feature == 'ecm')
421
+				if (! $user->rights->banque->cheque) {
422
+				    $deleteok=0;
423
+				}
424
+			} else if ($feature == 'ecm')
372 425
 			{
373
-				if (! $user->rights->ecm->upload) $deleteok=0;
374
-			}
375
-			else if ($feature == 'ftp')
426
+				if (! $user->rights->ecm->upload) {
427
+				    $deleteok=0;
428
+				}
429
+			} else if ($feature == 'ftp')
376 430
 			{
377
-				if (! $user->rights->ftp->write) $deleteok=0;
378
-			}else if ($feature == 'salaries')
431
+				if (! $user->rights->ftp->write) {
432
+				    $deleteok=0;
433
+				}
434
+			} else if ($feature == 'salaries')
379 435
 			{
380
-				if (! $user->rights->salaries->delete) $deleteok=0;
381
-			}
382
-			else if ($feature == 'salaries')
436
+				if (! $user->rights->salaries->delete) {
437
+				    $deleteok=0;
438
+				}
439
+			} else if ($feature == 'salaries')
383 440
 			{
384
-				if (! $user->rights->salaries->delete) $deleteok=0;
385
-			}
386
-			else if (! empty($feature2))	// This should be used for permissions on 2 levels
441
+				if (! $user->rights->salaries->delete) {
442
+				    $deleteok=0;
443
+				}
444
+			} else if (! empty($feature2)) {
445
+			    // This should be used for permissions on 2 levels
387 446
 			{
388 447
 				foreach($feature2 as $subfeature)
389 448
 				{
390 449
 					if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok=0;
391
-					else { $deleteok=1; break; } // For bypass the second test if the first is ok
450
+			} else { $deleteok=1; break; } // For bypass the second test if the first is ok
392 451
 				}
393
-			}
394
-			else if (! empty($feature))		// This is used for permissions on 1 level
452
+			} else if (! empty($feature)) {
453
+			    // This is used for permissions on 1 level
395 454
 			{
396 455
 				//print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
397 456
 				if (empty($user->rights->$feature->supprimer)
398 457
 					&& empty($user->rights->$feature->delete)
399 458
 					&& empty($user->rights->$feature->run)) $deleteok=0;
400 459
 			}
460
+			}
401 461
 		}
402 462
 
403 463
 		// If a or and at least one ok
404
-		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok=1;
464
+		if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
465
+		    $deleteok=1;
466
+		}
405 467
 
406
-		if (! $deleteok && ! ($isdraft && $createok)) accessforbidden();
468
+		if (! $deleteok && ! ($isdraft && $createok)) {
469
+		    accessforbidden();
470
+		}
407 471
 		//print "Delete access is ok";
408 472
 	}
409 473
 
@@ -446,9 +510,15 @@  discard block
 block discarded – undo
446 510
 		$sql='';
447 511
 
448 512
 		// For backward compatibility
449
-		if ($feature == 'member')  $feature='adherent';
450
-		if ($feature == 'project') $feature='projet';
451
-		if ($feature == 'task')    $feature='projet_task';
513
+		if ($feature == 'member') {
514
+		    $feature='adherent';
515
+		}
516
+		if ($feature == 'project') {
517
+		    $feature='projet';
518
+		}
519
+		if ($feature == 'task') {
520
+		    $feature='projet_task';
521
+		}
452 522
 
453 523
 		$check = array('adherent','banque','don','user','usergroup','product','produit','service','produit|service','categorie','resource'); // Test on entity only (Objects with no link to company)
454 524
 		$checksoc = array('societe');	 // Test for societe object
@@ -478,8 +548,7 @@  discard block
 block discarded – undo
478 548
 					{
479 549
 						$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
480 550
 						$sql.= " AND dbt.entity IS NOT NULL";
481
-					}
482
-					else
551
+					} else
483 552
 					{
484 553
 						$sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
485 554
 						$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
@@ -487,24 +556,23 @@  discard block
 block discarded – undo
487 556
 						$sql.= " AND ug.entity IN (".getEntity('user')."))";
488 557
 						$sql.= " OR dbt.entity = 0"; // Show always superadmin
489 558
 					}
490
-				}
491
-				else {
559
+				} else {
492 560
 					$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
493 561
 					$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
494 562
 				}
495
-			}
496
-			else
563
+			} else
497 564
 			{
498 565
 				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
499 566
 				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
500 567
 			}
501
-		}
502
-		else if (in_array($feature,$checksoc))	// We check feature = checksoc
568
+		} else if (in_array($feature,$checksoc)) {
569
+		    // We check feature = checksoc
503 570
 		{
504 571
 			// If external user: Check permission for external users
505 572
 			if ($user->socid > 0)
506 573
 			{
507 574
 				if ($user->socid <> $objectid) return false;
575
+		}
508 576
 			}
509 577
 			// If internal user: Check permission for internal users that are restricted on their objects
510 578
 			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
@@ -525,13 +593,14 @@  discard block
 block discarded – undo
525 593
 				$sql.= " WHERE s.rowid IN (".$objectid.")";
526 594
 				$sql.= " AND s.entity IN (".getEntity($sharedelement, 1).")";
527 595
 			}
528
-		}
529
-		else if (in_array($feature,$checkother))	// Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
596
+		} else if (in_array($feature,$checkother)) {
597
+		    // Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
530 598
 		{
531 599
 			// If external user: Check permission for external users
532 600
 			if ($user->socid > 0)
533 601
 			{
534 602
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
603
+		}
535 604
 				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
536 605
 				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
537 606
 				$sql.= " AND dbt.fk_soc = ".$user->socid;
@@ -554,8 +623,7 @@  discard block
 block discarded – undo
554 623
 				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
555 624
 				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
556 625
 			}
557
-		}
558
-		else if (in_array($feature,$checkproject))
626
+		} else if (in_array($feature,$checkproject))
559 627
 		{
560 628
 			if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
561 629
 			{
@@ -563,17 +631,17 @@  discard block
 block discarded – undo
563 631
 				$projectstatic=new Project($db);
564 632
 				$tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
565 633
 				$tmparray=explode(',',$tmps);
566
-				if (! in_array($objectid,$tmparray)) return false;
567
-			}
568
-			else
634
+				if (! in_array($objectid,$tmparray)) {
635
+				    return false;
636
+				}
637
+			} else
569 638
 			{
570 639
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
571 640
 				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
572 641
 				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
573 642
 				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
574 643
 			}
575
-		}
576
-		else if (in_array($feature,$checktask))
644
+		} else if (in_array($feature,$checktask))
577 645
 		{
578 646
 			if (! empty($conf->projet->enabled) && empty($user->rights->projet->all->lire))
579 647
 			{
@@ -584,22 +652,24 @@  discard block
 block discarded – undo
584 652
 				$projectstatic=new Project($db);
585 653
 				$tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,0);
586 654
 				$tmparray=explode(',',$tmps);
587
-				if (! in_array($task->fk_project,$tmparray)) return false;
588
-			}
589
-			else
655
+				if (! in_array($task->fk_project,$tmparray)) {
656
+				    return false;
657
+				}
658
+			} else
590 659
 			{
591 660
 				$sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
592 661
 				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
593 662
 				$sql.= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
594 663
 				$sql.= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
595 664
 			}
596
-		}
597
-		else if (! in_array($feature,$nocheck))		// By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
665
+		} else if (! in_array($feature,$nocheck)) {
666
+		    // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
598 667
 		{
599 668
 			// If external user: Check permission for external users
600 669
 			if ($user->socid > 0)
601 670
 			{
602 671
 				if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
672
+		}
603 673
 				$sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
604 674
 				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
605 675
 				$sql.= " WHERE dbt.rowid IN (".$objectid.")";
@@ -608,7 +678,9 @@  discard block
 block discarded – undo
608 678
 			// If internal user: Check permission for internal users that are restricted on their objects
609 679
 			else if (! empty($conf->societe->enabled) && ($user->rights->societe->lire && ! $user->rights->societe->client->voir))
610 680
 			{
611
-				if (empty($dbt_keyfield)) dol_print_error('','Param dbt_keyfield is required but not defined');
681
+				if (empty($dbt_keyfield)) {
682
+				    dol_print_error('','Param dbt_keyfield is required but not defined');
683
+				}
612 684
 				$sql = "SELECT COUNT(sc.fk_soc) as nb";
613 685
 				$sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
614 686
 				$sql.= ", ".MAIN_DB_PREFIX."societe as s";
@@ -635,9 +707,10 @@  discard block
 block discarded – undo
635 707
 			if ($resql)
636 708
 			{
637 709
 				$obj = $db->fetch_object($resql);
638
-				if (! $obj || $obj->nb < count(explode(',', $objectid))) return false;
639
-			}
640
-			else
710
+				if (! $obj || $obj->nb < count(explode(',', $objectid))) {
711
+				    return false;
712
+				}
713
+			} else
641 714
 			{
642 715
 				return false;
643 716
 			}
@@ -670,12 +743,18 @@  discard block
 block discarded – undo
670 743
 
671 744
 	if ($printheader)
672 745
 	{
673
-		if (function_exists("llxHeader")) llxHeader('');
674
-		else if (function_exists("llxHeaderVierge")) llxHeaderVierge('');
746
+		if (function_exists("llxHeader")) {
747
+		    llxHeader('');
748
+		} else if (function_exists("llxHeaderVierge")) {
749
+		    llxHeaderVierge('');
750
+		}
675 751
 	}
676 752
 	print '<div class="error">';
677
-	if (! $message) print $langs->trans("ErrorForbidden");
678
-	else print $message;
753
+	if (! $message) {
754
+	    print $langs->trans("ErrorForbidden");
755
+	} else {
756
+	    print $message;
757
+	}
679 758
 	print '</div>';
680 759
 	print '<br>';
681 760
 	if (empty($showonlymessage))
@@ -684,12 +763,13 @@  discard block
 block discarded – undo
684 763
 		{
685 764
 			print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
686 765
 			print $langs->trans("ErrorForbidden2",$langs->trans("Home"),$langs->trans("Users"));
687
-		}
688
-		else
766
+		} else
689 767
 		{
690 768
 			print $langs->trans("ErrorForbidden3");
691 769
 		}
692 770
 	}
693
-	if ($printfooter && function_exists("llxFooter")) llxFooter();
771
+	if ($printfooter && function_exists("llxFooter")) {
772
+	    llxFooter();
773
+	}
694 774
 	exit(0);
695 775
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/lib/functions2.lib.php 3 patches
Indentation   +400 added lines, -400 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 
127 127
     $selected='EUA4';
128 128
     if (!$outputlangs) {
129
-    	$outputlangs=$langs;
129
+        $outputlangs=$langs;
130 130
     }
131 131
 
132 132
     if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
@@ -230,15 +230,15 @@  discard block
 block discarded – undo
230 230
         else print ': ';
231 231
         if (is_object($object->user_creation))
232 232
         {
233
-        	if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
234
-        	else print $langs->trans("Unknown");
233
+            if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
234
+            else print $langs->trans("Unknown");
235 235
         }
236 236
         else
237 237
         {
238 238
             $userstatic=new User($db);
239 239
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
240 240
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
241
-        	else print $langs->trans("Unknown");
241
+            else print $langs->trans("Unknown");
242 242
         }
243 243
         if ($usetable) print '</td></tr>';
244 244
         else print '<br>';
@@ -266,15 +266,15 @@  discard block
 block discarded – undo
266 266
         else print ': ';
267 267
         if (is_object($object->user_modification))
268 268
         {
269
-        	if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
270
-        	else print $langs->trans("Unknown");
269
+            if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
270
+            else print $langs->trans("Unknown");
271 271
         }
272 272
         else
273 273
         {
274 274
             $userstatic=new User($db);
275 275
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
276 276
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
277
-        	else print $langs->trans("Unknown");
277
+            else print $langs->trans("Unknown");
278 278
         }
279 279
         if ($usetable) print '</td></tr>';
280 280
         else print '<br>';
@@ -303,14 +303,14 @@  discard block
 block discarded – undo
303 303
         if (is_object($object->user_validation))
304 304
         {
305 305
             if ($object->user_validation->id) print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
306
-        	else print $langs->trans("Unknown");
306
+            else print $langs->trans("Unknown");
307 307
         }
308 308
         else
309 309
         {
310 310
             $userstatic=new User($db);
311 311
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
312
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
313
-        	else print $langs->trans("Unknown");
312
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
313
+            else print $langs->trans("Unknown");
314 314
         }
315 315
         if ($usetable) print '</td></tr>';
316 316
         else print '<br>';
@@ -339,14 +339,14 @@  discard block
 block discarded – undo
339 339
         if (is_object($object->user_approve))
340 340
         {
341 341
             if ($object->user_approve->id) print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
342
-        	else print $langs->trans("Unknown");
342
+            else print $langs->trans("Unknown");
343 343
         }
344 344
         else
345 345
         {
346 346
             $userstatic=new User($db);
347 347
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
348
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
349
-        	else print $langs->trans("Unknown");
348
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
349
+            else print $langs->trans("Unknown");
350 350
         }
351 351
         if ($usetable) print '</td></tr>';
352 352
         else print '<br>';
@@ -402,15 +402,15 @@  discard block
 block discarded – undo
402 402
         else print ': ';
403 403
         if (is_object($object->user_cloture))
404 404
         {
405
-			if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
406
-        	else print $langs->trans("Unknown");
405
+            if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
406
+            else print $langs->trans("Unknown");
407 407
         }
408 408
         else
409 409
         {
410 410
             $userstatic=new User($db);
411 411
             $userstatic->fetch($object->user_cloture);
412
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
413
-        	else print $langs->trans("Unknown");
412
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
413
+            else print $langs->trans("Unknown");
414 414
         }
415 415
         if ($usetable) print '</td></tr>';
416 416
         else print '<br>';
@@ -438,15 +438,15 @@  discard block
 block discarded – undo
438 438
         else print ': ';
439 439
         if (is_object($object->user_rappro))
440 440
         {
441
-			if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
442
-        	else print $langs->trans("Unknown");
441
+            if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
442
+            else print $langs->trans("Unknown");
443 443
         }
444 444
         else
445 445
         {
446 446
             $userstatic=new User($db);
447 447
             $userstatic->fetch($object->user_rappro);
448
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
449
-        	else print $langs->trans("Unknown");
448
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
449
+            else print $langs->trans("Unknown");
450 450
         }
451 451
         if ($usetable) print '</td></tr>';
452 452
         else print '<br>';
@@ -492,8 +492,8 @@  discard block
 block discarded – undo
492 492
  */
493 493
 function dolAddEmailTrackId($email, $trackingid)
494 494
 {
495
-	$tmp=explode('@',$email);
496
-	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
495
+    $tmp=explode('@',$email);
496
+    return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
497 497
 }
498 498
 
499 499
 /**
@@ -619,33 +619,33 @@  discard block
 block discarded – undo
619 619
  */
620 620
 function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
621 621
 {
622
-	if(!isValidEmail($mail))return '';
623
-	$tab = explode('@', $mail);
624
-	$tab2 = explode('.',$tab[1]);
625
-	$string_replace = '';
626
-	$mail_name = $tab[0];
627
-	$mail_domaine = $tab2[0];
628
-	$mail_tld = '';
629
-
630
-	$nbofelem = count($tab2);
631
-	for($i=1; $i < $nbofelem && $displaytld; $i++)
632
-	{
633
-		$mail_tld .= '.'.$tab2[$i];
634
-	}
635
-
636
-	for($i=0; $i < $nbreplace; $i++){
637
-		$string_replace .= $replace;
638
-	}
639
-
640
-	if(strlen($mail_name) > $nbdisplaymail){
641
-		$mail_name = substr($mail_name, 0, $nbdisplaymail);
642
-	}
643
-
644
-	if(strlen($mail_domaine) > $nbdisplaydomain){
645
-		$mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
646
-	}
647
-
648
-	return $mail_name . $string_replace . $mail_domaine . $mail_tld;
622
+    if(!isValidEmail($mail))return '';
623
+    $tab = explode('@', $mail);
624
+    $tab2 = explode('.',$tab[1]);
625
+    $string_replace = '';
626
+    $mail_name = $tab[0];
627
+    $mail_domaine = $tab2[0];
628
+    $mail_tld = '';
629
+
630
+    $nbofelem = count($tab2);
631
+    for($i=1; $i < $nbofelem && $displaytld; $i++)
632
+    {
633
+        $mail_tld .= '.'.$tab2[$i];
634
+    }
635
+
636
+    for($i=0; $i < $nbreplace; $i++){
637
+        $string_replace .= $replace;
638
+    }
639
+
640
+    if(strlen($mail_name) > $nbdisplaymail){
641
+        $mail_name = substr($mail_name, 0, $nbdisplaymail);
642
+    }
643
+
644
+    if(strlen($mail_domaine) > $nbdisplaydomain){
645
+        $mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
646
+    }
647
+
648
+    return $mail_name . $string_replace . $mail_domaine . $mail_tld;
649 649
 }
650 650
 
651 651
 
@@ -783,24 +783,24 @@  discard block
 block discarded – undo
783 783
     }
784 784
     else
785 785
     {
786
-    	$masktype='';
787
-    	$masktype_value='';
786
+        $masktype='';
787
+        $masktype_value='';
788 788
     }
789 789
 
790 790
     // Extract value for user
791 791
     if (preg_match('/\{(u+)\}/i',$mask,$regType))
792 792
     {
793
-    	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
794
-    	if (is_object($objuser)) $lastname = $objuser->lastname;
793
+        $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
794
+        if (is_object($objuser)) $lastname = $objuser->lastname;
795 795
 
796
-    	$maskuser=$regType[1];
797
-    	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
798
-    	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
796
+        $maskuser=$regType[1];
797
+        $maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
798
+        $maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
799 799
     }
800 800
     else
801 801
     {
802
-    	$maskuser='';
803
-    	$maskuser_value='';
802
+        $maskuser='';
803
+        $maskuser_value='';
804 804
     }
805 805
 
806 806
     // Personalized field {XXX-1} à {XXX-9}
@@ -816,12 +816,12 @@  discard block
 block discarded – undo
816 816
 
817 817
     if (strstr($mask,'user_extra_'))
818 818
     {
819
-			$start = "{user_extra_";
820
-			$end = "\}";
821
-			$extra= get_string_between($mask, "user_extra_", "}");
822
-			if(!empty($user->array_options['options_'.$extra])){
823
-				$mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
824
-			}
819
+            $start = "{user_extra_";
820
+            $end = "\}";
821
+            $extra= get_string_between($mask, "user_extra_", "}");
822
+            if(!empty($user->array_options['options_'.$extra])){
823
+                $mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
824
+            }
825 825
     }
826 826
     $maskwithonlyymcode=$mask;
827 827
     $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
         else // if reset is for a specific month in year, we need year
883 883
         {
884 884
             if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
885
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
885
+            else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
886 886
             else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
887 887
             else return 'ErrorCantUseRazIfNoYearInMask';
888 888
         }
@@ -890,11 +890,11 @@  discard block
 block discarded – undo
890 890
         $yearlen = $posy?dol_strlen($reg[$posy]):0;
891 891
         $monthlen = $posm?dol_strlen($reg[$posm]):0;
892 892
         // Define pos
893
-       	$yearpos = (dol_strlen($reg[1])+1);
893
+            $yearpos = (dol_strlen($reg[1])+1);
894 894
         $monthpos = ($yearpos+$yearlen);
895 895
         if ($posy == 3 && $posm == 2) {		// if month is before year
896
-          	$monthpos = (dol_strlen($reg[1])+1);
897
-           	$yearpos = ($monthpos+$monthlen);
896
+                $monthpos = (dol_strlen($reg[1])+1);
897
+                $yearpos = ($monthpos+$monthlen);
898 898
         }
899 899
         //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
900 900
 
@@ -904,20 +904,20 @@  discard block
 block discarded – undo
904 904
 
905 905
         if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
906 906
         {
907
-        	$currentyear=date("Y", $date);
908
-        	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
909
-        	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
910
-        	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
911
-        	//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
912
-
913
-        	// If after or equal of current fiscal date
914
-        	if ($date >= $fiscaldate)
915
-        	{
916
-        		// If before of next new year date
917
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
918
-        	}
919
-        	// If after or equal of current new year date
920
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
907
+            $currentyear=date("Y", $date);
908
+            $fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
909
+            $newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
910
+            $nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
911
+            //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
912
+
913
+            // If after or equal of current fiscal date
914
+            if ($date >= $fiscaldate)
915
+            {
916
+                // If before of next new year date
917
+                if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
918
+            }
919
+            // If after or equal of current new year date
920
+            else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
921 921
         }
922 922
         // For backward compatibility
923 923
         else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
@@ -938,11 +938,11 @@  discard block
 block discarded – undo
938 938
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
939 939
             $sqlwhere.=')';
940 940
         }
941
-		else if ($resetEveryMonth)
942
-		{
943
-			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
941
+        else if ($resetEveryMonth)
942
+        {
943
+            $sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
944 944
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
945
-		}
945
+        }
946 946
         else   // reset is done on january
947 947
         {
948 948
             $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
@@ -953,13 +953,13 @@  discard block
 block discarded – undo
953 953
 
954 954
     // Define $sqlstring
955 955
     if (function_exists('mb_strrpos'))
956
-    	{
957
-    	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
958
-	}
959
-	else
960
-	{
961
-    	$posnumstart=strrpos($maskwithnocode,$maskcounter);
962
-	}	// Pos of counter in final string (from 0 to ...)
956
+        {
957
+        $posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
958
+    }
959
+    else
960
+    {
961
+        $posnumstart=strrpos($maskwithnocode,$maskcounter);
962
+    }	// Pos of counter in final string (from 0 to ...)
963 963
     if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
964 964
     $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
965 965
 
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
     if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
979 979
     foreach($maskperso as $key => $val)
980 980
     {
981
-    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
981
+        $maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
982 982
     }
983 983
 
984 984
     // Get counter in database
@@ -986,11 +986,11 @@  discard block
 block discarded – undo
986 986
     $sql = "SELECT MAX(".$sqlstring.") as val";
987 987
     $sql.= " FROM ".MAIN_DB_PREFIX.$table;
988 988
     $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
989
-	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
989
+    $sql.= " AND ".$field." NOT LIKE '(PROV%)'";
990 990
     if ($bentityon) // only if entity enable
991
-    	$sql.= " AND entity IN (".getEntity($sharetable).")";
991
+        $sql.= " AND entity IN (".getEntity($sharetable).")";
992 992
     else if (! empty($forceentity))
993
-    	$sql.= " AND entity IN (".$forceentity.")";
993
+        $sql.= " AND entity IN (".$forceentity.")";
994 994
     if ($where) $sql.=$where;
995 995
     if ($sqlwhere) $sql.=' AND '.$sqlwhere;
996 996
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
     if (empty($counter)) $counter=$maskoffset;
1009 1009
     else if (preg_match('/[^0-9]/i',$counter))
1010 1010
     {
1011
-    	$counter=0;
1012
-    	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1011
+        $counter=0;
1012
+        dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1013 1013
     }
1014 1014
     else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
1015 1015
 
@@ -1035,11 +1035,11 @@  discard block
 block discarded – undo
1035 1035
         $sql = "SELECT ".$field." as ref";
1036 1036
         $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1037 1037
         $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1038
-    	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1039
-    	if ($bentityon) // only if entity enable
1040
-        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1038
+        $sql.= " AND ".$field." NOT LIKE '%PROV%'";
1039
+        if ($bentityon) // only if entity enable
1040
+            $sql.= " AND entity IN (".getEntity($sharetable).")";
1041 1041
         else if (! empty($forceentity))
1042
-        	$sql.= " AND entity IN (".$forceentity.")";
1042
+            $sql.= " AND entity IN (".$forceentity.")";
1043 1043
         if ($where) $sql.=$where;
1044 1044
         if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1045 1045
 
@@ -1061,7 +1061,7 @@  discard block
 block discarded – undo
1061 1061
         // If value for $counter has a length higher than $maskcounter chars
1062 1062
         if ($counter >= pow(10, dol_strlen($maskcounter)))
1063 1063
         {
1064
-        	$counter='ErrorMaxNumberReachForThisMask';
1064
+            $counter='ErrorMaxNumberReachForThisMask';
1065 1065
         }
1066 1066
 
1067 1067
         if (! empty($maskrefclient_maskcounter))
@@ -1093,9 +1093,9 @@  discard block
 block discarded – undo
1093 1093
             //$sql.= " WHERE ".$field." not like '(%'";
1094 1094
             $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1095 1095
             if ($bentityon) // only if entity enable
1096
-            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1096
+                $maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1097 1097
             else if (! empty($forceentity))
1098
-            	$sql.= " AND entity IN (".$forceentity.")";
1098
+                $sql.= " AND entity IN (".$forceentity.")";
1099 1099
             if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1100 1100
             if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1101 1101
             $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
@@ -1110,25 +1110,25 @@  discard block
 block discarded – undo
1110 1110
             else dol_print_error($db);
1111 1111
 
1112 1112
             if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1113
-			$maskrefclient_counter++;
1113
+            $maskrefclient_counter++;
1114 1114
         }
1115 1115
 
1116 1116
         // Build numFinal
1117 1117
         $numFinal = $mask;
1118 1118
 
1119 1119
         // We replace special codes except refclient
1120
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1121
-		{
1122
-	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1123
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1124
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1125
-		}
1126
-		else	// we want yyyy to be current year
1127
-		{
1128
-        	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1129
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1130
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1131
-		}
1120
+        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1121
+        {
1122
+            $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1123
+            $numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1124
+            $numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1125
+        }
1126
+        else	// we want yyyy to be current year
1127
+        {
1128
+            $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1129
+            $numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1130
+            $numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1131
+        }
1132 1132
         $numFinal = preg_replace('/\{mm\}/i',  date("m",$date), $numFinal);
1133 1133
         $numFinal = preg_replace('/\{dd\}/i',  date("d",$date), $numFinal);
1134 1134
 
@@ -1158,9 +1158,9 @@  discard block
 block discarded – undo
1158 1158
         // Now we replace the user
1159 1159
         if ($maskuser)
1160 1160
         {
1161
-        	$maskuser_maskbefore='{'.$maskuser.'}';
1162
-        	$maskuser_maskafter=$maskuser_value;
1163
-        	$numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1161
+            $maskuser_maskbefore='{'.$maskuser.'}';
1162
+            $maskuser_maskafter=$maskuser_value;
1163
+            $numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1164 1164
         }
1165 1165
     }
1166 1166
 
@@ -1179,11 +1179,11 @@  discard block
 block discarded – undo
1179 1179
 function get_string_between($string, $start, $end)
1180 1180
 {
1181 1181
     $string = " ".$string;
1182
-     $ini = strpos($string,$start);
1183
-     if ($ini == 0) return "";
1184
-     $ini += strlen($start);
1185
-     $len = strpos($string,$end,$ini) - $ini;
1186
-     return substr($string,$ini,$len);
1182
+        $ini = strpos($string,$start);
1183
+        if ($ini == 0) return "";
1184
+        $ini += strlen($start);
1185
+        $len = strpos($string,$end,$ini) - $ini;
1186
+        return substr($string,$ini,$len);
1187 1187
 }
1188 1188
 
1189 1189
 /**
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
     }
1532 1532
     else
1533 1533
     {
1534
-    	$string = vatrate($reduction,true);
1534
+        $string = vatrate($reduction,true);
1535 1535
     }
1536 1536
 
1537 1537
     return $string;
@@ -1624,7 +1624,7 @@  discard block
 block discarded – undo
1624 1624
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1625 1625
                 $dirtoscan= preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1626 1626
 
1627
-		$listoffiles=array();
1627
+        $listoffiles=array();
1628 1628
 
1629 1629
                 // Now we add models found in directories scanned
1630 1630
                 $listofdir=explode(',',$dirtoscan);
@@ -1635,8 +1635,8 @@  discard block
 block discarded – undo
1635 1635
                     if (! $tmpdir) { unset($listofdir[$key]); continue; }
1636 1636
                     if (is_dir($tmpdir))
1637 1637
                     {
1638
-			// all type of template is allowed
1639
-			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1638
+            // all type of template is allowed
1639
+            $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1640 1640
                         if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1641 1641
                     }
1642 1642
                 }
@@ -1692,19 +1692,19 @@  discard block
 block discarded – undo
1692 1692
  */
1693 1693
 function is_ip($ip)
1694 1694
 {
1695
-	// First we test if it is a valid IPv4
1696
-	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1695
+    // First we test if it is a valid IPv4
1696
+    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1697 1697
 
1698
-		// Then we test if it is a private range
1699
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1698
+        // Then we test if it is a private range
1699
+        if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1700 1700
 
1701
-		// Then we test if it is a reserved range
1702
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1701
+        // Then we test if it is a reserved range
1702
+        if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1703 1703
 
1704
-		return 1;
1705
-	}
1704
+        return 1;
1705
+    }
1706 1706
 
1707
-	return 0;
1707
+    return 0;
1708 1708
 }
1709 1709
 
1710 1710
 /**
@@ -1744,25 +1744,25 @@  discard block
 block discarded – undo
1744 1744
     if ($proxyuse)
1745 1745
     {
1746 1746
         $params=array('connection_timeout'=>$timeout,
1747
-                      'response_timeout'=>$response_timeout,
1748
-                      'proxy_use'      => 1,
1749
-                      'proxy_host'     => $proxyhost,
1750
-                      'proxy_port'     => $proxyport,
1751
-                      'proxy_login'    => $proxyuser,
1752
-                      'proxy_password' => $proxypass,
1753
-                      'trace'		   => 1
1747
+                        'response_timeout'=>$response_timeout,
1748
+                        'proxy_use'      => 1,
1749
+                        'proxy_host'     => $proxyhost,
1750
+                        'proxy_port'     => $proxyport,
1751
+                        'proxy_login'    => $proxyuser,
1752
+                        'proxy_password' => $proxypass,
1753
+                        'trace'		   => 1
1754 1754
         );
1755 1755
     }
1756 1756
     else
1757 1757
     {
1758 1758
         $params=array('connection_timeout'=>$timeout,
1759
-                      'response_timeout'=>$response_timeout,
1760
-                      'proxy_use'      => 0,
1761
-                      'proxy_host'     => false,
1762
-                      'proxy_port'     => false,
1763
-                      'proxy_login'    => false,
1764
-                      'proxy_password' => false,
1765
-                      'trace'		   => 1
1759
+                        'response_timeout'=>$response_timeout,
1760
+                        'proxy_use'      => 0,
1761
+                        'proxy_host'     => false,
1762
+                        'proxy_port'     => false,
1763
+                        'proxy_login'    => false,
1764
+                        'proxy_password' => false,
1765
+                        'trace'		   => 1
1766 1766
         );
1767 1767
     }
1768 1768
     return $params;
@@ -1780,118 +1780,118 @@  discard block
 block discarded – undo
1780 1780
  */
1781 1781
 function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
1782 1782
 {
1783
-	global $db, $conf, $langs;
1784
-
1785
-	$ret='';
1786
-
1787
-	// Parse element/subelement (ex: project_task)
1788
-	$module = $element = $subelement = $objecttype;
1789
-	if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1790
-	{
1791
-		$module = $element = $regs[1];
1792
-		$subelement = $regs[2];
1793
-	}
1794
-
1795
-	$classpath = $element.'/class';
1796
-
1797
-	// To work with non standard path
1798
-	if ($objecttype == 'facture' || $objecttype == 'invoice') {
1799
-		$classpath = 'compta/facture/class';
1800
-		$module='facture';
1801
-		$subelement='facture';
1802
-	}
1803
-	if ($objecttype == 'commande' || $objecttype == 'order') {
1804
-		$classpath = 'commande/class';
1805
-		$module='commande';
1806
-		$subelement='commande';
1807
-	}
1808
-	if ($objecttype == 'propal')  {
1809
-		$classpath = 'comm/propal/class';
1810
-	}
1811
-	if ($objecttype == 'supplier_proposal')  {
1812
-		$classpath = 'supplier_proposal/class';
1813
-	}
1814
-	if ($objecttype == 'shipping') {
1815
-		$classpath = 'expedition/class';
1816
-		$subelement = 'expedition';
1817
-		$module = 'expedition_bon';
1818
-	}
1819
-	if ($objecttype == 'delivery') {
1820
-		$classpath = 'livraison/class';
1821
-		$subelement = 'livraison';
1822
-		$module = 'livraison_bon';
1823
-	}
1824
-	if ($objecttype == 'contract') {
1825
-		$classpath = 'contrat/class';
1826
-		$module='contrat';
1827
-		$subelement='contrat';
1828
-	}
1829
-	if ($objecttype == 'member') {
1830
-		$classpath = 'adherents/class';
1831
-		$module='adherent';
1832
-		$subelement='adherent';
1833
-	}
1834
-	if ($objecttype == 'cabinetmed_cons') {
1835
-		$classpath = 'cabinetmed/class';
1836
-		$module='cabinetmed';
1837
-		$subelement='cabinetmedcons';
1838
-	}
1839
-	if ($objecttype == 'fichinter') {
1840
-		$classpath = 'fichinter/class';
1841
-		$module='ficheinter';
1842
-		$subelement='fichinter';
1843
-	}
1844
-	if ($objecttype == 'task') {
1845
-		$classpath = 'projet/class';
1846
-		$module='projet';
1847
-		$subelement='task';
1848
-	}
1849
-	if ($objecttype == 'stock') {
1850
-		$classpath = 'product/stock/class';
1851
-		$module='stock';
1852
-		$subelement='stock';
1853
-	}
1854
-
1855
-	//print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
1856
-
1857
-	$classfile = strtolower($subelement); $classname = ucfirst($subelement);
1858
-	if ($objecttype == 'invoice_supplier') {
1859
-		$classfile = 'fournisseur.facture';
1860
-		$classname='FactureFournisseur';
1861
-		$classpath = 'fourn/class';
1862
-		$module='fournisseur';
1863
-	}
1864
-	elseif ($objecttype == 'order_supplier')   {
1865
-		$classfile = 'fournisseur.commande';
1866
-		$classname='CommandeFournisseur';
1867
-		$classpath = 'fourn/class';
1868
-		$module='fournisseur';
1869
-	}
1870
-	elseif ($objecttype == 'stock')   {
1871
-		$classpath = 'product/stock/class';
1872
-		$classfile='entrepot';
1873
-		$classname='Entrepot';
1874
-	}
1875
-	if (! empty($conf->$module->enabled))
1876
-	{
1877
-		$res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1878
-		if ($res)
1879
-		{
1880
-			if (class_exists($classname))
1881
-			{
1882
-				$object = new $classname($db);
1883
-				$res=$object->fetch($objectid);
1884
-				if ($res > 0) {
1885
-					$ret=$object->getNomUrl($withpicto,$option);
1886
-				} elseif($res==0) {
1887
-					$ret=$langs->trans('Deleted');
1888
-				}
1889
-				unset($object);
1890
-			}
1891
-			else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
1892
-		}
1893
-	}
1894
-	return $ret;
1783
+    global $db, $conf, $langs;
1784
+
1785
+    $ret='';
1786
+
1787
+    // Parse element/subelement (ex: project_task)
1788
+    $module = $element = $subelement = $objecttype;
1789
+    if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1790
+    {
1791
+        $module = $element = $regs[1];
1792
+        $subelement = $regs[2];
1793
+    }
1794
+
1795
+    $classpath = $element.'/class';
1796
+
1797
+    // To work with non standard path
1798
+    if ($objecttype == 'facture' || $objecttype == 'invoice') {
1799
+        $classpath = 'compta/facture/class';
1800
+        $module='facture';
1801
+        $subelement='facture';
1802
+    }
1803
+    if ($objecttype == 'commande' || $objecttype == 'order') {
1804
+        $classpath = 'commande/class';
1805
+        $module='commande';
1806
+        $subelement='commande';
1807
+    }
1808
+    if ($objecttype == 'propal')  {
1809
+        $classpath = 'comm/propal/class';
1810
+    }
1811
+    if ($objecttype == 'supplier_proposal')  {
1812
+        $classpath = 'supplier_proposal/class';
1813
+    }
1814
+    if ($objecttype == 'shipping') {
1815
+        $classpath = 'expedition/class';
1816
+        $subelement = 'expedition';
1817
+        $module = 'expedition_bon';
1818
+    }
1819
+    if ($objecttype == 'delivery') {
1820
+        $classpath = 'livraison/class';
1821
+        $subelement = 'livraison';
1822
+        $module = 'livraison_bon';
1823
+    }
1824
+    if ($objecttype == 'contract') {
1825
+        $classpath = 'contrat/class';
1826
+        $module='contrat';
1827
+        $subelement='contrat';
1828
+    }
1829
+    if ($objecttype == 'member') {
1830
+        $classpath = 'adherents/class';
1831
+        $module='adherent';
1832
+        $subelement='adherent';
1833
+    }
1834
+    if ($objecttype == 'cabinetmed_cons') {
1835
+        $classpath = 'cabinetmed/class';
1836
+        $module='cabinetmed';
1837
+        $subelement='cabinetmedcons';
1838
+    }
1839
+    if ($objecttype == 'fichinter') {
1840
+        $classpath = 'fichinter/class';
1841
+        $module='ficheinter';
1842
+        $subelement='fichinter';
1843
+    }
1844
+    if ($objecttype == 'task') {
1845
+        $classpath = 'projet/class';
1846
+        $module='projet';
1847
+        $subelement='task';
1848
+    }
1849
+    if ($objecttype == 'stock') {
1850
+        $classpath = 'product/stock/class';
1851
+        $module='stock';
1852
+        $subelement='stock';
1853
+    }
1854
+
1855
+    //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
1856
+
1857
+    $classfile = strtolower($subelement); $classname = ucfirst($subelement);
1858
+    if ($objecttype == 'invoice_supplier') {
1859
+        $classfile = 'fournisseur.facture';
1860
+        $classname='FactureFournisseur';
1861
+        $classpath = 'fourn/class';
1862
+        $module='fournisseur';
1863
+    }
1864
+    elseif ($objecttype == 'order_supplier')   {
1865
+        $classfile = 'fournisseur.commande';
1866
+        $classname='CommandeFournisseur';
1867
+        $classpath = 'fourn/class';
1868
+        $module='fournisseur';
1869
+    }
1870
+    elseif ($objecttype == 'stock')   {
1871
+        $classpath = 'product/stock/class';
1872
+        $classfile='entrepot';
1873
+        $classname='Entrepot';
1874
+    }
1875
+    if (! empty($conf->$module->enabled))
1876
+    {
1877
+        $res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1878
+        if ($res)
1879
+        {
1880
+            if (class_exists($classname))
1881
+            {
1882
+                $object = new $classname($db);
1883
+                $res=$object->fetch($objectid);
1884
+                if ($res > 0) {
1885
+                    $ret=$object->getNomUrl($withpicto,$option);
1886
+                } elseif($res==0) {
1887
+                    $ret=$langs->trans('Deleted');
1888
+                }
1889
+                unset($object);
1890
+            }
1891
+            else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
1892
+        }
1893
+    }
1894
+    return $ret;
1895 1895
 }
1896 1896
 
1897 1897
 
@@ -1905,113 +1905,113 @@  discard block
 block discarded – undo
1905 1905
  */
1906 1906
 function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
1907 1907
 {
1908
-	$totalnb=0;
1909
-	$listofid=array();
1910
-	$listofparentid=array();
1911
-
1912
-	// Get list of all id in array listofid and all parents in array listofparentid
1913
-	$sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1914
-	$resql = $db->query($sql);
1915
-	if ($resql)
1916
-	{
1917
-		$num = $db->num_rows($resql);
1918
-		$i = 0;
1919
-		while ($i < $num)
1920
-		{
1921
-			$obj = $db->fetch_object($resql);
1922
-			$listofid[]=$obj->rowid;
1923
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1924
-			$i++;
1925
-		}
1926
-	}
1927
-	else
1928
-	{
1929
-		dol_print_error($db);
1930
-	}
1931
-
1932
-	if (count($listofid))
1933
-	{
1934
-		print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1935
-
1936
-		// Check loops on each other
1937
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1938
-		$resql = $db->query($sql);
1939
-		if ($resql)
1940
-		{
1941
-			$nb=$db->affected_rows($sql);
1942
-			if ($nb > 0)
1943
-			{
1944
-				print '<br>Some record that were parent of themself were cleaned.';
1945
-			}
1946
-
1947
-			$totalnb+=$nb;
1948
-		}
1949
-		//else dol_print_error($db);
1950
-
1951
-		// Check other loops
1952
-		$listofidtoclean=array();
1953
-		foreach($listofparentid as $id => $pid)
1954
-		{
1955
-			// Check depth
1956
-			//print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1957
-
1958
-			$cursor=$id; $arrayidparsed=array();	// We start from child $id
1959
-			while ($cursor > 0)
1960
-			{
1961
-				$arrayidparsed[$cursor]=1;
1962
-				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1963
-				{
1964
-					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1965
-					unset($arrayidparsed);
1966
-					$listofidtoclean[$cursor]=$id;
1967
-					break;
1968
-				}
1969
-				$cursor=$listofparentid[$cursor];
1970
-			}
1971
-
1972
-			if (count($listofidtoclean)) break;
1973
-		}
1974
-
1975
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1976
-		$sql.= " SET ".$fieldfkparent." = 0";
1977
-		$sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1978
-		$resql = $db->query($sql);
1979
-		if ($resql)
1980
-		{
1981
-			$nb=$db->affected_rows($sql);
1982
-			if ($nb > 0)
1983
-			{
1984
-				// Removed orphelins records
1985
-				print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1986
-				print join(',',$listofidtoclean);
1987
-			}
1988
-
1989
-			$totalnb+=$nb;
1990
-		}
1991
-		//else dol_print_error($db);
1992
-
1993
-		// Check and clean orphelins
1994
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1995
-		$sql.= " SET ".$fieldfkparent." = 0";
1996
-		$sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
1997
-		$resql = $db->query($sql);
1998
-		if ($resql)
1999
-		{
2000
-			$nb=$db->affected_rows($sql);
2001
-			if ($nb > 0)
2002
-			{
2003
-				// Removed orphelins records
2004
-				print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2005
-				print join(',',$listofid);
2006
-			}
2007
-
2008
-			$totalnb+=$nb;
2009
-		}
2010
-		//else dol_print_error($db);
2011
-
2012
-		print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
2013
-		return $totalnb;
2014
-	}
1908
+    $totalnb=0;
1909
+    $listofid=array();
1910
+    $listofparentid=array();
1911
+
1912
+    // Get list of all id in array listofid and all parents in array listofparentid
1913
+    $sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1914
+    $resql = $db->query($sql);
1915
+    if ($resql)
1916
+    {
1917
+        $num = $db->num_rows($resql);
1918
+        $i = 0;
1919
+        while ($i < $num)
1920
+        {
1921
+            $obj = $db->fetch_object($resql);
1922
+            $listofid[]=$obj->rowid;
1923
+            if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1924
+            $i++;
1925
+        }
1926
+    }
1927
+    else
1928
+    {
1929
+        dol_print_error($db);
1930
+    }
1931
+
1932
+    if (count($listofid))
1933
+    {
1934
+        print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1935
+
1936
+        // Check loops on each other
1937
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1938
+        $resql = $db->query($sql);
1939
+        if ($resql)
1940
+        {
1941
+            $nb=$db->affected_rows($sql);
1942
+            if ($nb > 0)
1943
+            {
1944
+                print '<br>Some record that were parent of themself were cleaned.';
1945
+            }
1946
+
1947
+            $totalnb+=$nb;
1948
+        }
1949
+        //else dol_print_error($db);
1950
+
1951
+        // Check other loops
1952
+        $listofidtoclean=array();
1953
+        foreach($listofparentid as $id => $pid)
1954
+        {
1955
+            // Check depth
1956
+            //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1957
+
1958
+            $cursor=$id; $arrayidparsed=array();	// We start from child $id
1959
+            while ($cursor > 0)
1960
+            {
1961
+                $arrayidparsed[$cursor]=1;
1962
+                if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1963
+                {
1964
+                    print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1965
+                    unset($arrayidparsed);
1966
+                    $listofidtoclean[$cursor]=$id;
1967
+                    break;
1968
+                }
1969
+                $cursor=$listofparentid[$cursor];
1970
+            }
1971
+
1972
+            if (count($listofidtoclean)) break;
1973
+        }
1974
+
1975
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1976
+        $sql.= " SET ".$fieldfkparent." = 0";
1977
+        $sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1978
+        $resql = $db->query($sql);
1979
+        if ($resql)
1980
+        {
1981
+            $nb=$db->affected_rows($sql);
1982
+            if ($nb > 0)
1983
+            {
1984
+                // Removed orphelins records
1985
+                print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1986
+                print join(',',$listofidtoclean);
1987
+            }
1988
+
1989
+            $totalnb+=$nb;
1990
+        }
1991
+        //else dol_print_error($db);
1992
+
1993
+        // Check and clean orphelins
1994
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1995
+        $sql.= " SET ".$fieldfkparent." = 0";
1996
+        $sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
1997
+        $resql = $db->query($sql);
1998
+        if ($resql)
1999
+        {
2000
+            $nb=$db->affected_rows($sql);
2001
+            if ($nb > 0)
2002
+            {
2003
+                // Removed orphelins records
2004
+                print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2005
+                print join(',',$listofid);
2006
+            }
2007
+
2008
+            $totalnb+=$nb;
2009
+        }
2010
+        //else dol_print_error($db);
2011
+
2012
+        print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
2013
+        return $totalnb;
2014
+    }
2015 2015
 }
2016 2016
 
2017 2017
 /**
@@ -2143,21 +2143,21 @@  discard block
 block discarded – undo
2143 2143
 function fetchObjectByElement($element_id, $element_type, $element_ref='')
2144 2144
 {
2145 2145
     global $conf;
2146
-	global $db,$conf;
2146
+    global $db,$conf;
2147 2147
 
2148 2148
     $element_prop = getElementProperties($element_type);
2149 2149
     if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
2150 2150
     {
2151 2151
         dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
2152 2152
 
2153
-		$objecttmp = new $element_prop['classname']($db);
2154
-		$ret = $objecttmp->fetch($element_id, $element_ref);
2155
-		if ($ret >= 0)
2156
-		{
2157
-			return $objecttmp;
2158
-		}
2159
-	}
2160
-	return 0;
2153
+        $objecttmp = new $element_prop['classname']($db);
2154
+        $ret = $objecttmp->fetch($element_id, $element_ref);
2155
+        if ($ret >= 0)
2156
+        {
2157
+            return $objecttmp;
2158
+        }
2159
+    }
2160
+    return 0;
2161 2161
 }
2162 2162
 
2163 2163
 
@@ -2172,9 +2172,9 @@  discard block
 block discarded – undo
2172 2172
  */
2173 2173
 function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2174 2174
 {
2175
-	if (! is_array($arraycolor)) return $colorifnotfound;
2176
-	if (empty($arraycolor)) return $colorifnotfound;
2177
-	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2175
+    if (! is_array($arraycolor)) return $colorifnotfound;
2176
+    if (empty($arraycolor)) return $colorifnotfound;
2177
+    return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2178 2178
 }
2179 2179
 
2180 2180
 /**
@@ -2189,15 +2189,15 @@  discard block
 block discarded – undo
2189 2189
  */
2190 2190
 function colorStringToArray($stringcolor,$colorifnotfound=array(88,88,88))
2191 2191
 {
2192
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2193
-	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2194
-	if (! $tmp)
2195
-	{
2196
-		$tmp=explode(',',$stringcolor);
2197
-		if (count($tmp) < 3) return $colorifnotfound;
2198
-		return $tmp;
2199
-	}
2200
-	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2192
+    if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2193
+    $tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2194
+    if (! $tmp)
2195
+    {
2196
+        $tmp=explode(',',$stringcolor);
2197
+        if (count($tmp) < 3) return $colorifnotfound;
2198
+        return $tmp;
2199
+    }
2200
+    return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2201 2201
 }
2202 2202
 
2203 2203
 /**
@@ -2243,7 +2243,7 @@  discard block
 block discarded – undo
2243 2243
     if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2244 2244
 
2245 2245
     if ($module == 'contracts') {
2246
-    	$moduledirforclass = 'contrat';
2246
+        $moduledirforclass = 'contrat';
2247 2247
     }
2248 2248
     elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2249 2249
         $moduledirforclass = 'api';
@@ -2270,7 +2270,7 @@  discard block
 block discarded – undo
2270 2270
         $moduledirforclass = 'commande';
2271 2271
     }
2272 2272
     elseif ($module == 'shipments') {
2273
-    	$moduledirforclass = 'expedition';
2273
+        $moduledirforclass = 'expedition';
2274 2274
     }
2275 2275
     elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
2276 2276
         $moduledirforclass = 'compta/facture';
@@ -2288,7 +2288,7 @@  discard block
 block discarded – undo
2288 2288
         $moduledirforclass = 'product/stock';
2289 2289
     }
2290 2290
     elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
2291
-    	$moduledirforclass = 'supplier_proposal';
2291
+        $moduledirforclass = 'supplier_proposal';
2292 2292
     }
2293 2293
     elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
2294 2294
         $moduledirforclass = 'fourn';
@@ -2300,10 +2300,10 @@  discard block
 block discarded – undo
2300 2300
         $moduledirforclass = 'user';
2301 2301
     }
2302 2302
     elseif ($module == 'ficheinter' || $module == 'interventions') {
2303
-    	$moduledirforclass = 'fichinter';
2303
+        $moduledirforclass = 'fichinter';
2304 2304
     }
2305 2305
     elseif ($module == 'tickets') {
2306
-    	$moduledirforclass = 'ticket';
2306
+        $moduledirforclass = 'ticket';
2307 2307
     }
2308 2308
 
2309 2309
     return $moduledirforclass;
Please login to merge, or discard this patch.
Spacing   +548 added lines, -548 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
                 $pos++;
53 53
                 $unicodeHexVal = substr($source, $pos, 4);
54 54
                 $unicode = hexdec($unicodeHexVal);
55
-                $entity = "&#". $unicode . ';';
55
+                $entity = "&#".$unicode.';';
56 56
                 $decodedStr .= utf8_encode($entity);
57 57
                 $pos += 4;
58 58
             }
@@ -78,32 +78,32 @@  discard block
 block discarded – undo
78 78
  * @param	string	$subdir		Sub directory (Example: '/mailings')
79 79
  * @return	array				Array of directories that can contains module descriptors
80 80
  */
81
-function dolGetModulesDirs($subdir='')
81
+function dolGetModulesDirs($subdir = '')
82 82
 {
83 83
     global $conf;
84 84
 
85
-    $modulesdir=array();
85
+    $modulesdir = array();
86 86
 
87 87
     foreach ($conf->file->dol_document_root as $type => $dirroot)
88 88
     {
89 89
         // Default core/modules dir
90 90
         if ($type === 'main') {
91
-            $modulesdir[$dirroot . '/core/modules' . $subdir . '/'] = $dirroot . '/core/modules' . $subdir . '/';
91
+            $modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/';
92 92
         }
93 93
 
94 94
         // Scan dir from external modules
95
-        $handle=@opendir($dirroot);
95
+        $handle = @opendir($dirroot);
96 96
         if (is_resource($handle))
97 97
         {
98
-            while (($file = readdir($handle))!==false)
98
+            while (($file = readdir($handle)) !== false)
99 99
             {
100
-                if (preg_match('/disabled/',$file)) continue;   // We discard module if it contains disabled into name.
100
+                if (preg_match('/disabled/', $file)) continue; // We discard module if it contains disabled into name.
101 101
 
102 102
                 if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
103 103
                 {
104
-                    if (is_dir($dirroot . '/' . $file . '/core/modules'.$subdir.'/'))
104
+                    if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/'))
105 105
                     {
106
-                        $modulesdir[$dirroot . '/' . $file . '/core/modules'.$subdir.'/'] = $dirroot . '/' . $file . '/core/modules'.$subdir.'/';
106
+                        $modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/';
107 107
                     }
108 108
                 }
109 109
             }
@@ -124,13 +124,13 @@  discard block
 block discarded – undo
124 124
 {
125 125
     global $langs;
126 126
 
127
-    $selected='EUA4';
127
+    $selected = 'EUA4';
128 128
     if (!$outputlangs) {
129
-    	$outputlangs=$langs;
129
+    	$outputlangs = $langs;
130 130
     }
131 131
 
132
-    if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
133
-    if ($outputlangs->defaultlang == 'en_US') $selected='USLetter';    // US
132
+    if ($outputlangs->defaultlang == 'ca_CA') $selected = 'CAP4'; // Canada
133
+    if ($outputlangs->defaultlang == 'en_US') $selected = 'USLetter'; // US
134 134
     return $selected;
135 135
 }
136 136
 
@@ -142,20 +142,20 @@  discard block
 block discarded – undo
142 142
  *  @param  int			$searchalt      1=Search also in alternative languages
143 143
  *	@return	boolean						true if OK, false if KO
144 144
  */
145
-function dol_print_file($langs,$filename,$searchalt=0)
145
+function dol_print_file($langs, $filename, $searchalt = 0)
146 146
 {
147 147
     global $conf;
148 148
 
149 149
     // Test if file is in lang directory
150
-    foreach($langs->dir as $searchdir)
150
+    foreach ($langs->dir as $searchdir)
151 151
     {
152
-        $formfile=($searchdir."/langs/".$langs->defaultlang."/".$filename);
152
+        $formfile = ($searchdir."/langs/".$langs->defaultlang."/".$filename);
153 153
         dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
154 154
         if (is_readable($formfile))
155 155
         {
156
-            $content=file_get_contents($formfile);
157
-            $isutf8=utf8_check($content);
158
-            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
156
+            $content = file_get_contents($formfile);
157
+            $isutf8 = utf8_check($content);
158
+            if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
159 159
             elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
160 160
             else print $content;
161 161
             return true;
@@ -170,9 +170,9 @@  discard block
 block discarded – undo
170 170
             //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
171 171
             if (is_readable($formfilealt))
172 172
             {
173
-                $content=file_get_contents($formfilealt);
174
-                $isutf8=utf8_check($content);
175
-                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
173
+                $content = file_get_contents($formfilealt);
174
+                $isutf8 = utf8_check($content);
175
+                if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
176 176
                 elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
177 177
                 else print $content;
178 178
                 return true;
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
  *  @param  int     $usetable       Output into a table
193 193
  *	@return	void
194 194
  */
195
-function dol_print_object_info($object, $usetable=0)
195
+function dol_print_object_info($object, $usetable = 0)
196 196
 {
197 197
     global $langs, $db;
198 198
 
@@ -201,16 +201,16 @@  discard block
 block discarded – undo
201 201
 
202 202
     include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
203 203
 
204
-    $deltadateforserver=getServerTimeZoneInt('now');
205
-    $deltadateforclient=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
204
+    $deltadateforserver = getServerTimeZoneInt('now');
205
+    $deltadateforclient = ((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
206 206
     //$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
207
-    $deltadateforuser=round($deltadateforclient-$deltadateforserver);
207
+    $deltadateforuser = round($deltadateforclient - $deltadateforserver);
208 208
     //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
209 209
 
210 210
     if ($usetable) print '<table class="border centpercent">';
211 211
 
212 212
     // Import key
213
-    if (! empty($object->import_key))
213
+    if (!empty($object->import_key))
214 214
     {
215 215
         if ($usetable) print '<tr><td class="titlefield">';
216 216
         print $langs->trans("ImportedWithSet");
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
     }
223 223
 
224 224
     // User creation (old method using already loaded object and not id is kept for backward compatibility)
225
-    if (! empty($object->user_creation) || ! empty($object->user_creation_id))
225
+    if (!empty($object->user_creation) || !empty($object->user_creation_id))
226 226
     {
227 227
         if ($usetable) print '<tr><td class="titlefield">';
228 228
         print $langs->trans("CreatedBy");
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
         }
236 236
         else
237 237
         {
238
-            $userstatic=new User($db);
238
+            $userstatic = new User($db);
239 239
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
240 240
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
241 241
         	else print $langs->trans("Unknown");
@@ -245,20 +245,20 @@  discard block
 block discarded – undo
245 245
     }
246 246
 
247 247
     // Date creation
248
-    if (! empty($object->date_creation))
248
+    if (!empty($object->date_creation))
249 249
     {
250 250
         if ($usetable) print '<tr><td class="titlefield">';
251 251
         print $langs->trans("DateCreation");
252 252
         if ($usetable) print '</td><td>';
253 253
         else print ': ';
254 254
         print dol_print_date($object->date_creation, 'dayhour');
255
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
255
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
256 256
         if ($usetable) print '</td></tr>';
257 257
         else print '<br>';
258 258
     }
259 259
 
260 260
     // User change (old method using already loaded object and not id is kept for backward compatibility)
261
-    if (! empty($object->user_modification) || ! empty($object->user_modification_id))
261
+    if (!empty($object->user_modification) || !empty($object->user_modification_id))
262 262
     {
263 263
         if ($usetable) print '<tr><td class="titlefield">';
264 264
         print $langs->trans("ModifiedBy");
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
         }
272 272
         else
273 273
         {
274
-            $userstatic=new User($db);
274
+            $userstatic = new User($db);
275 275
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
276 276
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
277 277
         	else print $langs->trans("Unknown");
@@ -281,20 +281,20 @@  discard block
 block discarded – undo
281 281
     }
282 282
 
283 283
     // Date change
284
-    if (! empty($object->date_modification))
284
+    if (!empty($object->date_modification))
285 285
     {
286 286
         if ($usetable) print '<tr><td class="titlefield">';
287 287
         print $langs->trans("DateLastModification");
288 288
         if ($usetable) print '</td><td>';
289 289
         else print ': ';
290 290
         print dol_print_date($object->date_modification, 'dayhour');
291
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
291
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
292 292
         if ($usetable) print '</td></tr>';
293 293
         else print '<br>';
294 294
     }
295 295
 
296 296
     // User validation (old method using already loaded object and not id is kept for backward compatibility)
297
-    if (! empty($object->user_validation) || ! empty($object->user_validation_id))
297
+    if (!empty($object->user_validation) || !empty($object->user_validation_id))
298 298
     {
299 299
         if ($usetable) print '<tr><td class="titlefield">';
300 300
         print $langs->trans("ValidatedBy");
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
         }
308 308
         else
309 309
         {
310
-            $userstatic=new User($db);
310
+            $userstatic = new User($db);
311 311
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
312 312
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
313 313
         	else print $langs->trans("Unknown");
@@ -317,20 +317,20 @@  discard block
 block discarded – undo
317 317
     }
318 318
 
319 319
     // Date validation
320
-    if (! empty($object->date_validation))
320
+    if (!empty($object->date_validation))
321 321
     {
322 322
         if ($usetable) print '<tr><td class="titlefield">';
323 323
         print $langs->trans("DateValidation");
324 324
         if ($usetable) print '</td><td>';
325 325
         else print ': ';
326 326
         print dol_print_date($object->date_validation, 'dayhour');
327
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
327
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
328 328
         if ($usetable) print '</td></tr>';
329 329
         else print '<br>';
330 330
     }
331 331
 
332 332
     // User approve (old method using already loaded object and not id is kept for backward compatibility)
333
-    if (! empty($object->user_approve) || ! empty($object->user_approve_id))
333
+    if (!empty($object->user_approve) || !empty($object->user_approve_id))
334 334
     {
335 335
         if ($usetable) print '<tr><td class="titlefield">';
336 336
         print $langs->trans("ApprovedBy");
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
         }
344 344
         else
345 345
         {
346
-            $userstatic=new User($db);
346
+            $userstatic = new User($db);
347 347
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
348 348
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
349 349
         	else print $langs->trans("Unknown");
@@ -353,26 +353,26 @@  discard block
 block discarded – undo
353 353
     }
354 354
 
355 355
     // Date approve
356
-    if (! empty($object->date_approve))
356
+    if (!empty($object->date_approve))
357 357
     {
358 358
         if ($usetable) print '<tr><td class="titlefield">';
359 359
         print $langs->trans("DateApprove");
360 360
         if ($usetable) print '</td><td>';
361 361
         else print ': ';
362 362
         print dol_print_date($object->date_approve, 'dayhour');
363
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
363
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
364 364
         if ($usetable) print '</td></tr>';
365 365
         else print '<br>';
366 366
     }
367 367
 
368 368
     // User approve
369
-    if (! empty($object->user_approve_id2))
369
+    if (!empty($object->user_approve_id2))
370 370
     {
371 371
         if ($usetable) print '<tr><td class="titlefield">';
372 372
         print $langs->trans("ApprovedBy");
373 373
         if ($usetable) print '</td><td>';
374 374
         else print ': ';
375
-        $userstatic=new User($db);
375
+        $userstatic = new User($db);
376 376
         $userstatic->fetch($object->user_approve_id2);
377 377
         if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
378 378
         else print $langs->trans("Unknown");
@@ -381,20 +381,20 @@  discard block
 block discarded – undo
381 381
     }
382 382
 
383 383
     // Date approve
384
-    if (! empty($object->date_approve2))
384
+    if (!empty($object->date_approve2))
385 385
     {
386 386
         if ($usetable) print '<tr><td class="titlefield">';
387 387
         print $langs->trans("DateApprove2");
388 388
         if ($usetable) print '</td><td>';
389 389
         else print ': ';
390 390
         print dol_print_date($object->date_approve2, 'dayhour');
391
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
391
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2 + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
392 392
         if ($usetable) print '</td></tr>';
393 393
         else print '<br>';
394 394
     }
395 395
 
396 396
     // User close
397
-    if (! empty($object->user_cloture))
397
+    if (!empty($object->user_cloture))
398 398
     {
399 399
         if ($usetable) print '<tr><td class="titlefield">';
400 400
         print $langs->trans("ClosedBy");
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
         }
408 408
         else
409 409
         {
410
-            $userstatic=new User($db);
410
+            $userstatic = new User($db);
411 411
             $userstatic->fetch($object->user_cloture);
412 412
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
413 413
         	else print $langs->trans("Unknown");
@@ -417,20 +417,20 @@  discard block
 block discarded – undo
417 417
     }
418 418
 
419 419
     // Date close
420
-    if (! empty($object->date_cloture))
420
+    if (!empty($object->date_cloture))
421 421
     {
422 422
         if ($usetable) print '<tr><td class="titlefield">';
423 423
         print $langs->trans("DateClosing");
424 424
         if ($usetable) print '</td><td>';
425 425
         else print ': ';
426 426
         print dol_print_date($object->date_cloture, 'dayhour');
427
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
427
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
428 428
         if ($usetable) print '</td></tr>';
429 429
         else print '<br>';
430 430
     }
431 431
 
432 432
     // User conciliate
433
-    if (! empty($object->user_rappro))
433
+    if (!empty($object->user_rappro))
434 434
     {
435 435
         if ($usetable) print '<tr><td class="titlefield">';
436 436
         print $langs->trans("ConciliatedBy");
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
         }
444 444
         else
445 445
         {
446
-            $userstatic=new User($db);
446
+            $userstatic = new User($db);
447 447
             $userstatic->fetch($object->user_rappro);
448 448
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
449 449
         	else print $langs->trans("Unknown");
@@ -453,27 +453,27 @@  discard block
 block discarded – undo
453 453
     }
454 454
 
455 455
     // Date conciliate
456
-    if (! empty($object->date_rappro))
456
+    if (!empty($object->date_rappro))
457 457
     {
458 458
         if ($usetable) print '<tr><td class="titlefield">';
459 459
         print $langs->trans("DateConciliating");
460 460
         if ($usetable) print '</td><td>';
461 461
         else print ': ';
462 462
         print dol_print_date($object->date_rappro, 'dayhour');
463
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
463
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
464 464
         if ($usetable) print '</td></tr>';
465 465
         else print '<br>';
466 466
     }
467 467
 
468 468
     // Date send
469
-    if (! empty($object->date_envoi))
469
+    if (!empty($object->date_envoi))
470 470
     {
471 471
         if ($usetable) print '<tr><td class="titlefield">';
472 472
         print $langs->trans("DateLastSend");
473 473
         if ($usetable) print '</td><td>';
474 474
         else print ': ';
475 475
         print dol_print_date($object->date_envoi, 'dayhour');
476
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
476
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
477 477
         if ($usetable) print '</td></tr>';
478 478
         else print '<br>';
479 479
     }
@@ -492,8 +492,8 @@  discard block
 block discarded – undo
492 492
  */
493 493
 function dolAddEmailTrackId($email, $trackingid)
494 494
 {
495
-	$tmp=explode('@',$email);
496
-	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
495
+	$tmp = explode('@', $email);
496
+	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : '');
497 497
 }
498 498
 
499 499
 /**
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
  *  @param  int		$anchor		1: verify anchor is provided, 0: not verify anchor
529 529
  *	@return int					1=Check is OK, 0=Check is KO
530 530
  */
531
-function isValidUrl($url,$http=0,$pass=0,$port=0,$path=0,$query=0,$anchor=0)
531
+function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
532 532
 {
533 533
     $ValidUrl = 0;
534 534
     $urlregex = '';
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
     // HOSTNAME OR IP
543 543
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // x allowed (ex. http://localhost, http://routerlogin)
544 544
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+";  // x.x
545
-    $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*";  // x ou x.xx (2 x ou plus)
545
+    $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
546 546
     //use only one of the above
547 547
 
548 548
     // PORT
@@ -571,33 +571,33 @@  discard block
 block discarded – undo
571 571
  *	@param  integer	$http		1 = keep both http:// and https://, 0: remove http:// but not https://
572 572
  *	@return string				Cleaned url
573 573
  */
574
-function clean_url($url,$http=1)
574
+function clean_url($url, $http = 1)
575 575
 {
576 576
     // Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
577 577
     // To include the minus sign in a char class, we must not escape it but put it at the end of the class
578 578
     // Also, there's no need of escape a dot sign in a class
579
-    if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i',$url,$regs))
579
+    if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs))
580 580
     {
581
-        $proto=$regs[1];
582
-        $domain=$regs[2];
583
-        $port=isset($regs[3])?$regs[3]:'';
581
+        $proto = $regs[1];
582
+        $domain = $regs[2];
583
+        $port = isset($regs[3]) ? $regs[3] : '';
584 584
         //print $url." -> ".$proto." - ".$domain." - ".$port;
585 585
         //$url = dol_string_nospecial(trim($url));
586 586
         $url = trim($url);
587 587
 
588 588
         // Si http: defini on supprime le http (Si https on ne supprime pas)
589
-        $newproto=$proto;
590
-        if ($http==0)
589
+        $newproto = $proto;
590
+        if ($http == 0)
591 591
         {
592
-            if (preg_match('/^http:[\\/]+/i',$url))
592
+            if (preg_match('/^http:[\\/]+/i', $url))
593 593
             {
594
-                $url = preg_replace('/^http:[\\/]+/i','',$url);
594
+                $url = preg_replace('/^http:[\\/]+/i', '', $url);
595 595
                 $newproto = '';
596 596
             }
597 597
         }
598 598
 
599 599
         // On passe le nom de domaine en minuscule
600
-        $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
600
+        $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
601 601
 
602 602
         return $CleanUrl;
603 603
     }
@@ -617,35 +617,35 @@  discard block
 block discarded – undo
617 617
  * 	@param 		bool		$displaytld			Display tld (default: true)
618 618
  * 	@return		string							Return email with hidden parts or '';
619 619
  */
620
-function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
620
+function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
621 621
 {
622
-	if(!isValidEmail($mail))return '';
622
+	if (!isValidEmail($mail))return '';
623 623
 	$tab = explode('@', $mail);
624
-	$tab2 = explode('.',$tab[1]);
624
+	$tab2 = explode('.', $tab[1]);
625 625
 	$string_replace = '';
626 626
 	$mail_name = $tab[0];
627 627
 	$mail_domaine = $tab2[0];
628 628
 	$mail_tld = '';
629 629
 
630 630
 	$nbofelem = count($tab2);
631
-	for($i=1; $i < $nbofelem && $displaytld; $i++)
631
+	for ($i = 1; $i < $nbofelem && $displaytld; $i++)
632 632
 	{
633 633
 		$mail_tld .= '.'.$tab2[$i];
634 634
 	}
635 635
 
636
-	for($i=0; $i < $nbreplace; $i++){
636
+	for ($i = 0; $i < $nbreplace; $i++) {
637 637
 		$string_replace .= $replace;
638 638
 	}
639 639
 
640
-	if(strlen($mail_name) > $nbdisplaymail){
640
+	if (strlen($mail_name) > $nbdisplaymail) {
641 641
 		$mail_name = substr($mail_name, 0, $nbdisplaymail);
642 642
 	}
643 643
 
644
-	if(strlen($mail_domaine) > $nbdisplaydomain){
645
-		$mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
644
+	if (strlen($mail_domaine) > $nbdisplaydomain) {
645
+		$mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
646 646
 	}
647 647
 
648
-	return $mail_name . $string_replace . $mail_domaine . $mail_tld;
648
+	return $mail_name.$string_replace.$mail_domaine.$mail_tld;
649 649
 }
650 650
 
651 651
 
@@ -658,14 +658,14 @@  discard block
 block discarded – undo
658 658
  * 	@param	string	$tdoptions	Options for td
659 659
  * 	@return	string
660 660
  */
661
-function array2tr($data,$troptions='',$tdoptions='')
661
+function array2tr($data, $troptions = '', $tdoptions = '')
662 662
 {
663
-    $text = '<tr '.$troptions.'>' ;
664
-    foreach($data as $key => $item){
665
-        $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
663
+    $text = '<tr '.$troptions.'>';
664
+    foreach ($data as $key => $item) {
665
+        $text .= '<td '.$tdoptions.'>'.$item.'</td>';
666 666
     }
667
-    $text.= '</tr>' ;
668
-    return $text ;
667
+    $text .= '</tr>';
668
+    return $text;
669 669
 }
670 670
 
671 671
 /**
@@ -678,22 +678,22 @@  discard block
 block discarded – undo
678 678
  * 	@param	string	$tdoptions		Options for td
679 679
  * 	@return	string
680 680
  */
681
-function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
681
+function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
682 682
 {
683
-    $text='' ;
684
-    if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
685
-    foreach($data as $key => $item){
686
-        if(is_array($item)){
687
-            $text.=array2tr($item,$troptions,$tdoptions);
683
+    $text = '';
684
+    if ($tableMarkup) $text = '<table '.$tableoptions.'>';
685
+    foreach ($data as $key => $item) {
686
+        if (is_array($item)) {
687
+            $text .= array2tr($item, $troptions, $tdoptions);
688 688
         } else {
689
-            $text.= '<tr '.$troptions.'>' ;
690
-            $text.= '<td '.$tdoptions.'>'.$key.'</td>' ;
691
-            $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
692
-            $text.= '</tr>' ;
689
+            $text .= '<tr '.$troptions.'>';
690
+            $text .= '<td '.$tdoptions.'>'.$key.'</td>';
691
+            $text .= '<td '.$tdoptions.'>'.$item.'</td>';
692
+            $text .= '</tr>';
693 693
         }
694 694
     }
695
-    if($tableMarkup) $text.= '</table>' ;
696
-    return $text ;
695
+    if ($tableMarkup) $text .= '</table>';
696
+    return $text;
697 697
 }
698 698
 
699 699
 /**
@@ -712,19 +712,19 @@  discard block
 block discarded – undo
712 712
  * @param	int			$forceentity	Entity id to force
713 713
  * @return 	string						New value (numeric) or error message
714 714
  */
715
-function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$mode='next', $bentityon=true, $objuser=null, $forceentity=null)
715
+function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null)
716 716
 {
717
-    global $conf,$user;
717
+    global $conf, $user;
718 718
 
719
-    if (! is_object($objsoc)) $valueforccc=$objsoc;
720
-    else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
721
-    else $valueforccc=$objsoc->code_client;
719
+    if (!is_object($objsoc)) $valueforccc = $objsoc;
720
+    else if ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = $objsoc->code_fournisseur;
721
+    else $valueforccc = $objsoc->code_client;
722 722
 
723 723
     $sharetable = $table;
724 724
     if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
725 725
 
726 726
     // Clean parameters
727
-    if ($date == '') $date=dol_now();	// We use local year and month of PHP server to search numbers
727
+    if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers
728 728
     // but we should use local year and month of user
729 729
 
730 730
     // For debugging
@@ -734,132 +734,132 @@  discard block
 block discarded – undo
734 734
     //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
735 735
     //$date=dol_stringtotime('20130101');
736 736
 
737
-    $hasglobalcounter=false;
737
+    $hasglobalcounter = false;
738 738
     // Extract value for mask counter, mask raz and mask offset
739
-    if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$mask,$reg))
739
+    if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg))
740 740
     {
741
-        $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
742
-        $maskcounter=$reg[1];
743
-        $hasglobalcounter=true;
741
+        $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
742
+        $maskcounter = $reg[1];
743
+        $hasglobalcounter = true;
744 744
     }
745 745
     else
746 746
     {
747 747
         // setting some defaults so the rest of the code won't fail if there is a third party counter
748
-        $masktri='00000';
749
-        $maskcounter='00000';
748
+        $masktri = '00000';
749
+        $maskcounter = '00000';
750 750
     }
751 751
 
752
-    $maskraz=-1;
753
-    $maskoffset=0;
754
-    $resetEveryMonth=false;
752
+    $maskraz = -1;
753
+    $maskoffset = 0;
754
+    $resetEveryMonth = false;
755 755
     if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
756 756
 
757 757
     // Extract value for third party mask counter
758
-    if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
758
+    if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
759 759
     {
760
-        $maskrefclient=$regClientRef[1].$regClientRef[2];
761
-        $maskrefclient_maskclientcode=$regClientRef[1];
762
-        $maskrefclient_maskcounter=$regClientRef[2];
763
-        $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
764
-        $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
765
-        $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
766
-        $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
760
+        $maskrefclient = $regClientRef[1].$regClientRef[2];
761
+        $maskrefclient_maskclientcode = $regClientRef[1];
762
+        $maskrefclient_maskcounter = $regClientRef[2];
763
+        $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
764
+        $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
765
+        $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
766
+        $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
767 767
         if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
768 768
     }
769
-    else $maskrefclient='';
769
+    else $maskrefclient = '';
770 770
 
771 771
     // fail if there is neither a global nor a third party counter
772
-    if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
772
+    if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
773 773
     {
774 774
         return 'ErrorBadMask';
775 775
     }
776 776
 
777 777
     // Extract value for third party type
778
-    if (preg_match('/\{(t+)\}/i',$mask,$regType))
778
+    if (preg_match('/\{(t+)\}/i', $mask, $regType))
779 779
     {
780
-        $masktype=$regType[1];
781
-        $masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
782
-        $masktype_value=str_pad($masktype_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
780
+        $masktype = $regType[1];
781
+        $masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdpaty typent_code (where n is length in mask)
782
+        $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
783 783
     }
784 784
     else
785 785
     {
786
-    	$masktype='';
787
-    	$masktype_value='';
786
+    	$masktype = '';
787
+    	$masktype_value = '';
788 788
     }
789 789
 
790 790
     // Extract value for user
791
-    if (preg_match('/\{(u+)\}/i',$mask,$regType))
791
+    if (preg_match('/\{(u+)\}/i', $mask, $regType))
792 792
     {
793 793
     	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
794 794
     	if (is_object($objuser)) $lastname = $objuser->lastname;
795 795
 
796
-    	$maskuser=$regType[1];
797
-    	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
798
-    	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
796
+    	$maskuser = $regType[1];
797
+    	$maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask)
798
+    	$maskuser_value = str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
799 799
     }
800 800
     else
801 801
     {
802
-    	$maskuser='';
803
-    	$maskuser_value='';
802
+    	$maskuser = '';
803
+    	$maskuser_value = '';
804 804
     }
805 805
 
806 806
     // Personalized field {XXX-1} à {XXX-9}
807
-    $maskperso=array();
808
-    $maskpersonew=array();
809
-    $tmpmask=$mask;
810
-    while (preg_match('/\{([A-Z]+)\-([1-9])\}/',$tmpmask,$regKey))
807
+    $maskperso = array();
808
+    $maskpersonew = array();
809
+    $tmpmask = $mask;
810
+    while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey))
811 811
     {
812
-        $maskperso[$regKey[1]]='{'.$regKey[1].'-'.$regKey[2].'}';
813
-        $maskpersonew[$regKey[1]]=str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
814
-        $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
812
+        $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
813
+        $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
814
+        $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
815 815
     }
816 816
 
817
-    if (strstr($mask,'user_extra_'))
817
+    if (strstr($mask, 'user_extra_'))
818 818
     {
819 819
 			$start = "{user_extra_";
820 820
 			$end = "\}";
821
-			$extra= get_string_between($mask, "user_extra_", "}");
822
-			if(!empty($user->array_options['options_'.$extra])){
823
-				$mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
821
+			$extra = get_string_between($mask, "user_extra_", "}");
822
+			if (!empty($user->array_options['options_'.$extra])) {
823
+				$mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
824 824
 			}
825 825
     }
826
-    $maskwithonlyymcode=$mask;
827
-    $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
828
-    $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
829
-    $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
830
-    $maskwithonlyymcode=preg_replace('/\{(t+)\}/i',$masktype_value,$maskwithonlyymcode);
831
-    $maskwithonlyymcode=preg_replace('/\{(u+)\}/i',$maskuser_value,$maskwithonlyymcode);
832
-    foreach($maskperso as $key => $val)
826
+    $maskwithonlyymcode = $mask;
827
+    $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
828
+    $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
829
+    $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
830
+    $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
831
+    $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
832
+    foreach ($maskperso as $key => $val)
833 833
     {
834
-        $maskwithonlyymcode=preg_replace('/'.preg_quote($val,'/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
834
+        $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
835 835
     }
836
-    $maskwithnocode=$maskwithonlyymcode;
837
-    $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
838
-    $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
839
-    $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
840
-    $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
836
+    $maskwithnocode = $maskwithonlyymcode;
837
+    $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
838
+    $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
839
+    $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
840
+    $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
841 841
     // Now maskwithnocode = 0000ddmmyyyyccc for example
842 842
     // and maskcounter    = 0000 for example
843 843
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
844 844
     //var_dump($reg);
845 845
 
846 846
     // If an offset is asked
847
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
848
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
847
+    if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
848
+    if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
849 849
 
850 850
     // Define $sqlwhere
851
-    $sqlwhere='';
852
-    $yearoffset=0;	// Use year of current $date by default
853
-    $yearoffsettype=false;		// false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
851
+    $sqlwhere = '';
852
+    $yearoffset = 0; // Use year of current $date by default
853
+    $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
854 854
 
855 855
     // If a restore to zero after a month is asked we check if there is already a value for this year.
856
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))	$yearoffsettype = preg_replace('/^@/','',$reg[2]);
857
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))	$yearoffsettype = preg_replace('/^@/','',$reg[3]);
856
+    if (!empty($reg[2]) && preg_match('/^@/', $reg[2]))	$yearoffsettype = preg_replace('/^@/', '', $reg[2]);
857
+    if (!empty($reg[3]) && preg_match('/^@/', $reg[3]))	$yearoffsettype = preg_replace('/^@/', '', $reg[3]);
858 858
 
859 859
     //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
860 860
     if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
861
-        $maskraz=$yearoffsettype; // For backward compatibility
862
-    else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
861
+        $maskraz = $yearoffsettype; // For backward compatibility
862
+    else if ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
863 863
         $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
864 864
     //print "maskraz=".$maskraz;	// -1=no reset
865 865
 
@@ -873,79 +873,79 @@  discard block
 block discarded – undo
873 873
         // Define posy, posm and reg
874 874
         if ($maskraz > 1)	// if reset is not first month, we need month and year into mask
875 875
         {
876
-            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
877
-            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
876
+            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
877
+            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
878 878
             else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
879 879
 
880 880
             if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
881 881
         }
882 882
         else // if reset is for a specific month in year, we need year
883 883
         {
884
-            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
885
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
886
-            else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
884
+            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
885
+        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
886
+            else if (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; }
887 887
             else return 'ErrorCantUseRazIfNoYearInMask';
888 888
         }
889 889
         // Define length
890
-        $yearlen = $posy?dol_strlen($reg[$posy]):0;
891
-        $monthlen = $posm?dol_strlen($reg[$posm]):0;
890
+        $yearlen = $posy ?dol_strlen($reg[$posy]) : 0;
891
+        $monthlen = $posm ?dol_strlen($reg[$posm]) : 0;
892 892
         // Define pos
893
-       	$yearpos = (dol_strlen($reg[1])+1);
894
-        $monthpos = ($yearpos+$yearlen);
893
+       	$yearpos = (dol_strlen($reg[1]) + 1);
894
+        $monthpos = ($yearpos + $yearlen);
895 895
         if ($posy == 3 && $posm == 2) {		// if month is before year
896
-          	$monthpos = (dol_strlen($reg[1])+1);
897
-           	$yearpos = ($monthpos+$monthlen);
896
+          	$monthpos = (dol_strlen($reg[1]) + 1);
897
+           	$yearpos = ($monthpos + $monthlen);
898 898
         }
899 899
         //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
900 900
 
901 901
         // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
902
-        $monthcomp=$maskraz;
903
-        $yearcomp=0;
902
+        $monthcomp = $maskraz;
903
+        $yearcomp = 0;
904 904
 
905
-        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
905
+        if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
906 906
         {
907
-        	$currentyear=date("Y", $date);
908
-        	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
909
-        	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
910
-        	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
907
+        	$currentyear = date("Y", $date);
908
+        	$fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear);
909
+        	$newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear);
910
+        	$nextnewyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear + 1);
911 911
         	//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
912 912
 
913 913
         	// If after or equal of current fiscal date
914 914
         	if ($date >= $fiscaldate)
915 915
         	{
916 916
         		// If before of next new year date
917
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
917
+        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1;
918 918
         	}
919 919
         	// If after or equal of current new year date
920
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
920
+        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1;
921 921
         }
922 922
         // For backward compatibility
923
-        else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
923
+        else if (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; }	// If current month lower that month of return to zero, year is previous year
924 924
 
925
-        if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
926
-        elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
927
-        elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
925
+        if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
926
+        elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
927
+        elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset;
928 928
         if ($monthcomp > 1 && empty($resetEveryMonth))	// Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
929 929
         {
930
-            if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
931
-            elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
932
-
933
-            $sqlwhere.="(";
934
-            $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
935
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
936
-            $sqlwhere.=" OR";
937
-            $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
938
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
939
-            $sqlwhere.=')';
930
+            if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
931
+            elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
932
+
933
+            $sqlwhere .= "(";
934
+            $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
935
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
936
+            $sqlwhere .= " OR";
937
+            $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
938
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
939
+            $sqlwhere .= ')';
940 940
         }
941 941
 		else if ($resetEveryMonth)
942 942
 		{
943
-			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
944
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
943
+			$sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
944
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
945 945
 		}
946 946
         else   // reset is done on january
947 947
         {
948
-            $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
948
+            $sqlwhere .= '(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
949 949
         }
950 950
     }
951 951
     //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n";	// sqlwhere and yearcomp defined only if we ask a reset
@@ -954,49 +954,49 @@  discard block
 block discarded – undo
954 954
     // Define $sqlstring
955 955
     if (function_exists('mb_strrpos'))
956 956
     	{
957
-    	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
957
+    	$posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8');
958 958
 	}
959 959
 	else
960 960
 	{
961
-    	$posnumstart=strrpos($maskwithnocode,$maskcounter);
961
+    	$posnumstart = strrpos($maskwithnocode, $maskcounter);
962 962
 	}	// Pos of counter in final string (from 0 to ...)
963 963
     if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
964
-    $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
964
+    $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')';
965 965
 
966 966
     // Define $maskLike
967 967
     $maskLike = dol_string_nospecial($mask);
968
-    $maskLike = str_replace("%","_",$maskLike);
968
+    $maskLike = str_replace("%", "_", $maskLike);
969 969
     // Replace protected special codes with matching number of _ as wild card caracter
970
-    $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
971
-    $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
972
-    $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
973
-    $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
974
-    $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
975
-    $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
976
-    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
977
-    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
978
-    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
979
-    foreach($maskperso as $key => $val)
970
+    $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
971
+    $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
972
+    $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
973
+    $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
974
+    $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
975
+    $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
976
+    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
977
+    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
978
+    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
979
+    foreach ($maskperso as $key => $val)
980 980
     {
981
-    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
981
+    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
982 982
     }
983 983
 
984 984
     // Get counter in database
985
-    $counter=0;
985
+    $counter = 0;
986 986
     $sql = "SELECT MAX(".$sqlstring.") as val";
987
-    $sql.= " FROM ".MAIN_DB_PREFIX.$table;
988
-    $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
989
-	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
987
+    $sql .= " FROM ".MAIN_DB_PREFIX.$table;
988
+    $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
989
+	$sql .= " AND ".$field." NOT LIKE '(PROV%)'";
990 990
     if ($bentityon) // only if entity enable
991
-    	$sql.= " AND entity IN (".getEntity($sharetable).")";
992
-    else if (! empty($forceentity))
993
-    	$sql.= " AND entity IN (".$forceentity.")";
994
-    if ($where) $sql.=$where;
995
-    if ($sqlwhere) $sql.=' AND '.$sqlwhere;
991
+    	$sql .= " AND entity IN (".getEntity($sharetable).")";
992
+    else if (!empty($forceentity))
993
+    	$sql .= " AND entity IN (".$forceentity.")";
994
+    if ($where) $sql .= $where;
995
+    if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
996 996
 
997 997
     //print $sql.'<br>';
998 998
     dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
999
-    $resql=$db->query($sql);
999
+    $resql = $db->query($sql);
1000 1000
     if ($resql)
1001 1001
     {
1002 1002
         $obj = $db->fetch_object($resql);
@@ -1005,46 +1005,46 @@  discard block
 block discarded – undo
1005 1005
     else dol_print_error($db);
1006 1006
 
1007 1007
     // Check if we must force counter to maskoffset
1008
-    if (empty($counter)) $counter=$maskoffset;
1009
-    else if (preg_match('/[^0-9]/i',$counter))
1008
+    if (empty($counter)) $counter = $maskoffset;
1009
+    else if (preg_match('/[^0-9]/i', $counter))
1010 1010
     {
1011
-    	$counter=0;
1011
+    	$counter = 0;
1012 1012
     	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1013 1013
     }
1014
-    else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
1014
+    else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter = $maskoffset;
1015 1015
 
1016 1016
     if ($mode == 'last')	// We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1017 1017
     {
1018
-        $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1018
+        $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1019 1019
 
1020 1020
         // Define $maskLike
1021 1021
         $maskLike = dol_string_nospecial($mask);
1022
-        $maskLike = str_replace("%","_",$maskLike);
1022
+        $maskLike = str_replace("%", "_", $maskLike);
1023 1023
         // Replace protected special codes with matching number of _ as wild card caracter
1024
-        $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
1025
-        $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
1026
-        $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
1027
-        $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
1028
-        $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
1029
-        $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
1030
-        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1031
-        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1032
-        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1033
-
1034
-        $ref='';
1024
+        $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1025
+        $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1026
+        $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1027
+        $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1028
+        $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1029
+        $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
1030
+        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1031
+        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1032
+        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1033
+
1034
+        $ref = '';
1035 1035
         $sql = "SELECT ".$field." as ref";
1036
-        $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1037
-        $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1038
-    	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1036
+        $sql .= " FROM ".MAIN_DB_PREFIX.$table;
1037
+        $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
1038
+    	$sql .= " AND ".$field." NOT LIKE '%PROV%'";
1039 1039
     	if ($bentityon) // only if entity enable
1040
-        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1041
-        else if (! empty($forceentity))
1042
-        	$sql.= " AND entity IN (".$forceentity.")";
1043
-        if ($where) $sql.=$where;
1044
-        if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1040
+        	$sql .= " AND entity IN (".getEntity($sharetable).")";
1041
+        else if (!empty($forceentity))
1042
+        	$sql .= " AND entity IN (".$forceentity.")";
1043
+        if ($where) $sql .= $where;
1044
+        if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
1045 1045
 
1046 1046
         dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1047
-        $resql=$db->query($sql);
1047
+        $resql = $db->query($sql);
1048 1048
         if ($resql)
1049 1049
         {
1050 1050
             $obj = $db->fetch_object($resql);
@@ -1052,7 +1052,7 @@  discard block
 block discarded – undo
1052 1052
         }
1053 1053
         else dol_print_error($db);
1054 1054
 
1055
-        $numFinal=$ref;
1055
+        $numFinal = $ref;
1056 1056
     }
1057 1057
     else if ($mode == 'next')
1058 1058
     {
@@ -1061,47 +1061,47 @@  discard block
 block discarded – undo
1061 1061
         // If value for $counter has a length higher than $maskcounter chars
1062 1062
         if ($counter >= pow(10, dol_strlen($maskcounter)))
1063 1063
         {
1064
-        	$counter='ErrorMaxNumberReachForThisMask';
1064
+        	$counter = 'ErrorMaxNumberReachForThisMask';
1065 1065
         }
1066 1066
 
1067
-        if (! empty($maskrefclient_maskcounter))
1067
+        if (!empty($maskrefclient_maskcounter))
1068 1068
         {
1069 1069
             //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
1070 1070
 
1071 1071
             // Define $sqlstring
1072
-            $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient));	// Pos of counter in final string (from 0 to ...)
1072
+            $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
1073 1073
             if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
1074
-            $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
1074
+            $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
1075 1075
             //print "x".$sqlstring;
1076 1076
 
1077 1077
             // Define $maskrefclient_maskLike
1078 1078
             $maskrefclient_maskLike = dol_string_nospecial($mask);
1079
-            $maskrefclient_maskLike = str_replace("%","_",$maskrefclient_maskLike);
1079
+            $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
1080 1080
             // Replace protected special codes with matching number of _ as wild card caracter
1081
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskrefclient_maskLike);
1082
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskrefclient_maskLike);
1083
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskrefclient_maskLike);
1084
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskrefclient_maskLike);
1085
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskrefclient_maskLike);
1086
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskrefclient_maskLike);
1087
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),$maskrefclient_clientcode.str_pad("",dol_strlen($maskrefclient_maskcounter),"_"),$maskrefclient_maskLike);
1081
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
1082
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
1083
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
1084
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
1085
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
1086
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
1087
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
1088 1088
 
1089 1089
             // Get counter in database
1090
-            $maskrefclient_counter=0;
1090
+            $maskrefclient_counter = 0;
1091 1091
             $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
1092
-            $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
1092
+            $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
1093 1093
             //$sql.= " WHERE ".$field." not like '(%'";
1094
-            $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1094
+            $maskrefclient_sql .= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1095 1095
             if ($bentityon) // only if entity enable
1096
-            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1097
-            else if (! empty($forceentity))
1098
-            	$sql.= " AND entity IN (".$forceentity.")";
1099
-            if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1100
-            if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1101
-            $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1096
+            	$maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
1097
+            else if (!empty($forceentity))
1098
+            	$sql .= " AND entity IN (".$forceentity.")";
1099
+            if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask
1100
+            if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
1101
+            $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1102 1102
 
1103 1103
             dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
1104
-            $maskrefclient_resql=$db->query($maskrefclient_sql);
1104
+            $maskrefclient_resql = $db->query($maskrefclient_sql);
1105 1105
             if ($maskrefclient_resql)
1106 1106
             {
1107 1107
                 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
             }
1110 1110
             else dol_print_error($db);
1111 1111
 
1112
-            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1112
+            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset;
1113 1113
 			$maskrefclient_counter++;
1114 1114
         }
1115 1115
 
@@ -1117,54 +1117,54 @@  discard block
 block discarded – undo
1117 1117
         $numFinal = $mask;
1118 1118
 
1119 1119
         // We replace special codes except refclient
1120
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1120
+		if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1121 1121
 		{
1122
-	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1123
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1124
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1122
+	        $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal);
1123
+        	$numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal);
1124
+        	$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal);
1125 1125
 		}
1126 1126
 		else	// we want yyyy to be current year
1127 1127
 		{
1128
-        	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1129
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1130
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1128
+        	$numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
1129
+        	$numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
1130
+        	$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
1131 1131
 		}
1132
-        $numFinal = preg_replace('/\{mm\}/i',  date("m",$date), $numFinal);
1133
-        $numFinal = preg_replace('/\{dd\}/i',  date("d",$date), $numFinal);
1132
+        $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
1133
+        $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
1134 1134
 
1135 1135
         // Now we replace the counter
1136
-        $maskbefore='{'.$masktri.'}';
1137
-        $maskafter=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1136
+        $maskbefore = '{'.$masktri.'}';
1137
+        $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1138 1138
         //print 'x'.$maskbefore.'-'.$maskafter.'y';
1139
-        $numFinal = str_replace($maskbefore,$maskafter,$numFinal);
1139
+        $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
1140 1140
 
1141 1141
         // Now we replace the refclient
1142 1142
         if ($maskrefclient)
1143 1143
         {
1144 1144
             //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1145
-            $maskrefclient_maskbefore='{'.$maskrefclient.'}';
1146
-            $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter,dol_strlen($maskrefclient_maskcounter),"0",STR_PAD_LEFT);
1147
-            $numFinal = str_replace($maskrefclient_maskbefore,$maskrefclient_maskafter,$numFinal);
1145
+            $maskrefclient_maskbefore = '{'.$maskrefclient.'}';
1146
+            $maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
1147
+            $numFinal = str_replace($maskrefclient_maskbefore, $maskrefclient_maskafter, $numFinal);
1148 1148
         }
1149 1149
 
1150 1150
         // Now we replace the type
1151 1151
         if ($masktype)
1152 1152
         {
1153
-            $masktype_maskbefore='{'.$masktype.'}';
1154
-            $masktype_maskafter=$masktype_value;
1155
-            $numFinal = str_replace($masktype_maskbefore,$masktype_maskafter,$numFinal);
1153
+            $masktype_maskbefore = '{'.$masktype.'}';
1154
+            $masktype_maskafter = $masktype_value;
1155
+            $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
1156 1156
         }
1157 1157
 
1158 1158
         // Now we replace the user
1159 1159
         if ($maskuser)
1160 1160
         {
1161
-        	$maskuser_maskbefore='{'.$maskuser.'}';
1162
-        	$maskuser_maskafter=$maskuser_value;
1163
-        	$numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1161
+        	$maskuser_maskbefore = '{'.$maskuser.'}';
1162
+        	$maskuser_maskafter = $maskuser_value;
1163
+        	$numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
1164 1164
         }
1165 1165
     }
1166 1166
 
1167
-    dol_syslog("functions2::get_next_value return ".$numFinal,LOG_DEBUG);
1167
+    dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
1168 1168
     return $numFinal;
1169 1169
 }
1170 1170
 
@@ -1179,11 +1179,11 @@  discard block
 block discarded – undo
1179 1179
 function get_string_between($string, $start, $end)
1180 1180
 {
1181 1181
     $string = " ".$string;
1182
-     $ini = strpos($string,$start);
1182
+     $ini = strpos($string, $start);
1183 1183
      if ($ini == 0) return "";
1184 1184
      $ini += strlen($start);
1185
-     $len = strpos($string,$end,$ini) - $ini;
1186
-     return substr($string,$ini,$len);
1185
+     $len = strpos($string, $end, $ini) - $ini;
1186
+     return substr($string, $ini, $len);
1187 1187
 }
1188 1188
 
1189 1189
 /**
@@ -1193,78 +1193,78 @@  discard block
 block discarded – undo
1193 1193
  * @param 	string	$value		Value
1194 1194
  * @return	int|string		    <0 or error string if KO, 0 if OK
1195 1195
  */
1196
-function check_value($mask,$value)
1196
+function check_value($mask, $value)
1197 1197
 {
1198
-    $result=0;
1198
+    $result = 0;
1199 1199
 
1200
-    $hasglobalcounter=false;
1200
+    $hasglobalcounter = false;
1201 1201
     // Extract value for mask counter, mask raz and mask offset
1202
-    if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$mask,$reg))
1202
+    if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg))
1203 1203
     {
1204
-        $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
1205
-        $maskcounter=$reg[1];
1206
-        $hasglobalcounter=true;
1204
+        $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : '');
1205
+        $maskcounter = $reg[1];
1206
+        $hasglobalcounter = true;
1207 1207
     }
1208 1208
     else
1209 1209
     {
1210 1210
         // setting some defaults so the rest of the code won't fail if there is a third party counter
1211
-        $masktri='00000';
1212
-        $maskcounter='00000';
1211
+        $masktri = '00000';
1212
+        $maskcounter = '00000';
1213 1213
     }
1214 1214
 
1215
-    $maskraz=-1;
1216
-    $maskoffset=0;
1215
+    $maskraz = -1;
1216
+    $maskoffset = 0;
1217 1217
     if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1218 1218
 
1219 1219
     // Extract value for third party mask counter
1220
-    if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
1220
+    if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
1221 1221
     {
1222
-        $maskrefclient=$regClientRef[1].$regClientRef[2];
1223
-        $maskrefclient_maskclientcode=$regClientRef[1];
1224
-        $maskrefclient_maskcounter=$regClientRef[2];
1225
-        $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
1226
-        $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
1227
-        $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1228
-        $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
1222
+        $maskrefclient = $regClientRef[1].$regClientRef[2];
1223
+        $maskrefclient_maskclientcode = $regClientRef[1];
1224
+        $maskrefclient_maskcounter = $regClientRef[2];
1225
+        $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
1226
+        $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
1227
+        $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1228
+        $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
1229 1229
         if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1230 1230
     }
1231
-    else $maskrefclient='';
1231
+    else $maskrefclient = '';
1232 1232
 
1233 1233
     // fail if there is neither a global nor a third party counter
1234
-    if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
1234
+    if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
1235 1235
     {
1236 1236
         return 'ErrorBadMask';
1237 1237
     }
1238 1238
 
1239
-    $maskwithonlyymcode=$mask;
1240
-    $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$maskcounter,$maskwithonlyymcode);
1241
-    $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
1242
-    $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
1243
-    $maskwithnocode=$maskwithonlyymcode;
1244
-    $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
1245
-    $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
1246
-    $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
1247
-    $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
1239
+    $maskwithonlyymcode = $mask;
1240
+    $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
1241
+    $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
1242
+    $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
1243
+    $maskwithnocode = $maskwithonlyymcode;
1244
+    $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
1245
+    $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
1246
+    $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
1247
+    $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
1248 1248
     // Now maskwithnocode = 0000ddmmyyyyccc for example
1249 1249
     // and maskcounter    = 0000 for example
1250 1250
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1251 1251
 
1252 1252
     // If an offset is asked
1253
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
1254
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1253
+    if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
1254
+    if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
1255 1255
 
1256 1256
     // Define $sqlwhere
1257 1257
 
1258 1258
     // If a restore to zero after a month is asked we check if there is already a value for this year.
1259
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))  $maskraz=preg_replace('/^@/','',$reg[2]);
1260
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))  $maskraz=preg_replace('/^@/','',$reg[3]);
1259
+    if (!empty($reg[2]) && preg_match('/^@/', $reg[2]))  $maskraz = preg_replace('/^@/', '', $reg[2]);
1260
+    if (!empty($reg[3]) && preg_match('/^@/', $reg[3]))  $maskraz = preg_replace('/^@/', '', $reg[3]);
1261 1261
     if ($maskraz >= 0)
1262 1262
     {
1263 1263
         if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1264 1264
 
1265 1265
         // Define reg
1266
-        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1267
-        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
1266
+        if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1267
+        if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask';
1268 1268
         //print "x".$maskwithonlyymcode." ".$maskraz;
1269 1269
     }
1270 1270
     //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
@@ -1273,8 +1273,8 @@  discard block
 block discarded – undo
1273 1273
     //
1274 1274
 
1275 1275
     // Check length
1276
-    $len=dol_strlen($maskwithnocode);
1277
-    if (dol_strlen($value) != $len) $result=-1;
1276
+    $len = dol_strlen($maskwithnocode);
1277
+    if (dol_strlen($value) != $len) $result = -1;
1278 1278
 
1279 1279
     // Define $maskLike
1280 1280
     /* seems not used
@@ -1290,7 +1290,7 @@  discard block
 block discarded – undo
1290 1290
     if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike);
1291 1291
 	*/
1292 1292
 
1293
-    dol_syslog("functions2::check_value result=".$result,LOG_DEBUG);
1293
+    dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
1294 1294
     return $result;
1295 1295
 }
1296 1296
 
@@ -1302,13 +1302,13 @@  discard block
 block discarded – undo
1302 1302
  *	@param   boolean	$upper		Convert to tupper
1303 1303
  *	@return  string					x
1304 1304
  */
1305
-function binhex($bin, $pad=false, $upper=false)
1305
+function binhex($bin, $pad = false, $upper = false)
1306 1306
 {
1307
-    $last = dol_strlen($bin)-1;
1308
-    for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
1307
+    $last = dol_strlen($bin) - 1;
1308
+    for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); }
1309 1309
     $x = dechex($x);
1310
-    if($pad){ while(dol_strlen($x) < intval(dol_strlen($bin))/4){ $x = "0$x"; } }
1311
-    if($upper){ $x = strtoupper($x); }
1310
+    if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } }
1311
+    if ($upper) { $x = strtoupper($x); }
1312 1312
     return $x;
1313 1313
 }
1314 1314
 
@@ -1320,11 +1320,11 @@  discard block
 block discarded – undo
1320 1320
  */
1321 1321
 function hexbin($hexa)
1322 1322
 {
1323
-    $bin='';
1323
+    $bin = '';
1324 1324
     $strLength = dol_strlen($hexa);
1325
-    for($i=0;$i<$strLength;$i++)
1325
+    for ($i = 0; $i < $strLength; $i++)
1326 1326
     {
1327
-        $bin.=str_pad(decbin(hexdec($hexa{$i})),4,'0',STR_PAD_LEFT);
1327
+        $bin .= str_pad(decbin(hexdec($hexa{$i})), 4, '0', STR_PAD_LEFT);
1328 1328
     }
1329 1329
     return $bin;
1330 1330
 }
@@ -1337,9 +1337,9 @@  discard block
 block discarded – undo
1337 1337
  */
1338 1338
 function numero_semaine($time)
1339 1339
 {
1340
-    $stime = strftime('%Y-%m-%d',$time);
1340
+    $stime = strftime('%Y-%m-%d', $time);
1341 1341
 
1342
-    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i',$stime,$reg))
1342
+    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg))
1343 1343
     {
1344 1344
         // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
1345 1345
         $annee = $reg[1];
@@ -1355,47 +1355,47 @@  discard block
 block discarded – undo
1355 1355
      */
1356 1356
 
1357 1357
     // Definition du Jeudi de la semaine
1358
-    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
1359
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
1360
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
1361
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
1362
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
1363
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
1358
+    if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche
1359
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
1360
+    else if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi
1361
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
1362
+    else if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi
1363
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
1364 1364
     else // Jeudi
1365
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
1365
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
1366 1366
 
1367 1367
     // Definition du premier Jeudi de l'annee
1368
-    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
1368
+    if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche
1369 1369
     {
1370
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
1370
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
1371 1371
     }
1372
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
1372
+    else if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi
1373 1373
     {
1374
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60;
1374
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60;
1375 1375
     }
1376
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
1376
+    else if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi
1377 1377
     {
1378
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60;
1378
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60;
1379 1379
     }
1380 1380
     else // Jeudi
1381 1381
     {
1382
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
1382
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine));
1383 1383
     }
1384 1384
 
1385 1385
     // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
1386
-    $numeroSemaine =     (
1386
+    $numeroSemaine = (
1387 1387
     (
1388
-    date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine)))
1388
+    date("z", mktime(12, 0, 0, date("m", $jeudiSemaine), date("d", $jeudiSemaine), date("Y", $jeudiSemaine)))
1389 1389
     -
1390
-    date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee)))
1390
+    date("z", mktime(12, 0, 0, date("m", $premierJeudiAnnee), date("d", $premierJeudiAnnee), date("Y", $premierJeudiAnnee)))
1391 1391
     ) / 7
1392 1392
     ) + 1;
1393 1393
 
1394 1394
     // Cas particulier de la semaine 53
1395
-    if ($numeroSemaine==53)
1395
+    if ($numeroSemaine == 53)
1396 1396
     {
1397 1397
         // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
1398
-        if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365))
1398
+        if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365))
1399 1399
         {
1400 1400
             $numeroSemaine = 53;
1401 1401
         }
@@ -1407,7 +1407,7 @@  discard block
 block discarded – undo
1407 1407
 
1408 1408
     //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
1409 1409
 
1410
-    return sprintf("%02d",$numeroSemaine);
1410
+    return sprintf("%02d", $numeroSemaine);
1411 1411
 }
1412 1412
 
1413 1413
 /**
@@ -1418,26 +1418,26 @@  discard block
 block discarded – undo
1418 1418
  *	@param  int		$to_unit   		Nouvelle unite  en puissance de 10
1419 1419
  *	@return float	        		Masse convertie
1420 1420
  */
1421
-function weight_convert($weight,&$from_unit,$to_unit)
1421
+function weight_convert($weight, &$from_unit, $to_unit)
1422 1422
 {
1423 1423
     /* Pour convertire 320 gr en Kg appeler
1424 1424
      *  $f = -3
1425 1425
      *  weigh_convert(320, $f, 0) retournera 0.32
1426 1426
      *
1427 1427
      */
1428
-    while ($from_unit  <> $to_unit)
1428
+    while ($from_unit <> $to_unit)
1429 1429
     {
1430 1430
         if ($from_unit > $to_unit)
1431 1431
         {
1432 1432
             $weight = $weight * 10;
1433 1433
             $from_unit = $from_unit - 1;
1434
-            $weight = weight_convert($weight,$from_unit, $to_unit);
1434
+            $weight = weight_convert($weight, $from_unit, $to_unit);
1435 1435
         }
1436 1436
         if ($from_unit < $to_unit)
1437 1437
         {
1438 1438
             $weight = $weight / 10;
1439 1439
             $from_unit = $from_unit + 1;
1440
-            $weight = weight_convert($weight,$from_unit, $to_unit);
1440
+            $weight = weight_convert($weight, $from_unit, $to_unit);
1441 1441
         }
1442 1442
     }
1443 1443
 
@@ -1464,21 +1464,21 @@  discard block
 block discarded – undo
1464 1464
 
1465 1465
     // We remove old parameters for all keys in $tab
1466 1466
     $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
1467
-    $sql.= " WHERE fk_user = ".$user->id;
1468
-    $sql.= " AND entity = ".$conf->entity;
1469
-    $sql.= " AND param in (";
1470
-    $i=0;
1467
+    $sql .= " WHERE fk_user = ".$user->id;
1468
+    $sql .= " AND entity = ".$conf->entity;
1469
+    $sql .= " AND param in (";
1470
+    $i = 0;
1471 1471
     foreach ($tab as $key => $value)
1472 1472
     {
1473
-        if ($i > 0) $sql.=',';
1474
-        $sql.="'".$db->escape($key)."'";
1473
+        if ($i > 0) $sql .= ',';
1474
+        $sql .= "'".$db->escape($key)."'";
1475 1475
         $i++;
1476 1476
     }
1477
-    $sql.= ")";
1477
+    $sql .= ")";
1478 1478
     dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1479 1479
 
1480
-    $resql=$db->query($sql);
1481
-    if (! $resql)
1480
+    $resql = $db->query($sql);
1481
+    if (!$resql)
1482 1482
     {
1483 1483
         dol_print_error($db);
1484 1484
         $db->rollback();
@@ -1491,12 +1491,12 @@  discard block
 block discarded – undo
1491 1491
         if ($value)
1492 1492
         {
1493 1493
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
1494
-            $sql.= " VALUES (".$user->id.",".$conf->entity.",";
1495
-            $sql.= " '".$db->escape($key)."','".$db->escape($value)."')";
1494
+            $sql .= " VALUES (".$user->id.",".$conf->entity.",";
1495
+            $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
1496 1496
 
1497 1497
             dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1498
-            $result=$db->query($sql);
1499
-            if (! $result)
1498
+            $result = $db->query($sql);
1499
+            if (!$result)
1500 1500
             {
1501 1501
                 dol_print_error($db);
1502 1502
                 $db->rollback();
@@ -1522,7 +1522,7 @@  discard block
 block discarded – undo
1522 1522
  *	@param	Translate	$langs			Output language
1523 1523
  *	@return	string						Formated reduction
1524 1524
  */
1525
-function dol_print_reduction($reduction,$langs)
1525
+function dol_print_reduction($reduction, $langs)
1526 1526
 {
1527 1527
     $string = '';
1528 1528
     if ($reduction == 100)
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
     }
1532 1532
     else
1533 1533
     {
1534
-    	$string = vatrate($reduction,true);
1534
+    	$string = vatrate($reduction, true);
1535 1535
     }
1536 1536
 
1537 1537
     return $string;
@@ -1545,7 +1545,7 @@  discard block
 block discarded – undo
1545 1545
  */
1546 1546
 function version_os()
1547 1547
 {
1548
-    $osversion=php_uname();
1548
+    $osversion = php_uname();
1549 1549
     return $osversion;
1550 1550
 }
1551 1551
 
@@ -1589,18 +1589,18 @@  discard block
 block discarded – undo
1589 1589
  *  @param  int		    $maxfilenamelength  Max length of value to show
1590 1590
  * 	@return	mixed			    			0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
1591 1591
  */
1592
-function getListOfModels($db,$type,$maxfilenamelength=0)
1592
+function getListOfModels($db, $type, $maxfilenamelength = 0)
1593 1593
 {
1594
-    global $conf,$langs;
1595
-    $liste=array();
1596
-    $found=0;
1597
-    $dirtoscan='';
1594
+    global $conf, $langs;
1595
+    $liste = array();
1596
+    $found = 0;
1597
+    $dirtoscan = '';
1598 1598
 
1599 1599
     $sql = "SELECT nom as id, nom as lib, libelle as label, description as description";
1600
-    $sql.= " FROM ".MAIN_DB_PREFIX."document_model";
1601
-    $sql.= " WHERE type = '".$type."'";
1602
-    $sql.= " AND entity IN (0,".$conf->entity.")";
1603
-    $sql.= " ORDER BY description DESC";
1600
+    $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
1601
+    $sql .= " WHERE type = '".$type."'";
1602
+    $sql .= " AND entity IN (0,".$conf->entity.")";
1603
+    $sql .= " ORDER BY description DESC";
1604 1604
 
1605 1605
     dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
1606 1606
     $resql = $db->query($sql);
@@ -1610,48 +1610,48 @@  discard block
 block discarded – undo
1610 1610
         $i = 0;
1611 1611
         while ($i < $num)
1612 1612
         {
1613
-            $found=1;
1613
+            $found = 1;
1614 1614
 
1615 1615
             $obj = $db->fetch_object($resql);
1616 1616
 
1617 1617
             // If this generation module needs to scan a directory, then description field is filled
1618 1618
             // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1619
-            if (! empty($obj->description))	// A list of directories to scan is defined
1619
+            if (!empty($obj->description))	// A list of directories to scan is defined
1620 1620
             {
1621 1621
                 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1622 1622
 
1623
-                $const=$obj->description;
1623
+                $const = $obj->description;
1624 1624
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1625
-                $dirtoscan= preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1625
+                $dirtoscan = preg_replace('/[\r\n]+/', ',', trim($conf->global->$const));
1626 1626
 
1627
-		$listoffiles=array();
1627
+		$listoffiles = array();
1628 1628
 
1629 1629
                 // Now we add models found in directories scanned
1630
-                $listofdir=explode(',',$dirtoscan);
1631
-                foreach($listofdir as $key=>$tmpdir)
1630
+                $listofdir = explode(',', $dirtoscan);
1631
+                foreach ($listofdir as $key=>$tmpdir)
1632 1632
                 {
1633
-                    $tmpdir=trim($tmpdir);
1634
-                    $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
1635
-                    if (! $tmpdir) { unset($listofdir[$key]); continue; }
1633
+                    $tmpdir = trim($tmpdir);
1634
+                    $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
1635
+                    if (!$tmpdir) { unset($listofdir[$key]); continue; }
1636 1636
                     if (is_dir($tmpdir))
1637 1637
                     {
1638 1638
 			// all type of template is allowed
1639
-			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1640
-                        if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1639
+			$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1640
+                        if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
1641 1641
                     }
1642 1642
                 }
1643 1643
 
1644 1644
                 if (count($listoffiles))
1645 1645
                 {
1646
-                    foreach($listoffiles as $record)
1646
+                    foreach ($listoffiles as $record)
1647 1647
                     {
1648
-                        $max=($maxfilenamelength?$maxfilenamelength:28);
1649
-                        $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
1648
+                        $max = ($maxfilenamelength ? $maxfilenamelength : 28);
1649
+                        $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
1650 1650
                     }
1651 1651
                 }
1652 1652
                 else
1653 1653
                 {
1654
-                    $liste[0]=$obj->label.': '.$langs->trans("None");
1654
+                    $liste[0] = $obj->label.': '.$langs->trans("None");
1655 1655
                 }
1656 1656
             }
1657 1657
             else
@@ -1660,14 +1660,14 @@  discard block
 block discarded – undo
1660 1660
                 {
1661 1661
                     global $_Avery_Labels;
1662 1662
                     include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1663
-                    foreach($_Avery_Labels as $key => $val)
1663
+                    foreach ($_Avery_Labels as $key => $val)
1664 1664
                     {
1665
-                        $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
1665
+                        $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->lib).' '.$val['name'];
1666 1666
                     }
1667 1667
                 }
1668 1668
                 else    // Common usage
1669 1669
                 {
1670
-                    $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
1670
+                    $liste[$obj->id] = $obj->label ? $obj->label : $obj->lib;
1671 1671
                 }
1672 1672
             }
1673 1673
             $i++;
@@ -1696,10 +1696,10 @@  discard block
 block discarded – undo
1696 1696
 	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1697 1697
 
1698 1698
 		// Then we test if it is a private range
1699
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1699
+		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1700 1700
 
1701 1701
 		// Then we test if it is a reserved range
1702
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1702
+		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1703 1703
 
1704 1704
 		return 1;
1705 1705
 	}
@@ -1714,12 +1714,12 @@  discard block
 block discarded – undo
1714 1714
  *  @param  string		$firstname		Firstname
1715 1715
  *	@return	string						Login
1716 1716
  */
1717
-function dol_buildlogin($lastname,$firstname)
1717
+function dol_buildlogin($lastname, $firstname)
1718 1718
 {
1719
-    $login=strtolower(dol_string_unaccent($firstname));
1720
-    $login.=($login?'.':'');
1721
-    $login.=strtolower(dol_string_unaccent($lastname));
1722
-    $login=dol_string_nospecial($login,''); // For special names
1719
+    $login = strtolower(dol_string_unaccent($firstname));
1720
+    $login .= ($login ? '.' : '');
1721
+    $login .= strtolower(dol_string_unaccent($lastname));
1722
+    $login = dol_string_nospecial($login, ''); // For special names
1723 1723
     return $login;
1724 1724
 }
1725 1725
 
@@ -1732,18 +1732,18 @@  discard block
 block discarded – undo
1732 1732
 {
1733 1733
     global $conf;
1734 1734
 
1735
-    $params=array();
1736
-    $proxyuse =(empty($conf->global->MAIN_PROXY_USE)?false:true);
1737
-    $proxyhost=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_HOST);
1738
-    $proxyport=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PORT);
1739
-    $proxyuser=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_USER);
1740
-    $proxypass=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PASS);
1741
-    $timeout  =(empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)?10:$conf->global->MAIN_USE_CONNECT_TIMEOUT);               // Connection timeout
1742
-    $response_timeout=(empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT)?30:$conf->global->MAIN_USE_RESPONSE_TIMEOUT);    // Response timeout
1735
+    $params = array();
1736
+    $proxyuse = (empty($conf->global->MAIN_PROXY_USE) ?false:true);
1737
+    $proxyhost = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_HOST);
1738
+    $proxyport = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PORT);
1739
+    $proxyuser = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_USER);
1740
+    $proxypass = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PASS);
1741
+    $timeout  = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
1742
+    $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
1743 1743
     //print extension_loaded('soap');
1744 1744
     if ($proxyuse)
1745 1745
     {
1746
-        $params=array('connection_timeout'=>$timeout,
1746
+        $params = array('connection_timeout'=>$timeout,
1747 1747
                       'response_timeout'=>$response_timeout,
1748 1748
                       'proxy_use'      => 1,
1749 1749
                       'proxy_host'     => $proxyhost,
@@ -1755,7 +1755,7 @@  discard block
 block discarded – undo
1755 1755
     }
1756 1756
     else
1757 1757
     {
1758
-        $params=array('connection_timeout'=>$timeout,
1758
+        $params = array('connection_timeout'=>$timeout,
1759 1759
                       'response_timeout'=>$response_timeout,
1760 1760
                       'proxy_use'      => 0,
1761 1761
                       'proxy_host'     => false,
@@ -1778,15 +1778,15 @@  discard block
 block discarded – undo
1778 1778
  * @param 	string	$option			More options
1779 1779
  * @return	string					URL of link to object id/type
1780 1780
  */
1781
-function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
1781
+function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
1782 1782
 {
1783 1783
 	global $db, $conf, $langs;
1784 1784
 
1785
-	$ret='';
1785
+	$ret = '';
1786 1786
 
1787 1787
 	// Parse element/subelement (ex: project_task)
1788 1788
 	$module = $element = $subelement = $objecttype;
1789
-	if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1789
+	if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
1790 1790
 	{
1791 1791
 		$module = $element = $regs[1];
1792 1792
 		$subelement = $regs[2];
@@ -1797,18 +1797,18 @@  discard block
 block discarded – undo
1797 1797
 	// To work with non standard path
1798 1798
 	if ($objecttype == 'facture' || $objecttype == 'invoice') {
1799 1799
 		$classpath = 'compta/facture/class';
1800
-		$module='facture';
1801
-		$subelement='facture';
1800
+		$module = 'facture';
1801
+		$subelement = 'facture';
1802 1802
 	}
1803 1803
 	if ($objecttype == 'commande' || $objecttype == 'order') {
1804 1804
 		$classpath = 'commande/class';
1805
-		$module='commande';
1806
-		$subelement='commande';
1805
+		$module = 'commande';
1806
+		$subelement = 'commande';
1807 1807
 	}
1808
-	if ($objecttype == 'propal')  {
1808
+	if ($objecttype == 'propal') {
1809 1809
 		$classpath = 'comm/propal/class';
1810 1810
 	}
1811
-	if ($objecttype == 'supplier_proposal')  {
1811
+	if ($objecttype == 'supplier_proposal') {
1812 1812
 		$classpath = 'supplier_proposal/class';
1813 1813
 	}
1814 1814
 	if ($objecttype == 'shipping') {
@@ -1823,33 +1823,33 @@  discard block
 block discarded – undo
1823 1823
 	}
1824 1824
 	if ($objecttype == 'contract') {
1825 1825
 		$classpath = 'contrat/class';
1826
-		$module='contrat';
1827
-		$subelement='contrat';
1826
+		$module = 'contrat';
1827
+		$subelement = 'contrat';
1828 1828
 	}
1829 1829
 	if ($objecttype == 'member') {
1830 1830
 		$classpath = 'adherents/class';
1831
-		$module='adherent';
1832
-		$subelement='adherent';
1831
+		$module = 'adherent';
1832
+		$subelement = 'adherent';
1833 1833
 	}
1834 1834
 	if ($objecttype == 'cabinetmed_cons') {
1835 1835
 		$classpath = 'cabinetmed/class';
1836
-		$module='cabinetmed';
1837
-		$subelement='cabinetmedcons';
1836
+		$module = 'cabinetmed';
1837
+		$subelement = 'cabinetmedcons';
1838 1838
 	}
1839 1839
 	if ($objecttype == 'fichinter') {
1840 1840
 		$classpath = 'fichinter/class';
1841
-		$module='ficheinter';
1842
-		$subelement='fichinter';
1841
+		$module = 'ficheinter';
1842
+		$subelement = 'fichinter';
1843 1843
 	}
1844 1844
 	if ($objecttype == 'task') {
1845 1845
 		$classpath = 'projet/class';
1846
-		$module='projet';
1847
-		$subelement='task';
1846
+		$module = 'projet';
1847
+		$subelement = 'task';
1848 1848
 	}
1849 1849
 	if ($objecttype == 'stock') {
1850 1850
 		$classpath = 'product/stock/class';
1851
-		$module='stock';
1852
-		$subelement='stock';
1851
+		$module = 'stock';
1852
+		$subelement = 'stock';
1853 1853
 	}
1854 1854
 
1855 1855
 	//print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
@@ -1857,34 +1857,34 @@  discard block
 block discarded – undo
1857 1857
 	$classfile = strtolower($subelement); $classname = ucfirst($subelement);
1858 1858
 	if ($objecttype == 'invoice_supplier') {
1859 1859
 		$classfile = 'fournisseur.facture';
1860
-		$classname='FactureFournisseur';
1860
+		$classname = 'FactureFournisseur';
1861 1861
 		$classpath = 'fourn/class';
1862
-		$module='fournisseur';
1862
+		$module = 'fournisseur';
1863 1863
 	}
1864
-	elseif ($objecttype == 'order_supplier')   {
1864
+	elseif ($objecttype == 'order_supplier') {
1865 1865
 		$classfile = 'fournisseur.commande';
1866
-		$classname='CommandeFournisseur';
1866
+		$classname = 'CommandeFournisseur';
1867 1867
 		$classpath = 'fourn/class';
1868
-		$module='fournisseur';
1868
+		$module = 'fournisseur';
1869 1869
 	}
1870
-	elseif ($objecttype == 'stock')   {
1870
+	elseif ($objecttype == 'stock') {
1871 1871
 		$classpath = 'product/stock/class';
1872
-		$classfile='entrepot';
1873
-		$classname='Entrepot';
1872
+		$classfile = 'entrepot';
1873
+		$classname = 'Entrepot';
1874 1874
 	}
1875
-	if (! empty($conf->$module->enabled))
1875
+	if (!empty($conf->$module->enabled))
1876 1876
 	{
1877
-		$res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1877
+		$res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1878 1878
 		if ($res)
1879 1879
 		{
1880 1880
 			if (class_exists($classname))
1881 1881
 			{
1882 1882
 				$object = new $classname($db);
1883
-				$res=$object->fetch($objectid);
1883
+				$res = $object->fetch($objectid);
1884 1884
 				if ($res > 0) {
1885
-					$ret=$object->getNomUrl($withpicto,$option);
1886
-				} elseif($res==0) {
1887
-					$ret=$langs->trans('Deleted');
1885
+					$ret = $object->getNomUrl($withpicto, $option);
1886
+				} elseif ($res == 0) {
1887
+					$ret = $langs->trans('Deleted');
1888 1888
 				}
1889 1889
 				unset($object);
1890 1890
 			}
@@ -1905,12 +1905,12 @@  discard block
 block discarded – undo
1905 1905
  */
1906 1906
 function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
1907 1907
 {
1908
-	$totalnb=0;
1909
-	$listofid=array();
1910
-	$listofparentid=array();
1908
+	$totalnb = 0;
1909
+	$listofid = array();
1910
+	$listofparentid = array();
1911 1911
 
1912 1912
 	// Get list of all id in array listofid and all parents in array listofparentid
1913
-	$sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1913
+	$sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1914 1914
 	$resql = $db->query($sql);
1915 1915
 	if ($resql)
1916 1916
 	{
@@ -1919,8 +1919,8 @@  discard block
 block discarded – undo
1919 1919
 		while ($i < $num)
1920 1920
 		{
1921 1921
 			$obj = $db->fetch_object($resql);
1922
-			$listofid[]=$obj->rowid;
1923
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1922
+			$listofid[] = $obj->rowid;
1923
+			if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id;
1924 1924
 			$i++;
1925 1925
 		}
1926 1926
 	}
@@ -1934,78 +1934,78 @@  discard block
 block discarded – undo
1934 1934
 		print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1935 1935
 
1936 1936
 		// Check loops on each other
1937
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1937
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
1938 1938
 		$resql = $db->query($sql);
1939 1939
 		if ($resql)
1940 1940
 		{
1941
-			$nb=$db->affected_rows($sql);
1941
+			$nb = $db->affected_rows($sql);
1942 1942
 			if ($nb > 0)
1943 1943
 			{
1944 1944
 				print '<br>Some record that were parent of themself were cleaned.';
1945 1945
 			}
1946 1946
 
1947
-			$totalnb+=$nb;
1947
+			$totalnb += $nb;
1948 1948
 		}
1949 1949
 		//else dol_print_error($db);
1950 1950
 
1951 1951
 		// Check other loops
1952
-		$listofidtoclean=array();
1953
-		foreach($listofparentid as $id => $pid)
1952
+		$listofidtoclean = array();
1953
+		foreach ($listofparentid as $id => $pid)
1954 1954
 		{
1955 1955
 			// Check depth
1956 1956
 			//print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1957 1957
 
1958
-			$cursor=$id; $arrayidparsed=array();	// We start from child $id
1958
+			$cursor = $id; $arrayidparsed = array(); // We start from child $id
1959 1959
 			while ($cursor > 0)
1960 1960
 			{
1961
-				$arrayidparsed[$cursor]=1;
1961
+				$arrayidparsed[$cursor] = 1;
1962 1962
 				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1963 1963
 				{
1964 1964
 					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1965 1965
 					unset($arrayidparsed);
1966
-					$listofidtoclean[$cursor]=$id;
1966
+					$listofidtoclean[$cursor] = $id;
1967 1967
 					break;
1968 1968
 				}
1969
-				$cursor=$listofparentid[$cursor];
1969
+				$cursor = $listofparentid[$cursor];
1970 1970
 			}
1971 1971
 
1972 1972
 			if (count($listofidtoclean)) break;
1973 1973
 		}
1974 1974
 
1975 1975
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1976
-		$sql.= " SET ".$fieldfkparent." = 0";
1977
-		$sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1976
+		$sql .= " SET ".$fieldfkparent." = 0";
1977
+		$sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong
1978 1978
 		$resql = $db->query($sql);
1979 1979
 		if ($resql)
1980 1980
 		{
1981
-			$nb=$db->affected_rows($sql);
1981
+			$nb = $db->affected_rows($sql);
1982 1982
 			if ($nb > 0)
1983 1983
 			{
1984 1984
 				// Removed orphelins records
1985 1985
 				print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1986
-				print join(',',$listofidtoclean);
1986
+				print join(',', $listofidtoclean);
1987 1987
 			}
1988 1988
 
1989
-			$totalnb+=$nb;
1989
+			$totalnb += $nb;
1990 1990
 		}
1991 1991
 		//else dol_print_error($db);
1992 1992
 
1993 1993
 		// Check and clean orphelins
1994 1994
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1995
-		$sql.= " SET ".$fieldfkparent." = 0";
1996
-		$sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
1995
+		$sql .= " SET ".$fieldfkparent." = 0";
1996
+		$sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent
1997 1997
 		$resql = $db->query($sql);
1998 1998
 		if ($resql)
1999 1999
 		{
2000
-			$nb=$db->affected_rows($sql);
2000
+			$nb = $db->affected_rows($sql);
2001 2001
 			if ($nb > 0)
2002 2002
 			{
2003 2003
 				// Removed orphelins records
2004 2004
 				print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2005
-				print join(',',$listofid);
2005
+				print join(',', $listofid);
2006 2006
 			}
2007 2007
 
2008
-			$totalnb+=$nb;
2008
+			$totalnb += $nb;
2009 2009
 		}
2010 2010
 		//else dol_print_error($db);
2011 2011
 
@@ -2026,21 +2026,21 @@  discard block
 block discarded – undo
2026 2026
     $module = $element = $subelement = $element_type;
2027 2027
 
2028 2028
     // If we ask an resource form external module (instead of default path)
2029
-    if (preg_match('/^([^@]+)@([^@]+)$/i',$element_type,$regs))
2029
+    if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs))
2030 2030
     {
2031 2031
         $element = $subelement = $regs[1];
2032 2032
         $module 	= $regs[2];
2033 2033
     }
2034 2034
 
2035 2035
     //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
2036
-    if ( preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
2036
+    if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs))
2037 2037
     {
2038 2038
         $module = $element = $regs[1];
2039 2039
         $subelement = $regs[2];
2040 2040
     }
2041 2041
 
2042 2042
     // For compat
2043
-    if($element_type == "action") {
2043
+    if ($element_type == "action") {
2044 2044
         $classpath = 'comm/action/class';
2045 2045
         $subelement = 'Actioncomm';
2046 2046
         $module = 'agenda';
@@ -2049,18 +2049,18 @@  discard block
 block discarded – undo
2049 2049
     // To work with non standard path
2050 2050
     if ($element_type == 'facture' || $element_type == 'invoice') {
2051 2051
         $classpath = 'compta/facture/class';
2052
-        $module='facture';
2053
-        $subelement='facture';
2052
+        $module = 'facture';
2053
+        $subelement = 'facture';
2054 2054
     }
2055 2055
     if ($element_type == 'commande' || $element_type == 'order') {
2056 2056
         $classpath = 'commande/class';
2057
-        $module='commande';
2058
-        $subelement='commande';
2057
+        $module = 'commande';
2058
+        $subelement = 'commande';
2059 2059
     }
2060
-    if ($element_type == 'propal')  {
2060
+    if ($element_type == 'propal') {
2061 2061
         $classpath = 'comm/propal/class';
2062 2062
     }
2063
-    if ($element_type == 'supplier_proposal')  {
2063
+    if ($element_type == 'supplier_proposal') {
2064 2064
         $classpath = 'supplier_proposal/class';
2065 2065
     }
2066 2066
     if ($element_type == 'shipping') {
@@ -2075,45 +2075,45 @@  discard block
 block discarded – undo
2075 2075
     }
2076 2076
     if ($element_type == 'contract') {
2077 2077
         $classpath = 'contrat/class';
2078
-        $module='contrat';
2079
-        $subelement='contrat';
2078
+        $module = 'contrat';
2079
+        $subelement = 'contrat';
2080 2080
     }
2081 2081
     if ($element_type == 'member') {
2082 2082
         $classpath = 'adherents/class';
2083
-        $module='adherent';
2084
-        $subelement='adherent';
2083
+        $module = 'adherent';
2084
+        $subelement = 'adherent';
2085 2085
     }
2086 2086
     if ($element_type == 'cabinetmed_cons') {
2087 2087
         $classpath = 'cabinetmed/class';
2088
-        $module='cabinetmed';
2089
-        $subelement='cabinetmedcons';
2088
+        $module = 'cabinetmed';
2089
+        $subelement = 'cabinetmedcons';
2090 2090
     }
2091 2091
     if ($element_type == 'fichinter') {
2092 2092
         $classpath = 'fichinter/class';
2093
-        $module='ficheinter';
2094
-        $subelement='fichinter';
2093
+        $module = 'ficheinter';
2094
+        $subelement = 'fichinter';
2095 2095
     }
2096 2096
     if ($element_type == 'dolresource' || $element_type == 'resource') {
2097 2097
         $classpath = 'resource/class';
2098
-        $module='resource';
2099
-        $subelement='dolresource';
2098
+        $module = 'resource';
2099
+        $subelement = 'dolresource';
2100 2100
     }
2101 2101
     if ($element_type == 'propaldet') {
2102 2102
         $classpath = 'comm/propal/class';
2103
-        $module='propal';
2104
-        $subelement='propaleligne';
2103
+        $module = 'propal';
2104
+        $subelement = 'propaleligne';
2105 2105
     }
2106
-    if ($element_type == 'order_supplier')  {
2106
+    if ($element_type == 'order_supplier') {
2107 2107
         $classpath = 'fourn/class';
2108
-        $module='fournisseur';
2109
-        $subelement='commandefournisseur';
2110
-        $classfile='fournisseur.commande';
2108
+        $module = 'fournisseur';
2109
+        $subelement = 'commandefournisseur';
2110
+        $classfile = 'fournisseur.commande';
2111 2111
     }
2112
-    if ($element_type == 'invoice_supplier')  {
2112
+    if ($element_type == 'invoice_supplier') {
2113 2113
         $classpath = 'fourn/class';
2114
-        $module='fournisseur';
2115
-        $subelement='facturefournisseur';
2116
-        $classfile='fournisseur.facture';
2114
+        $module = 'fournisseur';
2115
+        $subelement = 'facturefournisseur';
2116
+        $classfile = 'fournisseur.facture';
2117 2117
     }
2118 2118
 
2119 2119
     if (!isset($classfile)) $classfile = strtolower($subelement);
@@ -2140,10 +2140,10 @@  discard block
 block discarded – undo
2140 2140
  * @param	ref     	$element_ref 	Element ref (Use this if element_id but not both)
2141 2141
  * @return 	int|object 					object || 0 || -1 if error
2142 2142
  */
2143
-function fetchObjectByElement($element_id, $element_type, $element_ref='')
2143
+function fetchObjectByElement($element_id, $element_type, $element_ref = '')
2144 2144
 {
2145 2145
     global $conf;
2146
-	global $db,$conf;
2146
+	global $db, $conf;
2147 2147
 
2148 2148
     $element_prop = getElementProperties($element_type);
2149 2149
     if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
@@ -2170,11 +2170,11 @@  discard block
 block discarded – undo
2170 2170
  *  @return	string						RGB hex value (without # before). For example: 'FF00FF', '01FF02'
2171 2171
  *  @see	colorStringToArray
2172 2172
  */
2173
-function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2173
+function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
2174 2174
 {
2175
-	if (! is_array($arraycolor)) return $colorifnotfound;
2175
+	if (!is_array($arraycolor)) return $colorifnotfound;
2176 2176
 	if (empty($arraycolor)) return $colorifnotfound;
2177
-	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2177
+	return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
2178 2178
 }
2179 2179
 
2180 2180
 /**
@@ -2187,17 +2187,17 @@  discard block
 block discarded – undo
2187 2187
  *  @return	string						RGB hex value (without # before). For example: FF00FF
2188 2188
  *  @see	colorArrayToHex
2189 2189
  */
2190
-function colorStringToArray($stringcolor,$colorifnotfound=array(88,88,88))
2190
+function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2191 2191
 {
2192
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2193
-	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2194
-	if (! $tmp)
2192
+	if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
2193
+	$tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg);
2194
+	if (!$tmp)
2195 2195
 	{
2196
-		$tmp=explode(',',$stringcolor);
2196
+		$tmp = explode(',', $stringcolor);
2197 2197
 		if (count($tmp) < 3) return $colorifnotfound;
2198 2198
 		return $tmp;
2199 2199
 	}
2200
-	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2200
+	return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
2201 2201
 }
2202 2202
 
2203 2203
 /**
@@ -2217,8 +2217,8 @@  discard block
 block discarded – undo
2217 2217
     foreach ($input as $key => $values) {
2218 2218
         $append = array();
2219 2219
 
2220
-        foreach($result as $product) {
2221
-            foreach($values as $item) {
2220
+        foreach ($result as $product) {
2221
+            foreach ($values as $item) {
2222 2222
                 $product[$key] = $item;
2223 2223
                 $append[] = $product;
2224 2224
             }
@@ -2239,8 +2239,8 @@  discard block
 block discarded – undo
2239 2239
  */
2240 2240
 function getModuleDirForApiClass($module)
2241 2241
 {
2242
-    $moduledirforclass=$module;
2243
-    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2242
+    $moduledirforclass = $module;
2243
+    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
2244 2244
 
2245 2245
     if ($module == 'contracts') {
2246 2246
     	$moduledirforclass = 'contrat';
@@ -2316,9 +2316,9 @@  discard block
 block discarded – undo
2316 2316
  * @param	$max	int	Between 0 and 255
2317 2317
  * @return String
2318 2318
  */
2319
-function random_color_part($min=0,$max=255)
2319
+function random_color_part($min = 0, $max = 255)
2320 2320
 {
2321
-    return str_pad( dechex( mt_rand( $min, $max) ), 2, '0', STR_PAD_LEFT);
2321
+    return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
2322 2322
 }
2323 2323
 
2324 2324
 /*
@@ -2328,7 +2328,7 @@  discard block
 block discarded – undo
2328 2328
  * @param	$max	int	Between 0 and 255
2329 2329
  * @return String
2330 2330
  */
2331
-function random_color($min=0, $max=255)
2331
+function random_color($min = 0, $max = 255)
2332 2332
 {
2333
-    return random_color_part($min, $max) . random_color_part($min, $max) . random_color_part($min, $max);
2333
+    return random_color_part($min, $max).random_color_part($min, $max).random_color_part($min, $max);
2334 2334
 }
Please login to merge, or discard this patch.
Braces   +696 added lines, -349 removed lines patch added patch discarded remove patch
@@ -55,8 +55,7 @@  discard block
 block discarded – undo
55 55
                 $entity = "&#". $unicode . ';';
56 56
                 $decodedStr .= utf8_encode($entity);
57 57
                 $pos += 4;
58
-            }
59
-            else {
58
+            } else {
60 59
                 // we have an escaped ascii character
61 60
                 $hexVal = substr($source, $pos, 2);
62 61
                 $decodedStr .= chr(hexdec($hexVal));
@@ -97,7 +96,10 @@  discard block
 block discarded – undo
97 96
         {
98 97
             while (($file = readdir($handle))!==false)
99 98
             {
100
-                if (preg_match('/disabled/',$file)) continue;   // We discard module if it contains disabled into name.
99
+                if (preg_match('/disabled/',$file)) {
100
+                    continue;
101
+                }
102
+                // We discard module if it contains disabled into name.
101 103
 
102 104
                 if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
103 105
                 {
@@ -129,8 +131,14 @@  discard block
 block discarded – undo
129 131
     	$outputlangs=$langs;
130 132
     }
131 133
 
132
-    if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
133
-    if ($outputlangs->defaultlang == 'en_US') $selected='USLetter';    // US
134
+    if ($outputlangs->defaultlang == 'ca_CA') {
135
+        $selected='CAP4';
136
+    }
137
+    // Canada
138
+    if ($outputlangs->defaultlang == 'en_US') {
139
+        $selected='USLetter';
140
+    }
141
+    // US
134 142
     return $selected;
135 143
 }
136 144
 
@@ -155,29 +163,42 @@  discard block
 block discarded – undo
155 163
         {
156 164
             $content=file_get_contents($formfile);
157 165
             $isutf8=utf8_check($content);
158
-            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
159
-            elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
160
-            else print $content;
166
+            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') {
167
+                print utf8_encode($content);
168
+            } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
169
+                print utf8_decode($content);
170
+            } else {
171
+                print $content;
172
+            }
161 173
             return true;
174
+        } else {
175
+            dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
162 176
         }
163
-        else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
164 177
 
165 178
         if ($searchalt) {
166 179
             // Test si fichier dans repertoire de la langue alternative
167
-            if ($langs->defaultlang != "en_US") $formfilealt = $searchdir."/langs/en_US/".$filename;
168
-            else $formfilealt = $searchdir."/langs/fr_FR/".$filename;
180
+            if ($langs->defaultlang != "en_US") {
181
+                $formfilealt = $searchdir."/langs/en_US/".$filename;
182
+            } else {
183
+                $formfilealt = $searchdir."/langs/fr_FR/".$filename;
184
+            }
169 185
             dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG);
170 186
             //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
171 187
             if (is_readable($formfilealt))
172 188
             {
173 189
                 $content=file_get_contents($formfilealt);
174 190
                 $isutf8=utf8_check($content);
175
-                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
176
-                elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
177
-                else print $content;
191
+                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') {
192
+                    print utf8_encode($content);
193
+                } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
194
+                    print utf8_decode($content);
195
+                } else {
196
+                    print $content;
197
+                }
178 198
                 return true;
199
+            } else {
200
+                dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
179 201
             }
180
-            else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
181 202
         }
182 203
     }
183 204
 
@@ -207,279 +228,460 @@  discard block
 block discarded – undo
207 228
     $deltadateforuser=round($deltadateforclient-$deltadateforserver);
208 229
     //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
209 230
 
210
-    if ($usetable) print '<table class="border centpercent">';
231
+    if ($usetable) {
232
+        print '<table class="border centpercent">';
233
+    }
211 234
 
212 235
     // Import key
213 236
     if (! empty($object->import_key))
214 237
     {
215
-        if ($usetable) print '<tr><td class="titlefield">';
238
+        if ($usetable) {
239
+            print '<tr><td class="titlefield">';
240
+        }
216 241
         print $langs->trans("ImportedWithSet");
217
-        if ($usetable) print '</td><td>';
218
-        else print ': ';
242
+        if ($usetable) {
243
+            print '</td><td>';
244
+        } else {
245
+            print ': ';
246
+        }
219 247
         print $object->import_key;
220
-        if ($usetable) print '</td></tr>';
221
-        else print '<br>';
248
+        if ($usetable) {
249
+            print '</td></tr>';
250
+        } else {
251
+            print '<br>';
252
+        }
222 253
     }
223 254
 
224 255
     // User creation (old method using already loaded object and not id is kept for backward compatibility)
225 256
     if (! empty($object->user_creation) || ! empty($object->user_creation_id))
226 257
     {
227
-        if ($usetable) print '<tr><td class="titlefield">';
258
+        if ($usetable) {
259
+            print '<tr><td class="titlefield">';
260
+        }
228 261
         print $langs->trans("CreatedBy");
229
-        if ($usetable) print '</td><td>';
230
-        else print ': ';
262
+        if ($usetable) {
263
+            print '</td><td>';
264
+        } else {
265
+            print ': ';
266
+        }
231 267
         if (is_object($object->user_creation))
232 268
         {
233
-        	if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
234
-        	else print $langs->trans("Unknown");
235
-        }
236
-        else
269
+        	if ($object->user_creation->id) {
270
+        	    print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
271
+        	} else {
272
+        	    print $langs->trans("Unknown");
273
+        	}
274
+        } else
237 275
         {
238 276
             $userstatic=new User($db);
239 277
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
240
-            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
241
-        	else print $langs->trans("Unknown");
278
+            if ($userstatic->id) {
279
+                print $userstatic->getNomUrl(1, '', 0, 0, 0);
280
+            } else {
281
+        	    print $langs->trans("Unknown");
282
+        	}
283
+        }
284
+        if ($usetable) {
285
+            print '</td></tr>';
286
+        } else {
287
+            print '<br>';
242 288
         }
243
-        if ($usetable) print '</td></tr>';
244
-        else print '<br>';
245 289
     }
246 290
 
247 291
     // Date creation
248 292
     if (! empty($object->date_creation))
249 293
     {
250
-        if ($usetable) print '<tr><td class="titlefield">';
294
+        if ($usetable) {
295
+            print '<tr><td class="titlefield">';
296
+        }
251 297
         print $langs->trans("DateCreation");
252
-        if ($usetable) print '</td><td>';
253
-        else print ': ';
298
+        if ($usetable) {
299
+            print '</td><td>';
300
+        } else {
301
+            print ': ';
302
+        }
254 303
         print dol_print_date($object->date_creation, 'dayhour');
255
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
256
-        if ($usetable) print '</td></tr>';
257
-        else print '<br>';
304
+        if ($deltadateforuser) {
305
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
306
+        }
307
+        if ($usetable) {
308
+            print '</td></tr>';
309
+        } else {
310
+            print '<br>';
311
+        }
258 312
     }
259 313
 
260 314
     // User change (old method using already loaded object and not id is kept for backward compatibility)
261 315
     if (! empty($object->user_modification) || ! empty($object->user_modification_id))
262 316
     {
263
-        if ($usetable) print '<tr><td class="titlefield">';
317
+        if ($usetable) {
318
+            print '<tr><td class="titlefield">';
319
+        }
264 320
         print $langs->trans("ModifiedBy");
265
-        if ($usetable) print '</td><td>';
266
-        else print ': ';
321
+        if ($usetable) {
322
+            print '</td><td>';
323
+        } else {
324
+            print ': ';
325
+        }
267 326
         if (is_object($object->user_modification))
268 327
         {
269
-        	if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
270
-        	else print $langs->trans("Unknown");
271
-        }
272
-        else
328
+        	if ($object->user_modification->id) {
329
+        	    print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
330
+        	} else {
331
+        	    print $langs->trans("Unknown");
332
+        	}
333
+        } else
273 334
         {
274 335
             $userstatic=new User($db);
275 336
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
276
-            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
277
-        	else print $langs->trans("Unknown");
337
+            if ($userstatic->id) {
338
+                print $userstatic->getNomUrl(1, '', 0, 0, 0);
339
+            } else {
340
+        	    print $langs->trans("Unknown");
341
+        	}
342
+        }
343
+        if ($usetable) {
344
+            print '</td></tr>';
345
+        } else {
346
+            print '<br>';
278 347
         }
279
-        if ($usetable) print '</td></tr>';
280
-        else print '<br>';
281 348
     }
282 349
 
283 350
     // Date change
284 351
     if (! empty($object->date_modification))
285 352
     {
286
-        if ($usetable) print '<tr><td class="titlefield">';
353
+        if ($usetable) {
354
+            print '<tr><td class="titlefield">';
355
+        }
287 356
         print $langs->trans("DateLastModification");
288
-        if ($usetable) print '</td><td>';
289
-        else print ': ';
357
+        if ($usetable) {
358
+            print '</td><td>';
359
+        } else {
360
+            print ': ';
361
+        }
290 362
         print dol_print_date($object->date_modification, 'dayhour');
291
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
292
-        if ($usetable) print '</td></tr>';
293
-        else print '<br>';
363
+        if ($deltadateforuser) {
364
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
365
+        }
366
+        if ($usetable) {
367
+            print '</td></tr>';
368
+        } else {
369
+            print '<br>';
370
+        }
294 371
     }
295 372
 
296 373
     // User validation (old method using already loaded object and not id is kept for backward compatibility)
297 374
     if (! empty($object->user_validation) || ! empty($object->user_validation_id))
298 375
     {
299
-        if ($usetable) print '<tr><td class="titlefield">';
376
+        if ($usetable) {
377
+            print '<tr><td class="titlefield">';
378
+        }
300 379
         print $langs->trans("ValidatedBy");
301
-        if ($usetable) print '</td><td>';
302
-        else print ': ';
380
+        if ($usetable) {
381
+            print '</td><td>';
382
+        } else {
383
+            print ': ';
384
+        }
303 385
         if (is_object($object->user_validation))
304 386
         {
305
-            if ($object->user_validation->id) print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
306
-        	else print $langs->trans("Unknown");
307
-        }
308
-        else
387
+            if ($object->user_validation->id) {
388
+                print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
389
+            } else {
390
+        	    print $langs->trans("Unknown");
391
+        	}
392
+        } else
309 393
         {
310 394
             $userstatic=new User($db);
311 395
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
312
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
313
-        	else print $langs->trans("Unknown");
396
+			if ($userstatic->id) {
397
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
398
+			} else {
399
+        	    print $langs->trans("Unknown");
400
+        	}
401
+        }
402
+        if ($usetable) {
403
+            print '</td></tr>';
404
+        } else {
405
+            print '<br>';
314 406
         }
315
-        if ($usetable) print '</td></tr>';
316
-        else print '<br>';
317 407
     }
318 408
 
319 409
     // Date validation
320 410
     if (! empty($object->date_validation))
321 411
     {
322
-        if ($usetable) print '<tr><td class="titlefield">';
412
+        if ($usetable) {
413
+            print '<tr><td class="titlefield">';
414
+        }
323 415
         print $langs->trans("DateValidation");
324
-        if ($usetable) print '</td><td>';
325
-        else print ': ';
416
+        if ($usetable) {
417
+            print '</td><td>';
418
+        } else {
419
+            print ': ';
420
+        }
326 421
         print dol_print_date($object->date_validation, 'dayhour');
327
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
328
-        if ($usetable) print '</td></tr>';
329
-        else print '<br>';
422
+        if ($deltadateforuser) {
423
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
424
+        }
425
+        if ($usetable) {
426
+            print '</td></tr>';
427
+        } else {
428
+            print '<br>';
429
+        }
330 430
     }
331 431
 
332 432
     // User approve (old method using already loaded object and not id is kept for backward compatibility)
333 433
     if (! empty($object->user_approve) || ! empty($object->user_approve_id))
334 434
     {
335
-        if ($usetable) print '<tr><td class="titlefield">';
435
+        if ($usetable) {
436
+            print '<tr><td class="titlefield">';
437
+        }
336 438
         print $langs->trans("ApprovedBy");
337
-        if ($usetable) print '</td><td>';
338
-        else print ': ';
439
+        if ($usetable) {
440
+            print '</td><td>';
441
+        } else {
442
+            print ': ';
443
+        }
339 444
         if (is_object($object->user_approve))
340 445
         {
341
-            if ($object->user_approve->id) print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
342
-        	else print $langs->trans("Unknown");
343
-        }
344
-        else
446
+            if ($object->user_approve->id) {
447
+                print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
448
+            } else {
449
+        	    print $langs->trans("Unknown");
450
+        	}
451
+        } else
345 452
         {
346 453
             $userstatic=new User($db);
347 454
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
348
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
349
-        	else print $langs->trans("Unknown");
455
+			if ($userstatic->id) {
456
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
457
+			} else {
458
+        	    print $langs->trans("Unknown");
459
+        	}
460
+        }
461
+        if ($usetable) {
462
+            print '</td></tr>';
463
+        } else {
464
+            print '<br>';
350 465
         }
351
-        if ($usetable) print '</td></tr>';
352
-        else print '<br>';
353 466
     }
354 467
 
355 468
     // Date approve
356 469
     if (! empty($object->date_approve))
357 470
     {
358
-        if ($usetable) print '<tr><td class="titlefield">';
471
+        if ($usetable) {
472
+            print '<tr><td class="titlefield">';
473
+        }
359 474
         print $langs->trans("DateApprove");
360
-        if ($usetable) print '</td><td>';
361
-        else print ': ';
475
+        if ($usetable) {
476
+            print '</td><td>';
477
+        } else {
478
+            print ': ';
479
+        }
362 480
         print dol_print_date($object->date_approve, 'dayhour');
363
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
364
-        if ($usetable) print '</td></tr>';
365
-        else print '<br>';
481
+        if ($deltadateforuser) {
482
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
483
+        }
484
+        if ($usetable) {
485
+            print '</td></tr>';
486
+        } else {
487
+            print '<br>';
488
+        }
366 489
     }
367 490
 
368 491
     // User approve
369 492
     if (! empty($object->user_approve_id2))
370 493
     {
371
-        if ($usetable) print '<tr><td class="titlefield">';
494
+        if ($usetable) {
495
+            print '<tr><td class="titlefield">';
496
+        }
372 497
         print $langs->trans("ApprovedBy");
373
-        if ($usetable) print '</td><td>';
374
-        else print ': ';
498
+        if ($usetable) {
499
+            print '</td><td>';
500
+        } else {
501
+            print ': ';
502
+        }
375 503
         $userstatic=new User($db);
376 504
         $userstatic->fetch($object->user_approve_id2);
377
-        if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
378
-        else print $langs->trans("Unknown");
379
-        if ($usetable) print '</td></tr>';
380
-        else print '<br>';
505
+        if ($userstatic->id) {
506
+            print $userstatic->getNomUrl(1, '', 0, 0, 0);
507
+        } else {
508
+            print $langs->trans("Unknown");
509
+        }
510
+        if ($usetable) {
511
+            print '</td></tr>';
512
+        } else {
513
+            print '<br>';
514
+        }
381 515
     }
382 516
 
383 517
     // Date approve
384 518
     if (! empty($object->date_approve2))
385 519
     {
386
-        if ($usetable) print '<tr><td class="titlefield">';
520
+        if ($usetable) {
521
+            print '<tr><td class="titlefield">';
522
+        }
387 523
         print $langs->trans("DateApprove2");
388
-        if ($usetable) print '</td><td>';
389
-        else print ': ';
524
+        if ($usetable) {
525
+            print '</td><td>';
526
+        } else {
527
+            print ': ';
528
+        }
390 529
         print dol_print_date($object->date_approve2, 'dayhour');
391
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
392
-        if ($usetable) print '</td></tr>';
393
-        else print '<br>';
530
+        if ($deltadateforuser) {
531
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
532
+        }
533
+        if ($usetable) {
534
+            print '</td></tr>';
535
+        } else {
536
+            print '<br>';
537
+        }
394 538
     }
395 539
 
396 540
     // User close
397 541
     if (! empty($object->user_cloture))
398 542
     {
399
-        if ($usetable) print '<tr><td class="titlefield">';
543
+        if ($usetable) {
544
+            print '<tr><td class="titlefield">';
545
+        }
400 546
         print $langs->trans("ClosedBy");
401
-        if ($usetable) print '</td><td>';
402
-        else print ': ';
547
+        if ($usetable) {
548
+            print '</td><td>';
549
+        } else {
550
+            print ': ';
551
+        }
403 552
         if (is_object($object->user_cloture))
404 553
         {
405
-			if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
406
-        	else print $langs->trans("Unknown");
407
-        }
408
-        else
554
+			if ($object->user_cloture->id) {
555
+			    print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
556
+			} else {
557
+        	    print $langs->trans("Unknown");
558
+        	}
559
+        } else
409 560
         {
410 561
             $userstatic=new User($db);
411 562
             $userstatic->fetch($object->user_cloture);
412
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
413
-        	else print $langs->trans("Unknown");
563
+			if ($userstatic->id) {
564
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
565
+			} else {
566
+        	    print $langs->trans("Unknown");
567
+        	}
568
+        }
569
+        if ($usetable) {
570
+            print '</td></tr>';
571
+        } else {
572
+            print '<br>';
414 573
         }
415
-        if ($usetable) print '</td></tr>';
416
-        else print '<br>';
417 574
     }
418 575
 
419 576
     // Date close
420 577
     if (! empty($object->date_cloture))
421 578
     {
422
-        if ($usetable) print '<tr><td class="titlefield">';
579
+        if ($usetable) {
580
+            print '<tr><td class="titlefield">';
581
+        }
423 582
         print $langs->trans("DateClosing");
424
-        if ($usetable) print '</td><td>';
425
-        else print ': ';
583
+        if ($usetable) {
584
+            print '</td><td>';
585
+        } else {
586
+            print ': ';
587
+        }
426 588
         print dol_print_date($object->date_cloture, 'dayhour');
427
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
428
-        if ($usetable) print '</td></tr>';
429
-        else print '<br>';
589
+        if ($deltadateforuser) {
590
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
591
+        }
592
+        if ($usetable) {
593
+            print '</td></tr>';
594
+        } else {
595
+            print '<br>';
596
+        }
430 597
     }
431 598
 
432 599
     // User conciliate
433 600
     if (! empty($object->user_rappro))
434 601
     {
435
-        if ($usetable) print '<tr><td class="titlefield">';
602
+        if ($usetable) {
603
+            print '<tr><td class="titlefield">';
604
+        }
436 605
         print $langs->trans("ConciliatedBy");
437
-        if ($usetable) print '</td><td>';
438
-        else print ': ';
606
+        if ($usetable) {
607
+            print '</td><td>';
608
+        } else {
609
+            print ': ';
610
+        }
439 611
         if (is_object($object->user_rappro))
440 612
         {
441
-			if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
442
-        	else print $langs->trans("Unknown");
443
-        }
444
-        else
613
+			if ($object->user_rappro->id) {
614
+			    print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
615
+			} else {
616
+        	    print $langs->trans("Unknown");
617
+        	}
618
+        } else
445 619
         {
446 620
             $userstatic=new User($db);
447 621
             $userstatic->fetch($object->user_rappro);
448
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
449
-        	else print $langs->trans("Unknown");
622
+			if ($userstatic->id) {
623
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
624
+			} else {
625
+        	    print $langs->trans("Unknown");
626
+        	}
627
+        }
628
+        if ($usetable) {
629
+            print '</td></tr>';
630
+        } else {
631
+            print '<br>';
450 632
         }
451
-        if ($usetable) print '</td></tr>';
452
-        else print '<br>';
453 633
     }
454 634
 
455 635
     // Date conciliate
456 636
     if (! empty($object->date_rappro))
457 637
     {
458
-        if ($usetable) print '<tr><td class="titlefield">';
638
+        if ($usetable) {
639
+            print '<tr><td class="titlefield">';
640
+        }
459 641
         print $langs->trans("DateConciliating");
460
-        if ($usetable) print '</td><td>';
461
-        else print ': ';
642
+        if ($usetable) {
643
+            print '</td><td>';
644
+        } else {
645
+            print ': ';
646
+        }
462 647
         print dol_print_date($object->date_rappro, 'dayhour');
463
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
464
-        if ($usetable) print '</td></tr>';
465
-        else print '<br>';
648
+        if ($deltadateforuser) {
649
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
650
+        }
651
+        if ($usetable) {
652
+            print '</td></tr>';
653
+        } else {
654
+            print '<br>';
655
+        }
466 656
     }
467 657
 
468 658
     // Date send
469 659
     if (! empty($object->date_envoi))
470 660
     {
471
-        if ($usetable) print '<tr><td class="titlefield">';
661
+        if ($usetable) {
662
+            print '<tr><td class="titlefield">';
663
+        }
472 664
         print $langs->trans("DateLastSend");
473
-        if ($usetable) print '</td><td>';
474
-        else print ': ';
665
+        if ($usetable) {
666
+            print '</td><td>';
667
+        } else {
668
+            print ': ';
669
+        }
475 670
         print dol_print_date($object->date_envoi, 'dayhour');
476
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
477
-        if ($usetable) print '</td></tr>';
478
-        else print '<br>';
671
+        if ($deltadateforuser) {
672
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
673
+        }
674
+        if ($usetable) {
675
+            print '</td></tr>';
676
+        } else {
677
+            print '<br>';
678
+        }
479 679
     }
480 680
 
481
-    if ($usetable) print '</table>';
482
-}
681
+    if ($usetable) {
682
+        print '</table>';
683
+    }
684
+    }
483 685
 
484 686
 
485 687
 /**
@@ -508,8 +710,7 @@  discard block
 block discarded – undo
508 710
     if (checkdnsrr($domain, "MX"))
509 711
     {
510 712
         return true;
511
-    }
512
-    else
713
+    } else
513 714
     {
514 715
         return false;
515 716
     }
@@ -534,10 +735,14 @@  discard block
 block discarded – undo
534 735
     $urlregex = '';
535 736
 
536 737
     // SCHEME
537
-    if ($http) $urlregex .= "^(http:\/\/|https:\/\/)";
738
+    if ($http) {
739
+        $urlregex .= "^(http:\/\/|https:\/\/)";
740
+    }
538 741
 
539 742
     // USER AND PASS
540
-    if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
743
+    if ($pass) {
744
+        $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
745
+    }
541 746
 
542 747
     // HOSTNAME OR IP
543 748
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // x allowed (ex. http://localhost, http://routerlogin)
@@ -546,13 +751,21 @@  discard block
 block discarded – undo
546 751
     //use only one of the above
547 752
 
548 753
     // PORT
549
-    if ($port) $urlregex .= "(\:[0-9]{2,5})";
754
+    if ($port) {
755
+        $urlregex .= "(\:[0-9]{2,5})";
756
+    }
550 757
     // PATH
551
-    if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
758
+    if ($path) {
759
+        $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
760
+    }
552 761
     // GET Query
553
-    if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
762
+    if ($query) {
763
+        $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
764
+    }
554 765
     // ANCHOR
555
-    if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
766
+    if ($anchor) {
767
+        $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
768
+    }
556 769
 
557 770
     // check
558 771
     if (preg_match('/'.$urlregex.'/i', $url))
@@ -600,9 +813,10 @@  discard block
 block discarded – undo
600 813
         $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
601 814
 
602 815
         return $CleanUrl;
816
+    } else {
817
+        return $url;
818
+    }
603 819
     }
604
-    else return $url;
605
-}
606 820
 
607 821
 
608 822
 
@@ -619,7 +833,9 @@  discard block
 block discarded – undo
619 833
  */
620 834
 function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
621 835
 {
622
-	if(!isValidEmail($mail))return '';
836
+	if(!isValidEmail($mail)) {
837
+	    return '';
838
+	}
623 839
 	$tab = explode('@', $mail);
624 840
 	$tab2 = explode('.',$tab[1]);
625 841
 	$string_replace = '';
@@ -681,7 +897,9 @@  discard block
 block discarded – undo
681 897
 function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
682 898
 {
683 899
     $text='' ;
684
-    if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
900
+    if($tableMarkup) {
901
+        $text = '<table '.$tableoptions.'>' ;
902
+    }
685 903
     foreach($data as $key => $item){
686 904
         if(is_array($item)){
687 905
             $text.=array2tr($item,$troptions,$tdoptions);
@@ -692,7 +910,9 @@  discard block
 block discarded – undo
692 910
             $text.= '</tr>' ;
693 911
         }
694 912
     }
695
-    if($tableMarkup) $text.= '</table>' ;
913
+    if($tableMarkup) {
914
+        $text.= '</table>' ;
915
+    }
696 916
     return $text ;
697 917
 }
698 918
 
@@ -716,15 +936,25 @@  discard block
 block discarded – undo
716 936
 {
717 937
     global $conf,$user;
718 938
 
719
-    if (! is_object($objsoc)) $valueforccc=$objsoc;
720
-    else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
721
-    else $valueforccc=$objsoc->code_client;
939
+    if (! is_object($objsoc)) {
940
+        $valueforccc=$objsoc;
941
+    } else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) {
942
+        $valueforccc=$objsoc->code_fournisseur;
943
+    } else {
944
+        $valueforccc=$objsoc->code_client;
945
+    }
722 946
 
723 947
     $sharetable = $table;
724
-    if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
948
+    if ($table == 'facture' || $table == 'invoice') {
949
+        $sharetable = 'invoicenumber';
950
+    }
951
+    // for getEntity function
725 952
 
726 953
     // Clean parameters
727
-    if ($date == '') $date=dol_now();	// We use local year and month of PHP server to search numbers
954
+    if ($date == '') {
955
+        $date=dol_now();
956
+    }
957
+    // We use local year and month of PHP server to search numbers
728 958
     // but we should use local year and month of user
729 959
 
730 960
     // For debugging
@@ -741,8 +971,7 @@  discard block
 block discarded – undo
741 971
         $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
742 972
         $maskcounter=$reg[1];
743 973
         $hasglobalcounter=true;
744
-    }
745
-    else
974
+    } else
746 975
     {
747 976
         // setting some defaults so the rest of the code won't fail if there is a third party counter
748 977
         $masktri='00000';
@@ -752,7 +981,9 @@  discard block
 block discarded – undo
752 981
     $maskraz=-1;
753 982
     $maskoffset=0;
754 983
     $resetEveryMonth=false;
755
-    if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
984
+    if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) {
985
+        return 'ErrorCounterMustHaveMoreThan3Digits';
986
+    }
756 987
 
757 988
     // Extract value for third party mask counter
758 989
     if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
@@ -764,9 +995,12 @@  discard block
 block discarded – undo
764 995
         $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
765 996
         $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
766 997
         $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
767
-        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
998
+        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
999
+            return 'ErrorCounterMustHaveMoreThan3Digits';
1000
+        }
1001
+    } else {
1002
+        $maskrefclient='';
768 1003
     }
769
-    else $maskrefclient='';
770 1004
 
771 1005
     // fail if there is neither a global nor a third party counter
772 1006
     if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
@@ -780,8 +1014,7 @@  discard block
 block discarded – undo
780 1014
         $masktype=$regType[1];
781 1015
         $masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
782 1016
         $masktype_value=str_pad($masktype_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
783
-    }
784
-    else
1017
+    } else
785 1018
     {
786 1019
     	$masktype='';
787 1020
     	$masktype_value='';
@@ -791,13 +1024,14 @@  discard block
 block discarded – undo
791 1024
     if (preg_match('/\{(u+)\}/i',$mask,$regType))
792 1025
     {
793 1026
     	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
794
-    	if (is_object($objuser)) $lastname = $objuser->lastname;
1027
+    	if (is_object($objuser)) {
1028
+    	    $lastname = $objuser->lastname;
1029
+    	}
795 1030
 
796 1031
     	$maskuser=$regType[1];
797 1032
     	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
798 1033
     	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
799
-    }
800
-    else
1034
+    } else
801 1035
     {
802 1036
     	$maskuser='';
803 1037
     	$maskuser_value='';
@@ -844,8 +1078,12 @@  discard block
 block discarded – undo
844 1078
     //var_dump($reg);
845 1079
 
846 1080
     // If an offset is asked
847
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
848
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1081
+    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) {
1082
+        $maskoffset=preg_replace('/^\+/','',$reg[2]);
1083
+    }
1084
+    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) {
1085
+        $maskoffset=preg_replace('/^\+/','',$reg[3]);
1086
+    }
849 1087
 
850 1088
     // Define $sqlwhere
851 1089
     $sqlwhere='';
@@ -853,14 +1091,21 @@  discard block
 block discarded – undo
853 1091
     $yearoffsettype=false;		// false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
854 1092
 
855 1093
     // If a restore to zero after a month is asked we check if there is already a value for this year.
856
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))	$yearoffsettype = preg_replace('/^@/','',$reg[2]);
857
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))	$yearoffsettype = preg_replace('/^@/','',$reg[3]);
1094
+    if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) {
1095
+        $yearoffsettype = preg_replace('/^@/','',$reg[2]);
1096
+    }
1097
+    if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) {
1098
+        $yearoffsettype = preg_replace('/^@/','',$reg[3]);
1099
+    }
858 1100
 
859 1101
     //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
860
-    if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
861
-        $maskraz=$yearoffsettype; // For backward compatibility
862
-    else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
863
-        $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
1102
+    if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) {
1103
+            $maskraz=$yearoffsettype;
1104
+    }
1105
+    // For backward compatibility
1106
+    else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) {
1107
+            $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
1108
+    }
864 1109
     //print "maskraz=".$maskraz;	// -1=no reset
865 1110
 
866 1111
     if ($maskraz > 0) {   // A reset is required
@@ -868,23 +1113,28 @@  discard block
 block discarded – undo
868 1113
             $maskraz = date('m', $date);
869 1114
             $resetEveryMonth = true;
870 1115
         }
871
-        if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1116
+        if ($maskraz > 12) {
1117
+            return 'ErrorBadMaskBadRazMonth';
1118
+        }
872 1119
 
873 1120
         // Define posy, posm and reg
874
-        if ($maskraz > 1)	// if reset is not first month, we need month and year into mask
1121
+        if ($maskraz > 1) {
1122
+            // if reset is not first month, we need month and year into mask
875 1123
         {
876
-            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
877
-            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
878
-            else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
879
-
880
-            if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
1124
+            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2;
881 1125
         }
882
-        else // if reset is for a specific month in year, we need year
1126
+        $posm=3; } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; } else {
1127
+                return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1128
+            }
1129
+
1130
+            if (dol_strlen($reg[$posy]) < 2) {
1131
+                return 'ErrorCantUseRazWithYearOnOneDigit';
1132
+            }
1133
+        } else // if reset is for a specific month in year, we need year
883 1134
         {
884
-            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
885
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
886
-            else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
887
-            else return 'ErrorCantUseRazIfNoYearInMask';
1135
+            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; } else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; } else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; } else {
1136
+                return 'ErrorCantUseRazIfNoYearInMask';
1137
+            }
888 1138
         }
889 1139
         // Define length
890 1140
         $yearlen = $posy?dol_strlen($reg[$posy]):0;
@@ -902,9 +1152,11 @@  discard block
 block discarded – undo
902 1152
         $monthcomp=$maskraz;
903 1153
         $yearcomp=0;
904 1154
 
905
-        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
1155
+        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') {
1156
+            // $yearoffsettype is - or +
906 1157
         {
907 1158
         	$currentyear=date("Y", $date);
1159
+        }
908 1160
         	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
909 1161
         	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
910 1162
         	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
@@ -914,21 +1166,32 @@  discard block
 block discarded – undo
914 1166
         	if ($date >= $fiscaldate)
915 1167
         	{
916 1168
         		// If before of next new year date
917
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
1169
+        		if ($date < $nextnewyeardate && $yearoffsettype == '+') {
1170
+        		    $yearoffset=1;
1171
+        		}
918 1172
         	}
919 1173
         	// If after or equal of current new year date
920
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
1174
+        	else if ($date >= $newyeardate && $yearoffsettype == '-') {
1175
+        	    $yearoffset=-1;
1176
+        	}
921 1177
         }
922 1178
         // For backward compatibility
923 1179
         else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
924 1180
 
925
-        if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
926
-        elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
927
-        elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
928
-        if ($monthcomp > 1 && empty($resetEveryMonth))	// Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
1181
+        if ($yearlen == 4) {
1182
+            $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
1183
+        } elseif ($yearlen == 2) {
1184
+            $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
1185
+        } elseif ($yearlen == 1) {
1186
+            $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
1187
+        }
1188
+        if ($monthcomp > 1 && empty($resetEveryMonth)) {
1189
+            // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
929 1190
         {
930 1191
             if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
931
-            elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
1192
+        } elseif ($yearlen == 2) {
1193
+                $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
1194
+            }
932 1195
 
933 1196
             $sqlwhere.="(";
934 1197
             $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
@@ -937,13 +1200,11 @@  discard block
 block discarded – undo
937 1200
             $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
938 1201
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
939 1202
             $sqlwhere.=')';
940
-        }
941
-		else if ($resetEveryMonth)
1203
+        } else if ($resetEveryMonth)
942 1204
 		{
943 1205
 			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
944 1206
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
945
-		}
946
-        else   // reset is done on january
1207
+		} else   // reset is done on january
947 1208
         {
948 1209
             $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
949 1210
         }
@@ -955,12 +1216,13 @@  discard block
 block discarded – undo
955 1216
     if (function_exists('mb_strrpos'))
956 1217
     	{
957 1218
     	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
958
-	}
959
-	else
1219
+	} else
960 1220
 	{
961 1221
     	$posnumstart=strrpos($maskwithnocode,$maskcounter);
962 1222
 	}	// Pos of counter in final string (from 0 to ...)
963
-    if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
1223
+    if ($posnumstart < 0) {
1224
+        return 'ErrorBadMaskFailedToLocatePosOfSequence';
1225
+    }
964 1226
     $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
965 1227
 
966 1228
     // Define $maskLike
@@ -973,9 +1235,15 @@  discard block
 block discarded – undo
973 1235
     $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
974 1236
     $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
975 1237
     $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
976
-    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
977
-    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
978
-    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1238
+    if ($maskrefclient) {
1239
+        $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1240
+    }
1241
+    if ($masktype) {
1242
+        $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1243
+    }
1244
+    if ($maskuser) {
1245
+        $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1246
+    }
979 1247
     foreach($maskperso as $key => $val)
980 1248
     {
981 1249
     	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
@@ -987,12 +1255,18 @@  discard block
 block discarded – undo
987 1255
     $sql.= " FROM ".MAIN_DB_PREFIX.$table;
988 1256
     $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
989 1257
 	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
990
-    if ($bentityon) // only if entity enable
1258
+    if ($bentityon) {
1259
+        // only if entity enable
991 1260
     	$sql.= " AND entity IN (".getEntity($sharetable).")";
992
-    else if (! empty($forceentity))
993
-    	$sql.= " AND entity IN (".$forceentity.")";
994
-    if ($where) $sql.=$where;
995
-    if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1261
+    } else if (! empty($forceentity)) {
1262
+        	$sql.= " AND entity IN (".$forceentity.")";
1263
+    }
1264
+    if ($where) {
1265
+        $sql.=$where;
1266
+    }
1267
+    if ($sqlwhere) {
1268
+        $sql.=' AND '.$sqlwhere;
1269
+    }
996 1270
 
997 1271
     //print $sql.'<br>';
998 1272
     dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
@@ -1001,21 +1275,26 @@  discard block
 block discarded – undo
1001 1275
     {
1002 1276
         $obj = $db->fetch_object($resql);
1003 1277
         $counter = $obj->val;
1278
+    } else {
1279
+        dol_print_error($db);
1004 1280
     }
1005
-    else dol_print_error($db);
1006 1281
 
1007 1282
     // Check if we must force counter to maskoffset
1008
-    if (empty($counter)) $counter=$maskoffset;
1009
-    else if (preg_match('/[^0-9]/i',$counter))
1283
+    if (empty($counter)) {
1284
+        $counter=$maskoffset;
1285
+    } else if (preg_match('/[^0-9]/i',$counter))
1010 1286
     {
1011 1287
     	$counter=0;
1012 1288
     	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1289
+    } else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) {
1290
+        $counter=$maskoffset;
1013 1291
     }
1014
-    else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
1015 1292
 
1016
-    if ($mode == 'last')	// We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1293
+    if ($mode == 'last') {
1294
+        // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1017 1295
     {
1018 1296
         $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1297
+    }
1019 1298
 
1020 1299
         // Define $maskLike
1021 1300
         $maskLike = dol_string_nospecial($mask);
@@ -1027,34 +1306,48 @@  discard block
 block discarded – undo
1027 1306
         $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
1028 1307
         $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
1029 1308
         $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
1030
-        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1031
-        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1032
-        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1309
+        if ($maskrefclient) {
1310
+            $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1311
+        }
1312
+        if ($masktype) {
1313
+            $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1314
+        }
1315
+        if ($maskuser) {
1316
+            $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1317
+        }
1033 1318
 
1034 1319
         $ref='';
1035 1320
         $sql = "SELECT ".$field." as ref";
1036 1321
         $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1037 1322
         $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1038 1323
     	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1039
-    	if ($bentityon) // only if entity enable
1324
+    	if ($bentityon) {
1325
+    	    // only if entity enable
1040 1326
         	$sql.= " AND entity IN (".getEntity($sharetable).")";
1041
-        else if (! empty($forceentity))
1042
-        	$sql.= " AND entity IN (".$forceentity.")";
1043
-        if ($where) $sql.=$where;
1044
-        if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1327
+    	} else if (! empty($forceentity)) {
1328
+                	$sql.= " AND entity IN (".$forceentity.")";
1329
+        }
1330
+        if ($where) {
1331
+            $sql.=$where;
1332
+        }
1333
+        if ($sqlwhere) {
1334
+            $sql.=' AND '.$sqlwhere;
1335
+        }
1045 1336
 
1046 1337
         dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1047 1338
         $resql=$db->query($sql);
1048 1339
         if ($resql)
1049 1340
         {
1050 1341
             $obj = $db->fetch_object($resql);
1051
-            if ($obj) $ref = $obj->ref;
1342
+            if ($obj) {
1343
+                $ref = $obj->ref;
1344
+            }
1345
+        } else {
1346
+            dol_print_error($db);
1052 1347
         }
1053
-        else dol_print_error($db);
1054 1348
 
1055 1349
         $numFinal=$ref;
1056
-    }
1057
-    else if ($mode == 'next')
1350
+    } else if ($mode == 'next')
1058 1351
     {
1059 1352
         $counter++;
1060 1353
 
@@ -1070,7 +1363,9 @@  discard block
 block discarded – undo
1070 1363
 
1071 1364
             // Define $sqlstring
1072 1365
             $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient));	// Pos of counter in final string (from 0 to ...)
1073
-            if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
1366
+            if ($maskrefclient_posnumstart <= 0) {
1367
+                return 'ErrorBadMask';
1368
+            }
1074 1369
             $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
1075 1370
             //print "x".$sqlstring;
1076 1371
 
@@ -1092,12 +1387,20 @@  discard block
 block discarded – undo
1092 1387
             $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
1093 1388
             //$sql.= " WHERE ".$field." not like '(%'";
1094 1389
             $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1095
-            if ($bentityon) // only if entity enable
1390
+            if ($bentityon) {
1391
+                // only if entity enable
1096 1392
             	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1097
-            else if (! empty($forceentity))
1098
-            	$sql.= " AND entity IN (".$forceentity.")";
1099
-            if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1100
-            if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1393
+            } else if (! empty($forceentity)) {
1394
+                        	$sql.= " AND entity IN (".$forceentity.")";
1395
+            }
1396
+            if ($where) {
1397
+                $maskrefclient_sql.=$where;
1398
+            }
1399
+            //use the same optional where as general mask
1400
+            if ($sqlwhere) {
1401
+                $maskrefclient_sql.=' AND '.$sqlwhere;
1402
+            }
1403
+            //use the same sqlwhere as general mask
1101 1404
             $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1102 1405
 
1103 1406
             dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
@@ -1106,10 +1409,13 @@  discard block
 block discarded – undo
1106 1409
             {
1107 1410
                 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
1108 1411
                 $maskrefclient_counter = $maskrefclient_obj->val;
1412
+            } else {
1413
+                dol_print_error($db);
1109 1414
             }
1110
-            else dol_print_error($db);
1111 1415
 
1112
-            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1416
+            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) {
1417
+                $maskrefclient_counter=$maskrefclient_maskoffset;
1418
+            }
1113 1419
 			$maskrefclient_counter++;
1114 1420
         }
1115 1421
 
@@ -1117,13 +1423,14 @@  discard block
 block discarded – undo
1117 1423
         $numFinal = $mask;
1118 1424
 
1119 1425
         // We replace special codes except refclient
1120
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1426
+		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') {
1427
+		    // yearoffsettype is - or +, so we don't want current year
1121 1428
 		{
1122 1429
 	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1430
+		}
1123 1431
         	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1124 1432
         	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1125
-		}
1126
-		else	// we want yyyy to be current year
1433
+		} else	// we want yyyy to be current year
1127 1434
 		{
1128 1435
         	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1129 1436
         	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
@@ -1180,7 +1487,9 @@  discard block
 block discarded – undo
1180 1487
 {
1181 1488
     $string = " ".$string;
1182 1489
      $ini = strpos($string,$start);
1183
-     if ($ini == 0) return "";
1490
+     if ($ini == 0) {
1491
+         return "";
1492
+     }
1184 1493
      $ini += strlen($start);
1185 1494
      $len = strpos($string,$end,$ini) - $ini;
1186 1495
      return substr($string,$ini,$len);
@@ -1204,8 +1513,7 @@  discard block
 block discarded – undo
1204 1513
         $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
1205 1514
         $maskcounter=$reg[1];
1206 1515
         $hasglobalcounter=true;
1207
-    }
1208
-    else
1516
+    } else
1209 1517
     {
1210 1518
         // setting some defaults so the rest of the code won't fail if there is a third party counter
1211 1519
         $masktri='00000';
@@ -1214,7 +1522,9 @@  discard block
 block discarded – undo
1214 1522
 
1215 1523
     $maskraz=-1;
1216 1524
     $maskoffset=0;
1217
-    if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1525
+    if (dol_strlen($maskcounter) < 3) {
1526
+        return 'ErrorCounterMustHaveMoreThan3Digits';
1527
+    }
1218 1528
 
1219 1529
     // Extract value for third party mask counter
1220 1530
     if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
@@ -1226,9 +1536,12 @@  discard block
 block discarded – undo
1226 1536
         $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
1227 1537
         $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1228 1538
         $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
1229
-        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1539
+        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
1540
+            return 'ErrorCounterMustHaveMoreThan3Digits';
1541
+        }
1542
+    } else {
1543
+        $maskrefclient='';
1230 1544
     }
1231
-    else $maskrefclient='';
1232 1545
 
1233 1546
     // fail if there is neither a global nor a third party counter
1234 1547
     if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
@@ -1250,21 +1563,35 @@  discard block
 block discarded – undo
1250 1563
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1251 1564
 
1252 1565
     // If an offset is asked
1253
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
1254
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1566
+    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) {
1567
+        $maskoffset=preg_replace('/^\+/','',$reg[2]);
1568
+    }
1569
+    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) {
1570
+        $maskoffset=preg_replace('/^\+/','',$reg[3]);
1571
+    }
1255 1572
 
1256 1573
     // Define $sqlwhere
1257 1574
 
1258 1575
     // If a restore to zero after a month is asked we check if there is already a value for this year.
1259
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))  $maskraz=preg_replace('/^@/','',$reg[2]);
1260
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))  $maskraz=preg_replace('/^@/','',$reg[3]);
1576
+    if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) {
1577
+        $maskraz=preg_replace('/^@/','',$reg[2]);
1578
+    }
1579
+    if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) {
1580
+        $maskraz=preg_replace('/^@/','',$reg[3]);
1581
+    }
1261 1582
     if ($maskraz >= 0)
1262 1583
     {
1263
-        if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1584
+        if ($maskraz > 12) {
1585
+            return 'ErrorBadMaskBadRazMonth';
1586
+        }
1264 1587
 
1265 1588
         // Define reg
1266
-        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1267
-        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
1589
+        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) {
1590
+            return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1591
+        }
1592
+        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) {
1593
+            return 'ErrorCantUseRazIfNoYearInMask';
1594
+        }
1268 1595
         //print "x".$maskwithonlyymcode." ".$maskraz;
1269 1596
     }
1270 1597
     //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
@@ -1274,7 +1601,9 @@  discard block
 block discarded – undo
1274 1601
 
1275 1602
     // Check length
1276 1603
     $len=dol_strlen($maskwithnocode);
1277
-    if (dol_strlen($value) != $len) $result=-1;
1604
+    if (dol_strlen($value) != $len) {
1605
+        $result=-1;
1606
+    }
1278 1607
 
1279 1608
     // Define $maskLike
1280 1609
     /* seems not used
@@ -1355,29 +1684,37 @@  discard block
 block discarded – undo
1355 1684
      */
1356 1685
 
1357 1686
     // Definition du Jeudi de la semaine
1358
-    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
1687
+    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) {
1688
+        // Dimanche
1359 1689
     $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
1360
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
1690
+    } else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) {
1691
+        // du Lundi au Mercredi
1361 1692
     $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
1362
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
1693
+    } else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) {
1694
+        // du Vendredi au Samedi
1363 1695
     $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
1364
-    else // Jeudi
1696
+    } else {
1697
+        // Jeudi
1365 1698
     $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
1699
+    }
1366 1700
 
1367 1701
     // Definition du premier Jeudi de l'annee
1368
-    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
1702
+    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) {
1703
+        // Dimanche
1369 1704
     {
1370 1705
         $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
1371 1706
     }
1372
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
1707
+    } else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) {
1708
+        // du Lundi au Mercredi
1373 1709
     {
1374 1710
         $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60;
1375 1711
     }
1376
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
1712
+    } else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) {
1713
+        // du Vendredi au Samedi
1377 1714
     {
1378 1715
         $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60;
1379 1716
     }
1380
-    else // Jeudi
1717
+    } else // Jeudi
1381 1718
     {
1382 1719
         $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
1383 1720
     }
@@ -1398,8 +1735,7 @@  discard block
 block discarded – undo
1398 1735
         if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365))
1399 1736
         {
1400 1737
             $numeroSemaine = 53;
1401
-        }
1402
-        else
1738
+        } else
1403 1739
         {
1404 1740
             $numeroSemaine = 1;
1405 1741
         }
@@ -1458,7 +1794,9 @@  discard block
 block discarded – undo
1458 1794
 function dol_set_user_param($db, $conf, &$user, $tab)
1459 1795
 {
1460 1796
     // Verification parametres
1461
-    if (count($tab) < 1) return -1;
1797
+    if (count($tab) < 1) {
1798
+        return -1;
1799
+    }
1462 1800
 
1463 1801
     $db->begin();
1464 1802
 
@@ -1470,7 +1808,9 @@  discard block
 block discarded – undo
1470 1808
     $i=0;
1471 1809
     foreach ($tab as $key => $value)
1472 1810
     {
1473
-        if ($i > 0) $sql.=',';
1811
+        if ($i > 0) {
1812
+            $sql.=',';
1813
+        }
1474 1814
         $sql.="'".$db->escape($key)."'";
1475 1815
         $i++;
1476 1816
     }
@@ -1504,8 +1844,7 @@  discard block
 block discarded – undo
1504 1844
             }
1505 1845
             $user->conf->$key = $value;
1506 1846
             //print "key=".$key." user->conf->key=".$user->conf->$key;
1507
-        }
1508
-        else
1847
+        } else
1509 1848
         {
1510 1849
             unset($user->conf->$key);
1511 1850
         }
@@ -1528,8 +1867,7 @@  discard block
 block discarded – undo
1528 1867
     if ($reduction == 100)
1529 1868
     {
1530 1869
         $string = $langs->transnoentities("Offered");
1531
-    }
1532
-    else
1870
+    } else
1533 1871
     {
1534 1872
     	$string = vatrate($reduction,true);
1535 1873
     }
@@ -1616,9 +1954,11 @@  discard block
 block discarded – undo
1616 1954
 
1617 1955
             // If this generation module needs to scan a directory, then description field is filled
1618 1956
             // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1619
-            if (! empty($obj->description))	// A list of directories to scan is defined
1957
+            if (! empty($obj->description)) {
1958
+                // A list of directories to scan is defined
1620 1959
             {
1621 1960
                 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1961
+            }
1622 1962
 
1623 1963
                 $const=$obj->description;
1624 1964
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
@@ -1637,7 +1977,9 @@  discard block
 block discarded – undo
1637 1977
                     {
1638 1978
 			// all type of template is allowed
1639 1979
 			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1640
-                        if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1980
+                        if (count($tmpfiles)) {
1981
+                            $listoffiles=array_merge($listoffiles,$tmpfiles);
1982
+                        }
1641 1983
                     }
1642 1984
                 }
1643 1985
 
@@ -1648,40 +1990,41 @@  discard block
 block discarded – undo
1648 1990
                         $max=($maxfilenamelength?$maxfilenamelength:28);
1649 1991
                         $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
1650 1992
                     }
1651
-                }
1652
-                else
1993
+                } else
1653 1994
                 {
1654 1995
                     $liste[0]=$obj->label.': '.$langs->trans("None");
1655 1996
                 }
1656
-            }
1657
-            else
1997
+            } else
1658 1998
             {
1659
-                if ($type == 'member' && $obj->lib == 'standard')   // Special case, if member template, we add variant per format
1999
+                if ($type == 'member' && $obj->lib == 'standard') {
2000
+                    // Special case, if member template, we add variant per format
1660 2001
                 {
1661 2002
                     global $_Avery_Labels;
2003
+                }
1662 2004
                     include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1663 2005
                     foreach($_Avery_Labels as $key => $val)
1664 2006
                     {
1665 2007
                         $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
1666 2008
                     }
1667
-                }
1668
-                else    // Common usage
2009
+                } else    // Common usage
1669 2010
                 {
1670 2011
                     $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
1671 2012
                 }
1672 2013
             }
1673 2014
             $i++;
1674 2015
         }
1675
-    }
1676
-    else
2016
+    } else
1677 2017
     {
1678 2018
         dol_print_error($db);
1679 2019
         return -1;
1680 2020
     }
1681 2021
 
1682
-    if ($found) return $liste;
1683
-    else return 0;
1684
-}
2022
+    if ($found) {
2023
+        return $liste;
2024
+    } else {
2025
+        return 0;
2026
+    }
2027
+    }
1685 2028
 
1686 2029
 /**
1687 2030
  * This function evaluates a string that should be a valid IPv4
@@ -1696,10 +2039,14 @@  discard block
 block discarded – undo
1696 2039
 	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1697 2040
 
1698 2041
 		// Then we test if it is a private range
1699
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
2042
+		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
2043
+		    return 2;
2044
+		}
1700 2045
 
1701 2046
 		// Then we test if it is a reserved range
1702
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
2047
+		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
2048
+		    return 0;
2049
+		}
1703 2050
 
1704 2051
 		return 1;
1705 2052
 	}
@@ -1752,8 +2099,7 @@  discard block
 block discarded – undo
1752 2099
                       'proxy_password' => $proxypass,
1753 2100
                       'trace'		   => 1
1754 2101
         );
1755
-    }
1756
-    else
2102
+    } else
1757 2103
     {
1758 2104
         $params=array('connection_timeout'=>$timeout,
1759 2105
                       'response_timeout'=>$response_timeout,
@@ -1860,14 +2206,12 @@  discard block
 block discarded – undo
1860 2206
 		$classname='FactureFournisseur';
1861 2207
 		$classpath = 'fourn/class';
1862 2208
 		$module='fournisseur';
1863
-	}
1864
-	elseif ($objecttype == 'order_supplier')   {
2209
+	} elseif ($objecttype == 'order_supplier')   {
1865 2210
 		$classfile = 'fournisseur.commande';
1866 2211
 		$classname='CommandeFournisseur';
1867 2212
 		$classpath = 'fourn/class';
1868 2213
 		$module='fournisseur';
1869
-	}
1870
-	elseif ($objecttype == 'stock')   {
2214
+	} elseif ($objecttype == 'stock')   {
1871 2215
 		$classpath = 'product/stock/class';
1872 2216
 		$classfile='entrepot';
1873 2217
 		$classname='Entrepot';
@@ -1887,8 +2231,9 @@  discard block
 block discarded – undo
1887 2231
 					$ret=$langs->trans('Deleted');
1888 2232
 				}
1889 2233
 				unset($object);
2234
+			} else {
2235
+			    dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
1890 2236
 			}
1891
-			else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
1892 2237
 		}
1893 2238
 	}
1894 2239
 	return $ret;
@@ -1920,11 +2265,12 @@  discard block
 block discarded – undo
1920 2265
 		{
1921 2266
 			$obj = $db->fetch_object($resql);
1922 2267
 			$listofid[]=$obj->rowid;
1923
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
2268
+			if ($obj->parent_id > 0) {
2269
+			    $listofparentid[$obj->rowid]=$obj->parent_id;
2270
+			}
1924 2271
 			$i++;
1925 2272
 		}
1926
-	}
1927
-	else
2273
+	} else
1928 2274
 	{
1929 2275
 		dol_print_error($db);
1930 2276
 	}
@@ -1959,9 +2305,11 @@  discard block
 block discarded – undo
1959 2305
 			while ($cursor > 0)
1960 2306
 			{
1961 2307
 				$arrayidparsed[$cursor]=1;
1962
-				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
2308
+				if ($arrayidparsed[$listofparentid[$cursor]]) {
2309
+				    // We detect a loop. A record with a parent that was already into child
1963 2310
 				{
1964 2311
 					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
2312
+				}
1965 2313
 					unset($arrayidparsed);
1966 2314
 					$listofidtoclean[$cursor]=$id;
1967 2315
 					break;
@@ -1969,7 +2317,9 @@  discard block
 block discarded – undo
1969 2317
 				$cursor=$listofparentid[$cursor];
1970 2318
 			}
1971 2319
 
1972
-			if (count($listofidtoclean)) break;
2320
+			if (count($listofidtoclean)) {
2321
+			    break;
2322
+			}
1973 2323
 		}
1974 2324
 
1975 2325
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
@@ -2116,9 +2466,15 @@  discard block
 block discarded – undo
2116 2466
         $classfile='fournisseur.facture';
2117 2467
     }
2118 2468
 
2119
-    if (!isset($classfile)) $classfile = strtolower($subelement);
2120
-    if (!isset($classname)) $classname = ucfirst($subelement);
2121
-    if (!isset($classpath)) $classpath = $module.'/class';
2469
+    if (!isset($classfile)) {
2470
+        $classfile = strtolower($subelement);
2471
+    }
2472
+    if (!isset($classname)) {
2473
+        $classname = ucfirst($subelement);
2474
+    }
2475
+    if (!isset($classpath)) {
2476
+        $classpath = $module.'/class';
2477
+    }
2122 2478
 
2123 2479
     $element_properties = array(
2124 2480
         'module' => $module,
@@ -2172,8 +2528,12 @@  discard block
 block discarded – undo
2172 2528
  */
2173 2529
 function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2174 2530
 {
2175
-	if (! is_array($arraycolor)) return $colorifnotfound;
2176
-	if (empty($arraycolor)) return $colorifnotfound;
2531
+	if (! is_array($arraycolor)) {
2532
+	    return $colorifnotfound;
2533
+	}
2534
+	if (empty($arraycolor)) {
2535
+	    return $colorifnotfound;
2536
+	}
2177 2537
 	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2178 2538
 }
2179 2539
 
@@ -2189,12 +2549,17 @@  discard block
 block discarded – undo
2189 2549
  */
2190 2550
 function colorStringToArray($stringcolor,$colorifnotfound=array(88,88,88))
2191 2551
 {
2192
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2552
+	if (is_array($stringcolor)) {
2553
+	    return $stringcolor;
2554
+	}
2555
+	// If already into correct output format, we return as is
2193 2556
 	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2194 2557
 	if (! $tmp)
2195 2558
 	{
2196 2559
 		$tmp=explode(',',$stringcolor);
2197
-		if (count($tmp) < 3) return $colorifnotfound;
2560
+		if (count($tmp) < 3) {
2561
+		    return $colorifnotfound;
2562
+		}
2198 2563
 		return $tmp;
2199 2564
 	}
2200 2565
 	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
@@ -2240,69 +2605,51 @@  discard block
 block discarded – undo
2240 2605
 function getModuleDirForApiClass($module)
2241 2606
 {
2242 2607
     $moduledirforclass=$module;
2243
-    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2608
+    if ($moduledirforclass != 'api') {
2609
+        $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2610
+    }
2244 2611
 
2245 2612
     if ($module == 'contracts') {
2246 2613
     	$moduledirforclass = 'contrat';
2247
-    }
2248
-    elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2614
+    } elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2249 2615
         $moduledirforclass = 'api';
2250
-    }
2251
-    elseif ($module == 'contact' || $module == 'contacts' || $module == 'customer' || $module == 'thirdparty' || $module == 'thirdparties') {
2616
+    } elseif ($module == 'contact' || $module == 'contacts' || $module == 'customer' || $module == 'thirdparty' || $module == 'thirdparties') {
2252 2617
         $moduledirforclass = 'societe';
2253
-    }
2254
-    elseif ($module == 'propale' || $module == 'proposals') {
2618
+    } elseif ($module == 'propale' || $module == 'proposals') {
2255 2619
         $moduledirforclass = 'comm/propal';
2256
-    }
2257
-    elseif ($module == 'agenda' || $module == 'agendaevents') {
2620
+    } elseif ($module == 'agenda' || $module == 'agendaevents') {
2258 2621
         $moduledirforclass = 'comm/action';
2259
-    }
2260
-    elseif ($module == 'adherent' || $module == 'members' || $module == 'memberstypes' || $module == 'subscriptions') {
2622
+    } elseif ($module == 'adherent' || $module == 'members' || $module == 'memberstypes' || $module == 'subscriptions') {
2261 2623
         $moduledirforclass = 'adherents';
2262
-    }
2263
-    elseif ($module == 'banque' || $module == 'bankaccounts') {
2624
+    } elseif ($module == 'banque' || $module == 'bankaccounts') {
2264 2625
         $moduledirforclass = 'compta/bank';
2265
-    }
2266
-    elseif ($module == 'category' || $module == 'categorie') {
2626
+    } elseif ($module == 'category' || $module == 'categorie') {
2267 2627
         $moduledirforclass = 'categories';
2268
-    }
2269
-    elseif ($module == 'order' || $module == 'orders') {
2628
+    } elseif ($module == 'order' || $module == 'orders') {
2270 2629
         $moduledirforclass = 'commande';
2271
-    }
2272
-    elseif ($module == 'shipments') {
2630
+    } elseif ($module == 'shipments') {
2273 2631
     	$moduledirforclass = 'expedition';
2274
-    }
2275
-    elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
2632
+    } elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
2276 2633
         $moduledirforclass = 'compta/facture';
2277
-    }
2278
-    elseif ($module == 'products') {
2634
+    } elseif ($module == 'products') {
2279 2635
         $moduledirforclass = 'product';
2280
-    }
2281
-    elseif ($module == 'project' || $module == 'projects' || $module == 'tasks') {
2636
+    } elseif ($module == 'project' || $module == 'projects' || $module == 'tasks') {
2282 2637
         $moduledirforclass = 'projet';
2283
-    }
2284
-    elseif ($module == 'task') {
2638
+    } elseif ($module == 'task') {
2285 2639
         $moduledirforclass = 'projet';
2286
-    }
2287
-    elseif ($module == 'stock' || $module == 'stockmovements' || $module == 'warehouses') {
2640
+    } elseif ($module == 'stock' || $module == 'stockmovements' || $module == 'warehouses') {
2288 2641
         $moduledirforclass = 'product/stock';
2289
-    }
2290
-    elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
2642
+    } elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
2291 2643
     	$moduledirforclass = 'supplier_proposal';
2292
-    }
2293
-    elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
2644
+    } elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
2294 2645
         $moduledirforclass = 'fourn';
2295
-    }
2296
-    elseif ($module == 'expensereports') {
2646
+    } elseif ($module == 'expensereports') {
2297 2647
         $moduledirforclass = 'expensereport';
2298
-    }
2299
-    elseif ($module == 'users') {
2648
+    } elseif ($module == 'users') {
2300 2649
         $moduledirforclass = 'user';
2301
-    }
2302
-    elseif ($module == 'ficheinter' || $module == 'interventions') {
2650
+    } elseif ($module == 'ficheinter' || $module == 'interventions') {
2303 2651
     	$moduledirforclass = 'fichinter';
2304
-    }
2305
-    elseif ($module == 'tickets') {
2652
+    } elseif ($module == 'tickets') {
2306 2653
     	$moduledirforclass = 'ticket';
2307 2654
     }
2308 2655
 
Please login to merge, or discard this patch.