Passed
Push — master ( 49af33...3cffbe )
by Alxarafe
21:21
created
dolibarr/htdocs/core/ajax/box.php 3 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -53,28 +53,28 @@
 block discarded – undo
53 53
 // Add a box
54 54
 if ($boxid > 0 && $zone !='' && $userid > 0)
55 55
 {
56
-	$tmp=explode('-',$boxorder);
57
-	$nbboxonleft=substr_count($tmp[0],',');
58
-	$nbboxonright=substr_count($tmp[1],',');
59
-	print $nbboxonleft.'-'.$nbboxonright;
60
-	if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
56
+    $tmp=explode('-',$boxorder);
57
+    $nbboxonleft=substr_count($tmp[0],',');
58
+    $nbboxonright=substr_count($tmp[1],',');
59
+    print $nbboxonleft.'-'.$nbboxonright;
60
+    if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
61 61
     else $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);    // Insert id of new box into list
62 62
 }
63 63
 
64 64
 // Registering the location of boxes after a move
65 65
 if ($boxorder && $zone != '' &&  $userid > 0)
66 66
 {
67
-	// boxorder value is the target order: "A:idboxA1,idboxA2,A-B:idboxB1,idboxB2,B"
68
-	dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG);
67
+    // boxorder value is the target order: "A:idboxA1,idboxA2,A-B:idboxB1,idboxB2,B"
68
+    dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG);
69 69
 
70
-	$result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid);
71
-	if ($result > 0)
72
-	{
73
-	    $langs->load("boxes");
74
-	    if (! GETPOST('closing'))
75
-	    {
76
-	       setEventMessages($langs->trans("BoxAdded"), null);
77
-	    }
78
-	}
70
+    $result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid);
71
+    if ($result > 0)
72
+    {
73
+        $langs->load("boxes");
74
+        if (! GETPOST('closing'))
75
+        {
76
+            setEventMessages($langs->trans("BoxAdded"), null);
77
+        }
78
+    }
79 79
 }
80 80
 
Please login to merge, or discard this patch.
Braces   +24 added lines, -7 removed lines patch added patch discarded remove patch
@@ -21,11 +21,22 @@  discard block
 block discarded – undo
21 21
  *       \brief      File to return Ajax response on Box move or close
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
26
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
27
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
28
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
24
+if (! defined('NOTOKENRENEWAL')) {
25
+    define('NOTOKENRENEWAL','1');
26
+}
27
+// Disables token renewal
28
+if (! defined('NOREQUIREMENU')) {
29
+    define('NOREQUIREMENU','1');
30
+}
31
+if (! defined('NOREQUIREHTML')) {
32
+    define('NOREQUIREHTML','1');
33
+}
34
+if (! defined('NOREQUIREAJAX')) {
35
+    define('NOREQUIREAJAX','1');
36
+}
37
+if (! defined('NOREQUIRESOC')) {
38
+    define('NOREQUIRESOC','1');
39
+}
29 40
 
30 41
 
31 42
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
@@ -60,8 +71,14 @@  discard block
 block discarded – undo
60 71
 	$nbboxonleft=substr_count($tmp[0],',');
61 72
 	$nbboxonright=substr_count($tmp[1],',');
62 73
 	print $nbboxonleft.'-'.$nbboxonright;
63
-	if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
64
-    else $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);    // Insert id of new box into list
74
+	if ($nbboxonleft > $nbboxonright) {
75
+	    $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);
76
+	}
77
+	// Insert id of new box into list
78
+    else {
79
+        $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);
80
+    }
81
+    // Insert id of new box into list
65 82
 }
66 83
 
67 84
 // Registering the location of boxes after a move
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -21,23 +21,23 @@  discard block
 block discarded – undo
21 21
  *       \brief      File to return Ajax response on Box move or close
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
26
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
27
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
28
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
24
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
25
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
26
+if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
27
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
28
+if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
29 29
 
30 30
 
31 31
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
32 32
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
33
-require DOL_BASE_PATH . '/main.inc.php';
33
+require DOL_BASE_PATH.'/main.inc.php';
34 34
 require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
35 35
 
36
-$boxid=GETPOST('boxid','int');
37
-$boxorder=GETPOST('boxorder');
38
-$userid=GETPOST('userid');
39
-$zone=GETPOST('zone','int');
40
-$userid=GETPOST('userid','int');
36
+$boxid = GETPOST('boxid', 'int');
37
+$boxorder = GETPOST('boxorder');
38
+$userid = GETPOST('userid');
39
+$zone = GETPOST('zone', 'int');
40
+$userid = GETPOST('userid', 'int');
41 41
 
42 42
 
43 43
 /*
@@ -54,27 +54,27 @@  discard block
 block discarded – undo
54 54
 print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
55 55
 
56 56
 // Add a box
57
-if ($boxid > 0 && $zone !='' && $userid > 0)
57
+if ($boxid > 0 && $zone != '' && $userid > 0)
58 58
 {
59
-	$tmp=explode('-',$boxorder);
60
-	$nbboxonleft=substr_count($tmp[0],',');
61
-	$nbboxonright=substr_count($tmp[1],',');
59
+	$tmp = explode('-', $boxorder);
60
+	$nbboxonleft = substr_count($tmp[0], ',');
61
+	$nbboxonright = substr_count($tmp[1], ',');
62 62
 	print $nbboxonleft.'-'.$nbboxonright;
63
-	if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
64
-    else $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);    // Insert id of new box into list
63
+	if ($nbboxonleft > $nbboxonright) $boxorder = preg_replace('/B:/', 'B:'.$boxid.',', $boxorder); // Insert id of new box into list
64
+    else $boxorder = preg_replace('/^A:/', 'A:'.$boxid.',', $boxorder); // Insert id of new box into list
65 65
 }
66 66
 
67 67
 // Registering the location of boxes after a move
68
-if ($boxorder && $zone != '' &&  $userid > 0)
68
+if ($boxorder && $zone != '' && $userid > 0)
69 69
 {
70 70
 	// boxorder value is the target order: "A:idboxA1,idboxA2,A-B:idboxB1,idboxB2,B"
71 71
 	dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG);
72 72
 
73
-	$result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid);
73
+	$result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid);
74 74
 	if ($result > 0)
75 75
 	{
76 76
 	    $langs->load("boxes");
77
-	    if (! GETPOST('closing'))
77
+	    if (!GETPOST('closing'))
78 78
 	    {
79 79
 	       setEventMessages($langs->trans("BoxAdded"), null);
80 80
 	    }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_printing.inc.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -30,12 +30,12 @@  discard block
 block discarded – undo
30 30
 // Print file
31 31
 if ($action == 'print_file' && $user->rights->printing->read) {
32 32
     $langs->load("printing");
33
-    require_once DOL_DOCUMENT_ROOT . '/core/modules/printing/modules_printing.php';
33
+    require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/modules_printing.php';
34 34
     $objectprint = new PrintingDriver($db);
35 35
     $list = $objectprint->listDrivers($db, 10);
36
-    if (! empty($list)) {
37
-        $errorprint=0;
38
-        $printerfound=0;
36
+    if (!empty($list)) {
37
+        $errorprint = 0;
38
+        $printerfound = 0;
39 39
         foreach ($list as $driver) {
40 40
             require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php';
41 41
             $langs->load($driver);
@@ -43,13 +43,13 @@  discard block
 block discarded – undo
43 43
             $printer = new $classname($db);
44 44
             //print '<pre>'.print_r($printer, true).'</pre>';
45 45
 
46
-            if (! empty($conf->global->{$printer->active}))
46
+            if (!empty($conf->global->{$printer->active}))
47 47
             {
48 48
                 $printerfound++;
49 49
 
50
-                $subdir='';
50
+                $subdir = '';
51 51
                 $module = GETPOST('printer', 'alpha');
52
-                switch ($module )
52
+                switch ($module)
53 53
                 {
54 54
                     case 'livraison' :
55 55
                         $subdir = 'receipt';
@@ -69,21 +69,21 @@  discard block
 block discarded – undo
69 69
                         //print '<pre>'.print_r($printer->errors, true).'</pre>';
70 70
                         setEventMessages($printer->error, $printer->errors, 'errors');
71 71
                     }
72
-                    if ($ret==0)
72
+                    if ($ret == 0)
73 73
                     {
74 74
                         //print '<pre>'.print_r($printer->errors, true).'</pre>';
75 75
                         setEventMessages($printer->error, $printer->errors);
76 76
                         setEventMessages($langs->transnoentitiesnoconv("FileWasSentToPrinter", basename(GETPOST('file', 'alpha'))).' '.$langs->transnoentitiesnoconv("ViaModule").' '.$printer->name, null);
77 77
                     }
78 78
                 }
79
-                catch(Exception $e)
79
+                catch (Exception $e)
80 80
                 {
81 81
                     $ret = 1;
82 82
                     setEventMessages($e->getMessage(), null, 'errors');
83 83
                 }
84 84
             }
85 85
         }
86
-        if ($printerfound==0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
86
+        if ($printerfound == 0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
87 87
     } else {
88 88
         setEventMessages($langs->trans("NoModuleFound"), null, 'warnings');
89 89
     }
Please login to merge, or discard this patch.
Braces   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -75,15 +75,16 @@
 block discarded – undo
75 75
                         setEventMessages($printer->error, $printer->errors);
76 76
                         setEventMessages($langs->transnoentitiesnoconv("FileWasSentToPrinter", basename(GETPOST('file', 'alpha'))).' '.$langs->transnoentitiesnoconv("ViaModule").' '.$printer->name, null);
77 77
                     }
78
-                }
79
-                catch(Exception $e)
78
+                } catch(Exception $e)
80 79
                 {
81 80
                     $ret = 1;
82 81
                     setEventMessages($e->getMessage(), null, 'errors');
83 82
                 }
84 83
             }
85 84
         }
86
-        if ($printerfound==0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
85
+        if ($printerfound==0) {
86
+            setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
87
+        }
87 88
     } else {
88 89
         setEventMessages($langs->trans("NoModuleFound"), null, 'warnings');
89 90
     }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/antispamimage.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -21,14 +21,14 @@  discard block
 block discarded – undo
21 21
  *		\brief      Return antispam image
22 22
  */
23 23
 
24
-define('NOLOGIN',1);
24
+define('NOLOGIN', 1);
25 25
 
26
-if (! defined('NOREQUIREUSER'))   define('NOREQUIREUSER',1);
27
-if (! defined('NOREQUIREDB'))     define('NOREQUIREDB',1);
28
-if (! defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN',1);
29
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
30
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC',1);
31
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
26
+if (!defined('NOREQUIREUSER'))   define('NOREQUIREUSER', 1);
27
+if (!defined('NOREQUIREDB'))     define('NOREQUIREDB', 1);
28
+if (!defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN', 1);
29
+if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
30
+if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', 1);
31
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
32 32
 
33 33
 require_once '../main.inc.php';
34 34
 
@@ -37,24 +37,24 @@  discard block
 block discarded – undo
37 37
  * View
38 38
  */
39 39
 
40
-$length=5;
40
+$length = 5;
41 41
 $letters = 'aAbBCDeEFgGhHJKLmMnNpPqQRsStTuVwWXYZz2345679';
42 42
 $number = strlen($letters);
43 43
 $string = '';
44
-for($i = 0; $i < $length; $i++)
44
+for ($i = 0; $i < $length; $i++)
45 45
 {
46 46
     $string .= $letters{mt_rand(0, $number - 1)};
47 47
 }
48 48
 //print $string;
49 49
 
50 50
 
51
-$sessionkey='dol_antispam_value';
52
-$_SESSION[$sessionkey]=$string;
51
+$sessionkey = 'dol_antispam_value';
52
+$_SESSION[$sessionkey] = $string;
53 53
 
54
-$img = imagecreate(80,32);
54
+$img = imagecreate(80, 32);
55 55
 if (empty($img))
56 56
 {
57
-    dol_print_error('',"Problem with GD creation");
57
+    dol_print_error('', "Problem with GD creation");
58 58
     exit;
59 59
 }
60 60
 
Please login to merge, or discard this patch.
Braces   +18 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,12 +23,24 @@
 block discarded – undo
23 23
 
24 24
 define('NOLOGIN',1);
25 25
 
26
-if (! defined('NOREQUIREUSER'))   define('NOREQUIREUSER',1);
27
-if (! defined('NOREQUIREDB'))     define('NOREQUIREDB',1);
28
-if (! defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN',1);
29
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
30
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC',1);
31
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
26
+if (! defined('NOREQUIREUSER')) {
27
+    define('NOREQUIREUSER',1);
28
+}
29
+if (! defined('NOREQUIREDB')) {
30
+    define('NOREQUIREDB',1);
31
+}
32
+if (! defined('NOREQUIRETRAN')) {
33
+    define('NOREQUIRETRAN',1);
34
+}
35
+if (! defined('NOREQUIREMENU')) {
36
+    define('NOREQUIREMENU',1);
37
+}
38
+if (! defined('NOREQUIRESOC')) {
39
+    define('NOREQUIRESOC',1);
40
+}
41
+if (! defined('NOTOKENRENEWAL')) {
42
+    define('NOTOKENRENEWAL',1);
43
+}
32 44
 
33 45
 require_once '../main.inc.php';
34 46
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/extrafieldsinexport.inc.php 3 patches
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -13,55 +13,55 @@
 block discarded – undo
13 13
 $resql=$this->db->query($sql);
14 14
 if ($resql)    // This can fail when class is used on old database (during migration for example)
15 15
 {
16
-	while ($obj=$this->db->fetch_object($resql))
17
-	{
18
-		$fieldname=$keyforaliasextra.'.'.$obj->name;
19
-		$fieldlabel=ucfirst($obj->label);
20
-		$typeFilter="Text";
21
-		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
22
-		switch ($typefield) {
23
-			case 'int':
24
-			case 'integer':
25
-			case 'double':
26
-			case 'price':
27
-				$typeFilter="Numeric";
28
-				break;
29
-			case 'date':
30
-			case 'datetime':
31
-			case 'timestamp':
32
-				$typeFilter="Date";
33
-				break;
34
-			case 'boolean':
35
-				$typeFilter="Boolean";
36
-				break;
37
-			case 'sellist':
38
-				$tmp='';
39
-				$tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
40
-				if ($tmpparam['options'] && is_array($tmpparam['options'])) {
41
-					$tmpkeys=array_keys($tmpparam['options']);
42
-					$tmp=array_shift($tmpkeys);
43
-				}
44
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
45
-				break;
46
-		}
47
-		if ($obj->type!='separate')
48
-		{
49
-		    // If not a computed field
50
-		    if (empty($obj->fieldcomputed))
51
-		    {
52
-    			$this->export_fields_array[$r][$fieldname]=$fieldlabel;
53
-    			$this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
54
-    			$this->export_entities_array[$r][$fieldname]=$keyforelement;
55
-		    }
56
-			// If this is a computed field
57
-			else
58
-			{
59
-			    $this->export_fields_array[$r][$fieldname]=$fieldlabel;
60
-			    $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
61
-			    $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
62
-			    $this->export_entities_array[$r][$fieldname]=$keyforelement;
63
-			}
64
-		}
65
-	}
16
+    while ($obj=$this->db->fetch_object($resql))
17
+    {
18
+        $fieldname=$keyforaliasextra.'.'.$obj->name;
19
+        $fieldlabel=ucfirst($obj->label);
20
+        $typeFilter="Text";
21
+        $typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
22
+        switch ($typefield) {
23
+            case 'int':
24
+            case 'integer':
25
+            case 'double':
26
+            case 'price':
27
+                $typeFilter="Numeric";
28
+                break;
29
+            case 'date':
30
+            case 'datetime':
31
+            case 'timestamp':
32
+                $typeFilter="Date";
33
+                break;
34
+            case 'boolean':
35
+                $typeFilter="Boolean";
36
+                break;
37
+            case 'sellist':
38
+                $tmp='';
39
+                $tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
40
+                if ($tmpparam['options'] && is_array($tmpparam['options'])) {
41
+                    $tmpkeys=array_keys($tmpparam['options']);
42
+                    $tmp=array_shift($tmpkeys);
43
+                }
44
+                if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
45
+                break;
46
+        }
47
+        if ($obj->type!='separate')
48
+        {
49
+            // If not a computed field
50
+            if (empty($obj->fieldcomputed))
51
+            {
52
+                $this->export_fields_array[$r][$fieldname]=$fieldlabel;
53
+                $this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
54
+                $this->export_entities_array[$r][$fieldname]=$keyforelement;
55
+            }
56
+            // If this is a computed field
57
+            else
58
+            {
59
+                $this->export_fields_array[$r][$fieldname]=$fieldlabel;
60
+                $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
61
+                $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
62
+                $this->export_entities_array[$r][$fieldname]=$keyforelement;
63
+            }
64
+        }
65
+    }
66 66
 }
67 67
 // End add axtra fields
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -8,58 +8,58 @@
 block discarded – undo
8 8
 }
9 9
 
10 10
 // Add extra fields
11
-$sql="SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.')';
11
+$sql = "SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.')';
12 12
 //print $sql;
13
-$resql=$this->db->query($sql);
13
+$resql = $this->db->query($sql);
14 14
 if ($resql)    // This can fail when class is used on old database (during migration for example)
15 15
 {
16
-	while ($obj=$this->db->fetch_object($resql))
16
+	while ($obj = $this->db->fetch_object($resql))
17 17
 	{
18
-		$fieldname=$keyforaliasextra.'.'.$obj->name;
19
-		$fieldlabel=ucfirst($obj->label);
20
-		$typeFilter="Text";
21
-		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
18
+		$fieldname = $keyforaliasextra.'.'.$obj->name;
19
+		$fieldlabel = ucfirst($obj->label);
20
+		$typeFilter = "Text";
21
+		$typefield = preg_replace('/\(.*$/', '', $obj->type); // double(24,8) -> double
22 22
 		switch ($typefield) {
23 23
 			case 'int':
24 24
 			case 'integer':
25 25
 			case 'double':
26 26
 			case 'price':
27
-				$typeFilter="Numeric";
27
+				$typeFilter = "Numeric";
28 28
 				break;
29 29
 			case 'date':
30 30
 			case 'datetime':
31 31
 			case 'timestamp':
32
-				$typeFilter="Date";
32
+				$typeFilter = "Date";
33 33
 				break;
34 34
 			case 'boolean':
35
-				$typeFilter="Boolean";
35
+				$typeFilter = "Boolean";
36 36
 				break;
37 37
 			case 'sellist':
38
-				$tmp='';
39
-				$tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
38
+				$tmp = '';
39
+				$tmpparam = unserialize($obj->param); // $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
40 40
 				if ($tmpparam['options'] && is_array($tmpparam['options'])) {
41
-					$tmpkeys=array_keys($tmpparam['options']);
42
-					$tmp=array_shift($tmpkeys);
41
+					$tmpkeys = array_keys($tmpparam['options']);
42
+					$tmp = array_shift($tmpkeys);
43 43
 				}
44
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
44
+				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter = "List:".$tmp;
45 45
 				break;
46 46
 		}
47
-		if ($obj->type!='separate')
47
+		if ($obj->type != 'separate')
48 48
 		{
49 49
 		    // If not a computed field
50 50
 		    if (empty($obj->fieldcomputed))
51 51
 		    {
52
-    			$this->export_fields_array[$r][$fieldname]=$fieldlabel;
53
-    			$this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
54
-    			$this->export_entities_array[$r][$fieldname]=$keyforelement;
52
+    			$this->export_fields_array[$r][$fieldname] = $fieldlabel;
53
+    			$this->export_TypeFields_array[$r][$fieldname] = $typeFilter;
54
+    			$this->export_entities_array[$r][$fieldname] = $keyforelement;
55 55
 		    }
56 56
 			// If this is a computed field
57 57
 			else
58 58
 			{
59
-			    $this->export_fields_array[$r][$fieldname]=$fieldlabel;
60
-			    $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
61
-			    $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
62
-			    $this->export_entities_array[$r][$fieldname]=$keyforelement;
59
+			    $this->export_fields_array[$r][$fieldname] = $fieldlabel;
60
+			    $this->export_TypeFields_array[$r][$fieldname] = $typeFilter.'Compute';
61
+			    $this->export_special_array[$r][$fieldname] = $obj->fieldcomputed;
62
+			    $this->export_entities_array[$r][$fieldname] = $keyforelement;
63 63
 			}
64 64
 		}
65 65
 	}
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -11,11 +11,13 @@  discard block
 block discarded – undo
11 11
 $sql="SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.')';
12 12
 //print $sql;
13 13
 $resql=$this->db->query($sql);
14
-if ($resql)    // This can fail when class is used on old database (during migration for example)
14
+if ($resql) {
15
+    // This can fail when class is used on old database (during migration for example)
15 16
 {
16 17
 	while ($obj=$this->db->fetch_object($resql))
17 18
 	{
18 19
 		$fieldname=$keyforaliasextra.'.'.$obj->name;
20
+}
19 21
 		$fieldlabel=ucfirst($obj->label);
20 22
 		$typeFilter="Text";
21 23
 		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
@@ -41,7 +43,9 @@  discard block
 block discarded – undo
41 43
 					$tmpkeys=array_keys($tmpparam['options']);
42 44
 					$tmp=array_shift($tmpkeys);
43 45
 				}
44
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
46
+				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) {
47
+				    $typeFilter="List:".$tmp;
48
+				}
45 49
 				break;
46 50
 		}
47 51
 		if ($obj->type!='separate')
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_massactions.inc.php 3 patches
Indentation   +1097 added lines, -1097 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 // Protection
37 37
 if (empty($objectclass) || empty($uploaddir))
38 38
 {
39
-	dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined');
40
-	exit;
39
+    dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined');
40
+    exit;
41 41
 }
42 42
 
43 43
 
@@ -45,1029 +45,1029 @@  discard block
 block discarded – undo
45 45
 $maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
46 46
 if (! empty($massaction) && count($toselect) < 1)
47 47
 {
48
-	$error++;
49
-	setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
48
+    $error++;
49
+    setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
50 50
 }
51 51
 if (! $error && is_array($toselect) && count($toselect) > $maxformassaction)
52 52
 {
53
-	setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
54
-	$error++;
53
+    setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
54
+    $error++;
55 55
 }
56 56
 
57 57
 if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
58 58
 {
59
-	$massaction='presend';
59
+    $massaction='presend';
60 60
 }
61 61
 if (! $error && $massaction == 'confirm_presend')
62 62
 {
63
-	$resaction = '';
64
-	$nbsent = 0;
65
-	$nbignored = 0;
66
-	$langs->load("mails");
67
-	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68
-
69
-	$listofobjectid=array();
70
-	$listofobjectthirdparties=array();
71
-	$listofobjectref=array();
72
-
73
-	if (! $error)
74
-	{
75
-		$thirdparty=new Societe($db);
76
-		if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
-		if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
78
-
79
-		$objecttmp=new $objectclass($db);
80
-		foreach($toselect as $toselectid)
81
-		{
82
-			$objecttmp=new $objectclass($db);	// we must create new instance because instance is saved into $listofobjectref array for future use
83
-			$result=$objecttmp->fetch($toselectid);
84
-			if ($result > 0)
85
-			{
86
-				$listofobjectid[$toselectid]=$toselectid;
87
-				$thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
-				if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
-				if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
-				if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
91
-				$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92
-				$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
93
-			}
94
-		}
95
-	}
96
-
97
-	// Check mandatory parameters
98
-	if (GETPOST('fromtype','alpha') === 'user' && empty($user->email))
99
-	{
100
-		$error++;
101
-		setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
102
-		$massaction='presend';
103
-	}
104
-
105
-	$receiver=$_POST['receiver'];
106
-	if (! is_array($receiver))
107
-	{
108
-		if (empty($receiver) || $receiver == '-1') $receiver=array();
109
-		else $receiver=array($receiver);
110
-	}
111
-	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
112
-	{
113
-	 	$error++;
114
-	   	setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115
-	   	$massaction='presend';
116
-	}
117
-
118
-	if (! GETPOST('subject','none'))
119
-	{
120
-		$error++;
121
-		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
122
-		$massaction='presend';
123
-	}
124
-
125
-	// Loop on each recipient/thirdparty
126
-	if (! $error)
127
-	{
128
-		foreach ($listofobjectthirdparties as $thirdpartyid)
129
-		{
130
-			$result = $thirdparty->fetch($thirdpartyid);
131
-			if ($result < 0)
132
-			{
133
-				dol_print_error($db);
134
-				exit;
135
-			}
136
-
137
-			$sendto='';
138
-			$sendtocc='';
139
-			$sendtobcc='';
140
-			$sendtoid = array();
141
-
142
-			// Define $sendto
143
-			$tmparray=array();
144
-			if (trim($_POST['sendto']))
145
-			{
146
-				// Recipients are provided into free text
147
-				$tmparray[] = trim($_POST['sendto']);
148
-			}
149
-			if (count($receiver)>0)
150
-			{
151
-				foreach($receiver as $key=>$val)
152
-				{
153
-					// Recipient was provided from combo list
154
-					if ($val == 'thirdparty') // Id of third party or user
155
-					{
156
-						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
157
-					}
158
-					elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
159
-					{
160
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
161
-						$sendtoid[] = $val;
162
-					}
163
-				}
164
-			}
165
-			$sendto=implode(',',$tmparray);
166
-
167
-			// Define $sendtocc
168
-			$receivercc=$_POST['receivercc'];
169
-			if (! is_array($receivercc))
170
-			{
171
-				if ($receivercc == '-1') $receivercc=array();
172
-				else $receivercc=array($receivercc);
173
-			}
174
-			$tmparray=array();
175
-			if (trim($_POST['sendtocc']))
176
-			{
177
-				$tmparray[] = trim($_POST['sendtocc']);
178
-			}
179
-			if (count($receivercc) > 0)
180
-			{
181
-				foreach($receivercc as $key=>$val)
182
-				{
183
-					// Recipient was provided from combo list
184
-					if ($val == 'thirdparty') // Id of third party
185
-					{
186
-						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
187
-					}
188
-					elseif ($val)	// Id du contact
189
-					{
190
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
191
-						//$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192
-					}
193
-				}
194
-			}
195
-			$sendtocc=implode(',',$tmparray);
196
-
197
-			//var_dump($listofobjectref);exit;
198
-			$attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
-			$listofqualifiedobj=array();
200
-			$listofqualifiedref=array();
201
-			$thirdpartywithoutemail=array();
202
-
203
-			foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
204
-			{
205
-				//var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
206
-				if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
207
-				{
208
-					$langs->load("errors");
209
-					$nbignored++;
210
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
211
-					continue; // Payment done or started or canceled
212
-				}
213
-				if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
214
-				{
215
-					$langs->load("errors");
216
-					$nbignored++;
217
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
218
-					continue;
219
-				}
220
-				if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
221
-				{
222
-					$langs->load("errors");
223
-					$nbignored++;
224
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
225
-					continue; // Payment done or started or canceled
226
-				}
227
-
228
-				// Test recipient
229
-				if (empty($sendto)) 	// For the case, no recipient were set (multi thirdparties send)
230
-				{
231
-					if ($objectobj->element == 'expensereport')
232
-					{
233
-						$fuser = new User($db);
234
-						$fuser->fetch($objectobj->fk_user_author);
235
-						$sendto = $fuser->email;
236
-					}
237
-					else
238
-					{
239
-						$objectobj->fetch_thirdparty();
240
-						$sendto = $objectobj->thirdparty->email;
241
-					}
242
-				}
243
-
244
-				if (empty($sendto))
245
-				{
246
-				   	//print "No recipient for thirdparty ".$objectobj->thirdparty->name;
247
-				   	$nbignored++;
248
-				   	if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
249
-					{
250
-						$resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
251
-					}
252
-					dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
253
-					$thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
254
-				   	continue;
255
-				}
256
-
257
-				if ($_POST['addmaindocfile'])
258
-				{
259
-					// TODO Use future field $objectobj->fullpathdoc to know where is stored default file
260
-					// TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
261
-					$filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
262
-					$filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
263
-					$file = $filedir . '/' . $filename;
264
-					$mime = dol_mimetype($file);
265
-
266
-	   				if (dol_is_file($file))
267
-					{
268
-							// Create form object
269
-							$attachedfiles=array(
270
-							'paths'=>array_merge($attachedfiles['paths'],array($file)),
271
-							'names'=>array_merge($attachedfiles['names'],array($filename)),
272
-							'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
273
-							);
274
-					}
275
-					else
276
-					{
277
-							$nbignored++;
278
-							$langs->load("errors");
279
-							$resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
280
-							dol_syslog('Failed to read file: '.$file, LOG_WARNING);
281
-							continue;
282
-					}
283
-				}
284
-
285
-				// Object of thirdparty qualified
286
-				$listofqualifiedobj[$objectid]=$objectobj;
287
-				$listofqualifiedref[$objectid]=$objectobj->ref;
288
-
289
-
290
-				//var_dump($listofqualifiedref);
291
-			}
292
-
293
-			// Send email if there is at least one qualified record
294
-			if (count($listofqualifiedobj) > 0)
295
-			{
296
-				$langs->load("commercial");
297
-
298
-				$fromtype = GETPOST('fromtype');
299
-				if ($fromtype === 'user') {
300
-					$from = $user->getFullName($langs) .' <'.$user->email.'>';
301
-				}
302
-				elseif ($fromtype === 'company') {
303
-					$from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304
-				}
305
-				elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306
-					$tmp=explode(',', $user->email_aliases);
307
-					$from = trim($tmp[($reg[1] - 1)]);
308
-				}
309
-				elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310
-					$tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311
-					$from = trim($tmp[($reg[1] - 1)]);
312
-				}
313
-				elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314
-					$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315
-					$resql = $db->query($sql);
316
-					$obj = $db->fetch_object($resql);
317
-					if ($obj)
318
-					{
319
-						$from = $obj->label.' <'.$obj->email.'>';
320
-					}
321
-				}
322
-				else {
323
-					$from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
324
-				}
325
-
326
-				$replyto = $from;
327
-				$subject = GETPOST('subject','none');
328
-				$message = GETPOST('message','none');
329
-
330
-				$sendtobcc = GETPOST('sendtoccc');
331
-				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
-				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
-				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
-				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
-				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
-				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
337
-
338
-				// $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339
-				$oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
340
-				$looparray=array();
341
-				if (! $oneemailperrecipient)
342
-				{
343
-					$looparray = $listofqualifiedobj;
344
-					foreach ($looparray as $key => $objecttmp)
345
-					{
346
-						$looparray[$key]->thirdparty = $thirdparty;
347
-					}
348
-				}
349
-				else
350
-				{
351
-					$objectforloop=new $objectclass($db);
352
-					$objectforloop->thirdparty = $thirdparty;
353
-					$looparray[0]=$objectforloop;
354
-				}
355
-				//var_dump($looparray);exit;
356
-
357
-				foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358
-				{
359
-					// Make substitution in email content
360
-					$substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
-					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362
-					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
363
-					$substitutionarray['__EMAIL__'] = $thirdparty->email;
364
-					$substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
365
-
366
-					$parameters=array('mode'=>'formemail');
367
-
368
-					if ( ! empty( $listofobjectthirdparties ) ) {
369
-						$parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
370
-					}
371
-					if ( ! empty( $listofobjectref ) ) {
372
-						$parameters['listofobjectref'] = $listofobjectref;
373
-					}
374
-
375
-					complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
376
-
377
-					$subject=make_substitutions($subject, $substitutionarray);
378
-					$message=make_substitutions($message, $substitutionarray);
379
-
380
-					$filepath = $attachedfiles['paths'];
381
-					$filename = $attachedfiles['names'];
382
-					$mimetype = $attachedfiles['mimes'];
383
-
384
-					// Define the trackid when emails sent from the mass action
385
-					if ($oneemailperrecipient)
386
-					{
387
-						$trackid='thi'.$thirdparty->id;
388
-						if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
-						if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
390
-					}
391
-					else
392
-					{
393
-						$trackid=strtolower(get_class($objecttmp));
394
-						if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
-						if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
-						if (get_class($objecttmp)=='Commande') $trackid='ord';
397
-						if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
-						if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
-						if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
-						if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
401
-
402
-						$trackid.=$objecttmp->id;
403
-					}
404
-					//var_dump($filepath);
405
-					//var_dump($trackid);exit;
406
-
407
-					// Send mail (substitutionarray must be done just before this)
408
-					require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
409
-					$mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
410
-					if ($mailfile->error)
411
-					{
412
-						$resaction.='<div class="error">'.$mailfile->error.'</div>';
413
-					}
414
-					else
415
-					{
416
-						$result=$mailfile->sendfile();
417
-						if ($result)
418
-						{
419
-							$resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>';		// Must not contain "
420
-
421
-							$error=0;
422
-
423
-							// Insert logs into agenda
424
-							foreach($listofqualifiedobj as $objid => $objectobj)
425
-							{
426
-								/*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
63
+    $resaction = '';
64
+    $nbsent = 0;
65
+    $nbignored = 0;
66
+    $langs->load("mails");
67
+    include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68
+
69
+    $listofobjectid=array();
70
+    $listofobjectthirdparties=array();
71
+    $listofobjectref=array();
72
+
73
+    if (! $error)
74
+    {
75
+        $thirdparty=new Societe($db);
76
+        if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
+        if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
78
+
79
+        $objecttmp=new $objectclass($db);
80
+        foreach($toselect as $toselectid)
81
+        {
82
+            $objecttmp=new $objectclass($db);	// we must create new instance because instance is saved into $listofobjectref array for future use
83
+            $result=$objecttmp->fetch($toselectid);
84
+            if ($result > 0)
85
+            {
86
+                $listofobjectid[$toselectid]=$toselectid;
87
+                $thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
+                if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
+                if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
+                if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
91
+                $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92
+                $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
93
+            }
94
+        }
95
+    }
96
+
97
+    // Check mandatory parameters
98
+    if (GETPOST('fromtype','alpha') === 'user' && empty($user->email))
99
+    {
100
+        $error++;
101
+        setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
102
+        $massaction='presend';
103
+    }
104
+
105
+    $receiver=$_POST['receiver'];
106
+    if (! is_array($receiver))
107
+    {
108
+        if (empty($receiver) || $receiver == '-1') $receiver=array();
109
+        else $receiver=array($receiver);
110
+    }
111
+    if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
112
+    {
113
+            $error++;
114
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115
+            $massaction='presend';
116
+    }
117
+
118
+    if (! GETPOST('subject','none'))
119
+    {
120
+        $error++;
121
+        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
122
+        $massaction='presend';
123
+    }
124
+
125
+    // Loop on each recipient/thirdparty
126
+    if (! $error)
127
+    {
128
+        foreach ($listofobjectthirdparties as $thirdpartyid)
129
+        {
130
+            $result = $thirdparty->fetch($thirdpartyid);
131
+            if ($result < 0)
132
+            {
133
+                dol_print_error($db);
134
+                exit;
135
+            }
136
+
137
+            $sendto='';
138
+            $sendtocc='';
139
+            $sendtobcc='';
140
+            $sendtoid = array();
141
+
142
+            // Define $sendto
143
+            $tmparray=array();
144
+            if (trim($_POST['sendto']))
145
+            {
146
+                // Recipients are provided into free text
147
+                $tmparray[] = trim($_POST['sendto']);
148
+            }
149
+            if (count($receiver)>0)
150
+            {
151
+                foreach($receiver as $key=>$val)
152
+                {
153
+                    // Recipient was provided from combo list
154
+                    if ($val == 'thirdparty') // Id of third party or user
155
+                    {
156
+                        $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
157
+                    }
158
+                    elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
159
+                    {
160
+                        $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
161
+                        $sendtoid[] = $val;
162
+                    }
163
+                }
164
+            }
165
+            $sendto=implode(',',$tmparray);
166
+
167
+            // Define $sendtocc
168
+            $receivercc=$_POST['receivercc'];
169
+            if (! is_array($receivercc))
170
+            {
171
+                if ($receivercc == '-1') $receivercc=array();
172
+                else $receivercc=array($receivercc);
173
+            }
174
+            $tmparray=array();
175
+            if (trim($_POST['sendtocc']))
176
+            {
177
+                $tmparray[] = trim($_POST['sendtocc']);
178
+            }
179
+            if (count($receivercc) > 0)
180
+            {
181
+                foreach($receivercc as $key=>$val)
182
+                {
183
+                    // Recipient was provided from combo list
184
+                    if ($val == 'thirdparty') // Id of third party
185
+                    {
186
+                        $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
187
+                    }
188
+                    elseif ($val)	// Id du contact
189
+                    {
190
+                        $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
191
+                        //$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192
+                    }
193
+                }
194
+            }
195
+            $sendtocc=implode(',',$tmparray);
196
+
197
+            //var_dump($listofobjectref);exit;
198
+            $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
+            $listofqualifiedobj=array();
200
+            $listofqualifiedref=array();
201
+            $thirdpartywithoutemail=array();
202
+
203
+            foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
204
+            {
205
+                //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
206
+                if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
207
+                {
208
+                    $langs->load("errors");
209
+                    $nbignored++;
210
+                    $resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
211
+                    continue; // Payment done or started or canceled
212
+                }
213
+                if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
214
+                {
215
+                    $langs->load("errors");
216
+                    $nbignored++;
217
+                    $resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
218
+                    continue;
219
+                }
220
+                if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
221
+                {
222
+                    $langs->load("errors");
223
+                    $nbignored++;
224
+                    $resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
225
+                    continue; // Payment done or started or canceled
226
+                }
227
+
228
+                // Test recipient
229
+                if (empty($sendto)) 	// For the case, no recipient were set (multi thirdparties send)
230
+                {
231
+                    if ($objectobj->element == 'expensereport')
232
+                    {
233
+                        $fuser = new User($db);
234
+                        $fuser->fetch($objectobj->fk_user_author);
235
+                        $sendto = $fuser->email;
236
+                    }
237
+                    else
238
+                    {
239
+                        $objectobj->fetch_thirdparty();
240
+                        $sendto = $objectobj->thirdparty->email;
241
+                    }
242
+                }
243
+
244
+                if (empty($sendto))
245
+                {
246
+                        //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
247
+                        $nbignored++;
248
+                        if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
249
+                    {
250
+                        $resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
251
+                    }
252
+                    dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
253
+                    $thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
254
+                        continue;
255
+                }
256
+
257
+                if ($_POST['addmaindocfile'])
258
+                {
259
+                    // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
260
+                    // TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
261
+                    $filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
262
+                    $filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
263
+                    $file = $filedir . '/' . $filename;
264
+                    $mime = dol_mimetype($file);
265
+
266
+                        if (dol_is_file($file))
267
+                    {
268
+                            // Create form object
269
+                            $attachedfiles=array(
270
+                            'paths'=>array_merge($attachedfiles['paths'],array($file)),
271
+                            'names'=>array_merge($attachedfiles['names'],array($filename)),
272
+                            'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
273
+                            );
274
+                    }
275
+                    else
276
+                    {
277
+                            $nbignored++;
278
+                            $langs->load("errors");
279
+                            $resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
280
+                            dol_syslog('Failed to read file: '.$file, LOG_WARNING);
281
+                            continue;
282
+                    }
283
+                }
284
+
285
+                // Object of thirdparty qualified
286
+                $listofqualifiedobj[$objectid]=$objectobj;
287
+                $listofqualifiedref[$objectid]=$objectobj->ref;
288
+
289
+
290
+                //var_dump($listofqualifiedref);
291
+            }
292
+
293
+            // Send email if there is at least one qualified record
294
+            if (count($listofqualifiedobj) > 0)
295
+            {
296
+                $langs->load("commercial");
297
+
298
+                $fromtype = GETPOST('fromtype');
299
+                if ($fromtype === 'user') {
300
+                    $from = $user->getFullName($langs) .' <'.$user->email.'>';
301
+                }
302
+                elseif ($fromtype === 'company') {
303
+                    $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304
+                }
305
+                elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306
+                    $tmp=explode(',', $user->email_aliases);
307
+                    $from = trim($tmp[($reg[1] - 1)]);
308
+                }
309
+                elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310
+                    $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311
+                    $from = trim($tmp[($reg[1] - 1)]);
312
+                }
313
+                elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314
+                    $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315
+                    $resql = $db->query($sql);
316
+                    $obj = $db->fetch_object($resql);
317
+                    if ($obj)
318
+                    {
319
+                        $from = $obj->label.' <'.$obj->email.'>';
320
+                    }
321
+                }
322
+                else {
323
+                    $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
324
+                }
325
+
326
+                $replyto = $from;
327
+                $subject = GETPOST('subject','none');
328
+                $message = GETPOST('message','none');
329
+
330
+                $sendtobcc = GETPOST('sendtoccc');
331
+                if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
+                if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
+                if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
+                if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
+                if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
+                if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
337
+
338
+                // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339
+                $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
340
+                $looparray=array();
341
+                if (! $oneemailperrecipient)
342
+                {
343
+                    $looparray = $listofqualifiedobj;
344
+                    foreach ($looparray as $key => $objecttmp)
345
+                    {
346
+                        $looparray[$key]->thirdparty = $thirdparty;
347
+                    }
348
+                }
349
+                else
350
+                {
351
+                    $objectforloop=new $objectclass($db);
352
+                    $objectforloop->thirdparty = $thirdparty;
353
+                    $looparray[0]=$objectforloop;
354
+                }
355
+                //var_dump($looparray);exit;
356
+
357
+                foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358
+                {
359
+                    // Make substitution in email content
360
+                    $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
+                    $substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362
+                    $substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
363
+                    $substitutionarray['__EMAIL__'] = $thirdparty->email;
364
+                    $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
365
+
366
+                    $parameters=array('mode'=>'formemail');
367
+
368
+                    if ( ! empty( $listofobjectthirdparties ) ) {
369
+                        $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
370
+                    }
371
+                    if ( ! empty( $listofobjectref ) ) {
372
+                        $parameters['listofobjectref'] = $listofobjectref;
373
+                    }
374
+
375
+                    complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
376
+
377
+                    $subject=make_substitutions($subject, $substitutionarray);
378
+                    $message=make_substitutions($message, $substitutionarray);
379
+
380
+                    $filepath = $attachedfiles['paths'];
381
+                    $filename = $attachedfiles['names'];
382
+                    $mimetype = $attachedfiles['mimes'];
383
+
384
+                    // Define the trackid when emails sent from the mass action
385
+                    if ($oneemailperrecipient)
386
+                    {
387
+                        $trackid='thi'.$thirdparty->id;
388
+                        if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
+                        if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
390
+                    }
391
+                    else
392
+                    {
393
+                        $trackid=strtolower(get_class($objecttmp));
394
+                        if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
+                        if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
+                        if (get_class($objecttmp)=='Commande') $trackid='ord';
397
+                        if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
+                        if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
+                        if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
+                        if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
401
+
402
+                        $trackid.=$objecttmp->id;
403
+                    }
404
+                    //var_dump($filepath);
405
+                    //var_dump($trackid);exit;
406
+
407
+                    // Send mail (substitutionarray must be done just before this)
408
+                    require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
409
+                    $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
410
+                    if ($mailfile->error)
411
+                    {
412
+                        $resaction.='<div class="error">'.$mailfile->error.'</div>';
413
+                    }
414
+                    else
415
+                    {
416
+                        $result=$mailfile->sendfile();
417
+                        if ($result)
418
+                        {
419
+                            $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>';		// Must not contain "
420
+
421
+                            $error=0;
422
+
423
+                            // Insert logs into agenda
424
+                            foreach($listofqualifiedobj as $objid => $objectobj)
425
+                            {
426
+                                /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
427 427
 	                            if ($objectclass == 'Commande') $actiontypecode='AC_COM';
428 428
 	                            if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
429 429
 	                            if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
430 430
 	                            if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
431 431
 	                            if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
432 432
 
433
-								$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434
-								if ($message)
435
-								{
436
-									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
437
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
439
-									$actionmsg = dol_concatdesc($actionmsg, $message);
440
-								}
441
-								$actionmsg2='';
442
-
443
-								// Initialisation donnees
444
-								$objectobj->sendtoid		= 0;
445
-								$objectobj->actionmsg		= $actionmsg;  // Long text
446
-								$objectobj->actionmsg2		= $actionmsg2; // Short text
447
-								$objectobj->fk_element		= $objid;
448
-								$objectobj->elementtype	= $objectobj->element;
449
-
450
-								$triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
451
-								if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452
-								if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453
-								if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
454
-								if ($triggername == 'FACTURE_SENTBYMAIL')    $triggername = 'BILL_SENTBYMAIL';
455
-								if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
456
-								if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
457
-								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458
-								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
459
-
460
-								if (! empty($triggername))
461
-								{
462
-									// Appel des triggers
463
-									include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
464
-									$interface=new Interfaces($db);
465
-									$result=$interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
-									if ($result < 0) { $error++; $errors=$interface->errors; }
467
-									// Fin appel triggers
468
-
469
-									if ($error)
470
-									{
471
-										setEventMessages($db->lasterror(), $errors, 'errors');
472
-										dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
473
-									}
474
-								}
475
-
476
-								$nbsent++;
477
-							}
478
-						}
479
-						else
480
-						{
481
-							$langs->load("other");
482
-							if ($mailfile->error)
483
-							{
484
-								$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485
-								$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
486
-							}
487
-							else
488
-							{
489
-								$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490
-							}
491
-						}
492
-					}
493
-				}
494
-			}
495
-		}
496
-
497
-		$resaction.=($resaction?'<br>':$resaction);
498
-		$resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
-		$resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
-		$resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
501
-		$resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
502
-
503
-		if ($nbsent)
504
-		{
505
-			$action='';	// Do not show form post if there was at least one successfull sent
506
-			//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507
-			setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508
-			setEventMessages($resaction, null, 'mesgs');
509
-		}
510
-		else
511
-		{
512
-			//setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings');  // May be object has no generated PDF file
513
-			setEventMessages($resaction, null, 'warnings');
514
-		}
515
-
516
-		$action='list';
517
-		$massaction='';
518
-	}
433
+                                $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434
+                                if ($message)
435
+                                {
436
+                                    if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
437
+                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438
+                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
439
+                                    $actionmsg = dol_concatdesc($actionmsg, $message);
440
+                                }
441
+                                $actionmsg2='';
442
+
443
+                                // Initialisation donnees
444
+                                $objectobj->sendtoid		= 0;
445
+                                $objectobj->actionmsg		= $actionmsg;  // Long text
446
+                                $objectobj->actionmsg2		= $actionmsg2; // Short text
447
+                                $objectobj->fk_element		= $objid;
448
+                                $objectobj->elementtype	= $objectobj->element;
449
+
450
+                                $triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
451
+                                if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452
+                                if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453
+                                if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
454
+                                if ($triggername == 'FACTURE_SENTBYMAIL')    $triggername = 'BILL_SENTBYMAIL';
455
+                                if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
456
+                                if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
457
+                                if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458
+                                if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
459
+
460
+                                if (! empty($triggername))
461
+                                {
462
+                                    // Appel des triggers
463
+                                    include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
464
+                                    $interface=new Interfaces($db);
465
+                                    $result=$interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
+                                    if ($result < 0) { $error++; $errors=$interface->errors; }
467
+                                    // Fin appel triggers
468
+
469
+                                    if ($error)
470
+                                    {
471
+                                        setEventMessages($db->lasterror(), $errors, 'errors');
472
+                                        dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
473
+                                    }
474
+                                }
475
+
476
+                                $nbsent++;
477
+                            }
478
+                        }
479
+                        else
480
+                        {
481
+                            $langs->load("other");
482
+                            if ($mailfile->error)
483
+                            {
484
+                                $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485
+                                $resaction.='<br><div class="error">'.$mailfile->error.'</div>';
486
+                            }
487
+                            else
488
+                            {
489
+                                $resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490
+                            }
491
+                        }
492
+                    }
493
+                }
494
+            }
495
+        }
496
+
497
+        $resaction.=($resaction?'<br>':$resaction);
498
+        $resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
+        $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
+        $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
501
+        $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
502
+
503
+        if ($nbsent)
504
+        {
505
+            $action='';	// Do not show form post if there was at least one successfull sent
506
+            //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507
+            setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508
+            setEventMessages($resaction, null, 'mesgs');
509
+        }
510
+        else
511
+        {
512
+            //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings');  // May be object has no generated PDF file
513
+            setEventMessages($resaction, null, 'warnings');
514
+        }
515
+
516
+        $action='list';
517
+        $massaction='';
518
+    }
519 519
 }
520 520
 
521 521
 if ($massaction == 'confirm_createbills')
522 522
 {
523
-	$orders = GETPOST('toselect','array');
524
-	$createbills_onebythird = GETPOST('createbills_onebythird', 'int');
525
-	$validate_invoices = GETPOST('valdate_invoices', 'int');
526
-
527
-	$TFact = array();
528
-	$TFactThird = array();
529
-
530
-	$nb_bills_created = 0;
531
-
532
-	$db->begin();
533
-
534
-	foreach($orders as $id_order)
535
-	{
536
-		$cmd = new Commande($db);
537
-		if ($cmd->fetch($id_order) <= 0) continue;
538
-
539
-		$objecttmp = new Facture($db);
540
-		if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
541
-		else {
542
-
543
-			$objecttmp->socid = $cmd->socid;
544
-			$objecttmp->type = Facture::TYPE_STANDARD;
545
-			$objecttmp->cond_reglement_id	= $cmd->cond_reglement_id;
546
-			$objecttmp->mode_reglement_id	= $cmd->mode_reglement_id;
547
-			$objecttmp->fk_project			= $cmd->fk_project;
548
-
549
-			$datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
550
-			if (empty($datefacture))
551
-			{
552
-				$datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y"));
553
-			}
554
-
555
-			$objecttmp->date = $datefacture;
556
-			$objecttmp->origin    = 'commande';
557
-			$objecttmp->origin_id = $id_order;
558
-
559
-			$res = $objecttmp->create($user);
560
-
561
-			if($res > 0) $nb_bills_created++;
562
-		}
563
-
564
-		if ($objecttmp->id > 0)
565
-		{
566
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
567
-			$sql.= "fk_source";
568
-			$sql.= ", sourcetype";
569
-			$sql.= ", fk_target";
570
-			$sql.= ", targettype";
571
-			$sql.= ") VALUES (";
572
-			$sql.= $id_order;
573
-			$sql.= ", '".$objecttmp->origin."'";
574
-			$sql.= ", ".$objecttmp->id;
575
-			$sql.= ", '".$objecttmp->element."'";
576
-			$sql.= ")";
577
-
578
-			if (! $db->query($sql))
579
-			{
580
-				$error++;
581
-			}
582
-
583
-			if (! $error)
584
-			{
585
-				$lines = $cmd->lines;
586
-				if (empty($lines) && method_exists($cmd, 'fetch_lines'))
587
-				{
588
-					$cmd->fetch_lines();
589
-					$lines = $cmd->lines;
590
-				}
591
-
592
-				$fk_parent_line=0;
593
-				$num=count($lines);
594
-
595
-				for ($i=0;$i<$num;$i++)
596
-				{
597
-					$desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
598
-					if ($lines[$i]->subprice < 0)
599
-					{
600
-						// Negative line, we create a discount line
601
-						$discount = new DiscountAbsolute($db);
602
-						$discount->fk_soc=$objecttmp->socid;
603
-						$discount->amount_ht=abs($lines[$i]->total_ht);
604
-						$discount->amount_tva=abs($lines[$i]->total_tva);
605
-						$discount->amount_ttc=abs($lines[$i]->total_ttc);
606
-						$discount->tva_tx=$lines[$i]->tva_tx;
607
-						$discount->fk_user=$user->id;
608
-						$discount->description=$desc;
609
-						$discountid=$discount->create($user);
610
-						if ($discountid > 0)
611
-						{
612
-							$result=$objecttmp->insert_discount($discountid);
613
-							//$result=$discount->link_to_invoice($lineid,$id);
614
-						}
615
-						else
616
-						{
617
-							setEventMessages($discount->error, $discount->errors, 'errors');
618
-							$error++;
619
-							break;
620
-						}
621
-					}
622
-					else
623
-					{
624
-						// Positive line
625
-						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
626
-						// Date start
627
-						$date_start=false;
628
-						if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
-						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
-						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
631
-						//Date end
632
-						$date_end=false;
633
-						if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
-						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
-						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
636
-						// Reset fk_parent_line for no child products and special product
637
-						if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638
-						{
639
-							$fk_parent_line = 0;
640
-						}
641
-
642
-						// Extrafields
643
-						if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
644
-							$lines[$i]->fetch_optionals($lines[$i]->rowid);
645
-							$array_options = $lines[$i]->array_options;
646
-						}
647
-
648
-						$result = $objecttmp->addline(
649
-							$desc,
650
-							$lines[$i]->subprice,
651
-							$lines[$i]->qty,
652
-							$lines[$i]->tva_tx,
653
-							$lines[$i]->localtax1_tx,
654
-							$lines[$i]->localtax2_tx,
655
-							$lines[$i]->fk_product,
656
-							$lines[$i]->remise_percent,
657
-							$date_start,
658
-							$date_end,
659
-							0,
660
-							$lines[$i]->info_bits,
661
-							$lines[$i]->fk_remise_except,
662
-							'HT',
663
-							0,
664
-							$product_type,
665
-							$ii,
666
-							$lines[$i]->special_code,
667
-							$objecttmp->origin,
668
-							$lines[$i]->rowid,
669
-							$fk_parent_line,
670
-							$lines[$i]->fk_fournprice,
671
-							$lines[$i]->pa_ht,
672
-							$lines[$i]->label,
673
-							$array_options
674
-							);
675
-						if ($result > 0)
676
-						{
677
-							$lineid=$result;
678
-						}
679
-						else
680
-						{
681
-							$lineid=0;
682
-							$error++;
683
-							break;
684
-						}
685
-						// Defined the new fk_parent_line
686
-						if ($result > 0 && $lines[$i]->product_type == 9)
687
-						{
688
-							$fk_parent_line = $result;
689
-						}
690
-					}
691
-				}
692
-			}
693
-		}
694
-
695
-		//$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696
-
697
-		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698
-		else $TFact[$objecttmp->id] = $objecttmp;
699
-	}
700
-
701
-	// Build doc with all invoices
702
-	$TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
703
-	$toselect = array();
704
-
705
-	if (! $error && $validate_invoices)
706
-	{
707
-		$massaction = $action = 'builddoc';
708
-		foreach($TAllFact as &$objecttmp)
709
-		{
710
-			$result = $objecttmp->validate($user);
711
-			if ($result <= 0)
712
-			{
713
-				$error++;
714
-				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
715
-				break;
716
-			}
717
-
718
-			$id = $objecttmp->id; // For builddoc action
719
-
720
-			// Builddoc
721
-			$donotredirect = 1;
722
-			$upload_dir = $conf->facture->dir_output;
723
-			$permissioncreate=$user->rights->facture->creer;
724
-			include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
725
-		}
726
-
727
-		$massaction = $action = 'confirm_createbills';
728
-	}
729
-
730
-	if (! $error)
731
-	{
732
-		$db->commit();
733
-		setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
734
-
735
-		// Make a redirect to avoid to bill twice if we make a refresh or back
736
-		$param='';
737
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
-		if ($sall)					$param.='&sall='.urlencode($sall);
740
-		if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
-		if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
-		if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
-		if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
-		if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
-		if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
-		if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
-		if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
-		if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
-		if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
-		if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
-		if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
-		if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
-		if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
-		if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
-		if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
-		if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
-		if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
-		if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
-		if ($billed != '')			$param.='&billed='.urlencode($billed);
760
-
761
-		header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762
-		exit;
763
-	}
764
-	else
765
-	{
766
-		$db->rollback();
767
-		$action='create';
768
-		$_GET["origin"]=$_POST["origin"];
769
-		$_GET["originid"]=$_POST["originid"];
770
-		setEventMessages("Error", null, 'errors');
771
-		$error++;
772
-	}
523
+    $orders = GETPOST('toselect','array');
524
+    $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
525
+    $validate_invoices = GETPOST('valdate_invoices', 'int');
526
+
527
+    $TFact = array();
528
+    $TFactThird = array();
529
+
530
+    $nb_bills_created = 0;
531
+
532
+    $db->begin();
533
+
534
+    foreach($orders as $id_order)
535
+    {
536
+        $cmd = new Commande($db);
537
+        if ($cmd->fetch($id_order) <= 0) continue;
538
+
539
+        $objecttmp = new Facture($db);
540
+        if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
541
+        else {
542
+
543
+            $objecttmp->socid = $cmd->socid;
544
+            $objecttmp->type = Facture::TYPE_STANDARD;
545
+            $objecttmp->cond_reglement_id	= $cmd->cond_reglement_id;
546
+            $objecttmp->mode_reglement_id	= $cmd->mode_reglement_id;
547
+            $objecttmp->fk_project			= $cmd->fk_project;
548
+
549
+            $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
550
+            if (empty($datefacture))
551
+            {
552
+                $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y"));
553
+            }
554
+
555
+            $objecttmp->date = $datefacture;
556
+            $objecttmp->origin    = 'commande';
557
+            $objecttmp->origin_id = $id_order;
558
+
559
+            $res = $objecttmp->create($user);
560
+
561
+            if($res > 0) $nb_bills_created++;
562
+        }
563
+
564
+        if ($objecttmp->id > 0)
565
+        {
566
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
567
+            $sql.= "fk_source";
568
+            $sql.= ", sourcetype";
569
+            $sql.= ", fk_target";
570
+            $sql.= ", targettype";
571
+            $sql.= ") VALUES (";
572
+            $sql.= $id_order;
573
+            $sql.= ", '".$objecttmp->origin."'";
574
+            $sql.= ", ".$objecttmp->id;
575
+            $sql.= ", '".$objecttmp->element."'";
576
+            $sql.= ")";
577
+
578
+            if (! $db->query($sql))
579
+            {
580
+                $error++;
581
+            }
582
+
583
+            if (! $error)
584
+            {
585
+                $lines = $cmd->lines;
586
+                if (empty($lines) && method_exists($cmd, 'fetch_lines'))
587
+                {
588
+                    $cmd->fetch_lines();
589
+                    $lines = $cmd->lines;
590
+                }
591
+
592
+                $fk_parent_line=0;
593
+                $num=count($lines);
594
+
595
+                for ($i=0;$i<$num;$i++)
596
+                {
597
+                    $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
598
+                    if ($lines[$i]->subprice < 0)
599
+                    {
600
+                        // Negative line, we create a discount line
601
+                        $discount = new DiscountAbsolute($db);
602
+                        $discount->fk_soc=$objecttmp->socid;
603
+                        $discount->amount_ht=abs($lines[$i]->total_ht);
604
+                        $discount->amount_tva=abs($lines[$i]->total_tva);
605
+                        $discount->amount_ttc=abs($lines[$i]->total_ttc);
606
+                        $discount->tva_tx=$lines[$i]->tva_tx;
607
+                        $discount->fk_user=$user->id;
608
+                        $discount->description=$desc;
609
+                        $discountid=$discount->create($user);
610
+                        if ($discountid > 0)
611
+                        {
612
+                            $result=$objecttmp->insert_discount($discountid);
613
+                            //$result=$discount->link_to_invoice($lineid,$id);
614
+                        }
615
+                        else
616
+                        {
617
+                            setEventMessages($discount->error, $discount->errors, 'errors');
618
+                            $error++;
619
+                            break;
620
+                        }
621
+                    }
622
+                    else
623
+                    {
624
+                        // Positive line
625
+                        $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
626
+                        // Date start
627
+                        $date_start=false;
628
+                        if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
+                        if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
+                        if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
631
+                        //Date end
632
+                        $date_end=false;
633
+                        if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
+                        if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
+                        if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
636
+                        // Reset fk_parent_line for no child products and special product
637
+                        if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638
+                        {
639
+                            $fk_parent_line = 0;
640
+                        }
641
+
642
+                        // Extrafields
643
+                        if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
644
+                            $lines[$i]->fetch_optionals($lines[$i]->rowid);
645
+                            $array_options = $lines[$i]->array_options;
646
+                        }
647
+
648
+                        $result = $objecttmp->addline(
649
+                            $desc,
650
+                            $lines[$i]->subprice,
651
+                            $lines[$i]->qty,
652
+                            $lines[$i]->tva_tx,
653
+                            $lines[$i]->localtax1_tx,
654
+                            $lines[$i]->localtax2_tx,
655
+                            $lines[$i]->fk_product,
656
+                            $lines[$i]->remise_percent,
657
+                            $date_start,
658
+                            $date_end,
659
+                            0,
660
+                            $lines[$i]->info_bits,
661
+                            $lines[$i]->fk_remise_except,
662
+                            'HT',
663
+                            0,
664
+                            $product_type,
665
+                            $ii,
666
+                            $lines[$i]->special_code,
667
+                            $objecttmp->origin,
668
+                            $lines[$i]->rowid,
669
+                            $fk_parent_line,
670
+                            $lines[$i]->fk_fournprice,
671
+                            $lines[$i]->pa_ht,
672
+                            $lines[$i]->label,
673
+                            $array_options
674
+                            );
675
+                        if ($result > 0)
676
+                        {
677
+                            $lineid=$result;
678
+                        }
679
+                        else
680
+                        {
681
+                            $lineid=0;
682
+                            $error++;
683
+                            break;
684
+                        }
685
+                        // Defined the new fk_parent_line
686
+                        if ($result > 0 && $lines[$i]->product_type == 9)
687
+                        {
688
+                            $fk_parent_line = $result;
689
+                        }
690
+                    }
691
+                }
692
+            }
693
+        }
694
+
695
+        //$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696
+
697
+        if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698
+        else $TFact[$objecttmp->id] = $objecttmp;
699
+    }
700
+
701
+    // Build doc with all invoices
702
+    $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
703
+    $toselect = array();
704
+
705
+    if (! $error && $validate_invoices)
706
+    {
707
+        $massaction = $action = 'builddoc';
708
+        foreach($TAllFact as &$objecttmp)
709
+        {
710
+            $result = $objecttmp->validate($user);
711
+            if ($result <= 0)
712
+            {
713
+                $error++;
714
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
715
+                break;
716
+            }
717
+
718
+            $id = $objecttmp->id; // For builddoc action
719
+
720
+            // Builddoc
721
+            $donotredirect = 1;
722
+            $upload_dir = $conf->facture->dir_output;
723
+            $permissioncreate=$user->rights->facture->creer;
724
+            include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
725
+        }
726
+
727
+        $massaction = $action = 'confirm_createbills';
728
+    }
729
+
730
+    if (! $error)
731
+    {
732
+        $db->commit();
733
+        setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
734
+
735
+        // Make a redirect to avoid to bill twice if we make a refresh or back
736
+        $param='';
737
+        if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
+        if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
+        if ($sall)					$param.='&sall='.urlencode($sall);
740
+        if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
+        if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
+        if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
+        if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
+        if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
+        if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
+        if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
+        if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
+        if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
+        if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
+        if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
+        if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
+        if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
+        if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
+        if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
+        if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
+        if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
+        if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
+        if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
+        if ($billed != '')			$param.='&billed='.urlencode($billed);
760
+
761
+        header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762
+        exit;
763
+    }
764
+    else
765
+    {
766
+        $db->rollback();
767
+        $action='create';
768
+        $_GET["origin"]=$_POST["origin"];
769
+        $_GET["originid"]=$_POST["originid"];
770
+        setEventMessages("Error", null, 'errors');
771
+        $error++;
772
+    }
773 773
 }
774 774
 
775 775
 if (!$error && $massaction == 'cancelorders')
776 776
 {
777 777
 
778
-	$db->begin();
779
-
780
-	$nbok = 0;
781
-
782
-
783
-	$orders = GETPOST('toselect', 'array');
784
-	foreach ($orders as $id_order)
785
-	{
786
-
787
-		$cmd = new Commande($db);
788
-		if ($cmd->fetch($id_order) <= 0)
789
-			continue;
790
-
791
-		if ($cmd->statut != Commande::STATUS_VALIDATED)
792
-		{
793
-			$langs->load('errors');
794
-			setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
795
-			$error++;
796
-			break;
797
-		}
798
-		else
799
-			$result = $cmd->cancel();
800
-
801
-		if ($result < 0)
802
-		{
803
-			setEventMessages($cmd->error, $cmd->errors, 'errors');
804
-			$error++;
805
-			break;
806
-		}
807
-		else
808
-			$nbok++;
809
-	}
810
-	if (!$error)
811
-	{
812
-		if ($nbok > 1)
813
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814
-		else
815
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
816
-		$db->commit();
817
-	}
818
-	else
819
-	{
820
-		$db->rollback();
821
-	}
778
+    $db->begin();
779
+
780
+    $nbok = 0;
781
+
782
+
783
+    $orders = GETPOST('toselect', 'array');
784
+    foreach ($orders as $id_order)
785
+    {
786
+
787
+        $cmd = new Commande($db);
788
+        if ($cmd->fetch($id_order) <= 0)
789
+            continue;
790
+
791
+        if ($cmd->statut != Commande::STATUS_VALIDATED)
792
+        {
793
+            $langs->load('errors');
794
+            setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
795
+            $error++;
796
+            break;
797
+        }
798
+        else
799
+            $result = $cmd->cancel();
800
+
801
+        if ($result < 0)
802
+        {
803
+            setEventMessages($cmd->error, $cmd->errors, 'errors');
804
+            $error++;
805
+            break;
806
+        }
807
+        else
808
+            $nbok++;
809
+    }
810
+    if (!$error)
811
+    {
812
+        if ($nbok > 1)
813
+            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814
+        else
815
+            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
816
+        $db->commit();
817
+    }
818
+    else
819
+    {
820
+        $db->rollback();
821
+    }
822 822
 }
823 823
 
824 824
 
825 825
 if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search'))
826 826
 {
827
-	if (empty($diroutputmassaction))
828
-	{
829
-		dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
830
-		exit;
831
-	}
832
-
833
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
834
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
835
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
836
-
837
-	$objecttmp=new $objectclass($db);
838
-	$listofobjectid=array();
839
-	$listofobjectthirdparties=array();
840
-	$listofobjectref=array();
841
-	foreach($toselect as $toselectid)
842
-	{
843
-		$objecttmp=new $objectclass($db);	// must create new instance because instance is saved into $listofobjectref array for future use
844
-		$result=$objecttmp->fetch($toselectid);
845
-		if ($result > 0)
846
-		{
847
-			$listofobjectid[$toselectid]=$toselectid;
848
-			$thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
849
-			$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
850
-			$listofobjectref[$toselectid]=$objecttmp->ref;
851
-		}
852
-	}
853
-
854
-	$arrayofinclusion=array();
855
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
857
-	$listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
858
-
859
-	// build list of files with full path
860
-	$files = array();
861
-	foreach($listofobjectref as $basename)
862
-	{
863
-		$basename = dol_sanitizeFileName($basename);
864
-		foreach($listoffiles as $filefound)
865
-		{
866
-			if (strstr($filefound["name"],$basename))
867
-			{
868
-				$files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
869
-				break;
870
-			}
871
-		}
872
-	}
873
-
874
-	// Define output language (Here it is not used because we do only merging existing PDF)
875
-	$outputlangs = $langs;
876
-	$newlang='';
877
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
879
-	if (! empty($newlang))
880
-	{
881
-		$outputlangs = new Translate("",$conf);
882
-		$outputlangs->setDefaultLang($newlang);
883
-	}
884
-
885
-	if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT))
886
-	{
887
-		// Create output dir if not exists
888
-		dol_mkdir($diroutputmassaction);
889
-
890
-		// Defined name of merged file
891
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
-		$filename=preg_replace('/\s/','_',$filename);
893
-
894
-		// Save merged file
895
-		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896
-		{
897
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899
-		}
900
-		if ($year) $filename.='_'.$year;
901
-		if ($month) $filename.='_'.$month;
902
-
903
-		if (count($files)>0)
904
-		{
905
-			$now=dol_now();
906
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
907
-
908
-			$input_files = '';
909
-			foreach($files as $f) {
910
-				$input_files.=' '.escapeshellarg($f);
911
-			}
912
-
913
-			$cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914
-			exec($cmd);
915
-
916
-			if (! empty($conf->global->MAIN_UMASK))
917
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
918
-
919
-			$langs->load("exports");
920
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
921
-		}
922
-		else
923
-		{
924
-			setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
925
-		}
926
-	}
927
-	else {
928
-		// Create empty PDF
929
-		$formatarray=pdf_getFormat();
930
-		$page_largeur = $formatarray['width'];
931
-		$page_hauteur = $formatarray['height'];
932
-		$format = array($page_largeur,$page_hauteur);
933
-
934
-		$pdf=pdf_getInstance($format);
935
-
936
-		if (class_exists('TCPDF'))
937
-		{
938
-			$pdf->setPrintHeader(false);
939
-			$pdf->setPrintFooter(false);
940
-		}
941
-		$pdf->SetFont(pdf_getPDFFont($outputlangs));
942
-
943
-		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
944
-
945
-		// Add all others
946
-		foreach($files as $file)
947
-		{
948
-			// Charge un document PDF depuis un fichier.
949
-			$pagecount = $pdf->setSourceFile($file);
950
-			for ($i = 1; $i <= $pagecount; $i++)
951
-			{
952
-				$tplidx = $pdf->importPage($i);
953
-				$s = $pdf->getTemplatesize($tplidx);
954
-				$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
955
-				$pdf->useTemplate($tplidx);
956
-			}
957
-		}
958
-
959
-		// Create output dir if not exists
960
-		dol_mkdir($diroutputmassaction);
961
-
962
-		// Defined name of merged file
963
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
-		$filename=preg_replace('/\s/','_',$filename);
965
-
966
-		// Save merged file
967
-		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968
-		{
969
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
971
-		}
972
-		if ($year) $filename.='_'.$year;
973
-		if ($month) $filename.='_'.$month;
974
-		if ($pagecount)
975
-		{
976
-			$now=dol_now();
977
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978
-			$pdf->Output($file,'F');
979
-			if (! empty($conf->global->MAIN_UMASK))
980
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
981
-
982
-			$langs->load("exports");
983
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
984
-		}
985
-		else
986
-		{
987
-		setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
988
-		}
989
-	}
827
+    if (empty($diroutputmassaction))
828
+    {
829
+        dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
830
+        exit;
831
+    }
832
+
833
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
834
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
835
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
836
+
837
+    $objecttmp=new $objectclass($db);
838
+    $listofobjectid=array();
839
+    $listofobjectthirdparties=array();
840
+    $listofobjectref=array();
841
+    foreach($toselect as $toselectid)
842
+    {
843
+        $objecttmp=new $objectclass($db);	// must create new instance because instance is saved into $listofobjectref array for future use
844
+        $result=$objecttmp->fetch($toselectid);
845
+        if ($result > 0)
846
+        {
847
+            $listofobjectid[$toselectid]=$toselectid;
848
+            $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
849
+            $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
850
+            $listofobjectref[$toselectid]=$objecttmp->ref;
851
+        }
852
+    }
853
+
854
+    $arrayofinclusion=array();
855
+    foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
+    foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
857
+    $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
858
+
859
+    // build list of files with full path
860
+    $files = array();
861
+    foreach($listofobjectref as $basename)
862
+    {
863
+        $basename = dol_sanitizeFileName($basename);
864
+        foreach($listoffiles as $filefound)
865
+        {
866
+            if (strstr($filefound["name"],$basename))
867
+            {
868
+                $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
869
+                break;
870
+            }
871
+        }
872
+    }
873
+
874
+    // Define output language (Here it is not used because we do only merging existing PDF)
875
+    $outputlangs = $langs;
876
+    $newlang='';
877
+    if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
+    if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
879
+    if (! empty($newlang))
880
+    {
881
+        $outputlangs = new Translate("",$conf);
882
+        $outputlangs->setDefaultLang($newlang);
883
+    }
884
+
885
+    if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT))
886
+    {
887
+        // Create output dir if not exists
888
+        dol_mkdir($diroutputmassaction);
889
+
890
+        // Defined name of merged file
891
+        $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
+        $filename=preg_replace('/\s/','_',$filename);
893
+
894
+        // Save merged file
895
+        if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896
+        {
897
+            if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
+            else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899
+        }
900
+        if ($year) $filename.='_'.$year;
901
+        if ($month) $filename.='_'.$month;
902
+
903
+        if (count($files)>0)
904
+        {
905
+            $now=dol_now();
906
+            $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
907
+
908
+            $input_files = '';
909
+            foreach($files as $f) {
910
+                $input_files.=' '.escapeshellarg($f);
911
+            }
912
+
913
+            $cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914
+            exec($cmd);
915
+
916
+            if (! empty($conf->global->MAIN_UMASK))
917
+                @chmod($file, octdec($conf->global->MAIN_UMASK));
918
+
919
+            $langs->load("exports");
920
+            setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
921
+        }
922
+        else
923
+        {
924
+            setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
925
+        }
926
+    }
927
+    else {
928
+        // Create empty PDF
929
+        $formatarray=pdf_getFormat();
930
+        $page_largeur = $formatarray['width'];
931
+        $page_hauteur = $formatarray['height'];
932
+        $format = array($page_largeur,$page_hauteur);
933
+
934
+        $pdf=pdf_getInstance($format);
935
+
936
+        if (class_exists('TCPDF'))
937
+        {
938
+            $pdf->setPrintHeader(false);
939
+            $pdf->setPrintFooter(false);
940
+        }
941
+        $pdf->SetFont(pdf_getPDFFont($outputlangs));
942
+
943
+        if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
944
+
945
+        // Add all others
946
+        foreach($files as $file)
947
+        {
948
+            // Charge un document PDF depuis un fichier.
949
+            $pagecount = $pdf->setSourceFile($file);
950
+            for ($i = 1; $i <= $pagecount; $i++)
951
+            {
952
+                $tplidx = $pdf->importPage($i);
953
+                $s = $pdf->getTemplatesize($tplidx);
954
+                $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
955
+                $pdf->useTemplate($tplidx);
956
+            }
957
+        }
958
+
959
+        // Create output dir if not exists
960
+        dol_mkdir($diroutputmassaction);
961
+
962
+        // Defined name of merged file
963
+        $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
+        $filename=preg_replace('/\s/','_',$filename);
965
+
966
+        // Save merged file
967
+        if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968
+        {
969
+            if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
+            else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
971
+        }
972
+        if ($year) $filename.='_'.$year;
973
+        if ($month) $filename.='_'.$month;
974
+        if ($pagecount)
975
+        {
976
+            $now=dol_now();
977
+            $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978
+            $pdf->Output($file,'F');
979
+            if (! empty($conf->global->MAIN_UMASK))
980
+                @chmod($file, octdec($conf->global->MAIN_UMASK));
981
+
982
+            $langs->load("exports");
983
+            setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
984
+        }
985
+        else
986
+        {
987
+        setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
988
+        }
989
+    }
990 990
 }
991 991
 
992 992
 // Remove a file from massaction area
993 993
 if ($action == 'remove_file')
994 994
 {
995
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
996
-
997
-	$langs->load("other");
998
-	$upload_dir = $diroutputmassaction;
999
-	$file = $upload_dir . '/' . GETPOST('file');
1000
-	$ret=dol_delete_file($file);
1001
-	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002
-	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1003
-	$action='';
995
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
996
+
997
+    $langs->load("other");
998
+    $upload_dir = $diroutputmassaction;
999
+    $file = $upload_dir . '/' . GETPOST('file');
1000
+    $ret=dol_delete_file($file);
1001
+    if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002
+    else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1003
+    $action='';
1004 1004
 }
1005 1005
 
1006 1006
 // Validate records
1007 1007
 if (! $error && $massaction == 'validate' && $permtocreate)
1008 1008
 {
1009
-	$objecttmp=new $objectclass($db);
1010
-
1011
-	if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
1012
-	{
1013
-		$langs->load("errors");
1014
-		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1015
-		$error++;
1016
-	}
1017
-	if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1018
-	{
1019
-		$langs->load("errors");
1020
-		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1021
-		$error++;
1022
-	}
1023
-	if (! $error)
1024
-	{
1025
-		$db->begin();
1026
-
1027
-		$nbok = 0;
1028
-		foreach($toselect as $toselectid)
1029
-		{
1030
-			$result=$objecttmp->fetch($toselectid);
1031
-			if ($result > 0)
1032
-			{
1033
-				//if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1034
-				//else
1035
-				$result = $objecttmp->validate($user);
1036
-				if ($result == 0)
1037
-				{
1038
-					$langs->load("errors");
1039
-					setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1040
-					$error++;
1041
-					break;
1042
-				}
1043
-				elseif ($result < 0)
1044
-				{
1045
-					setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1046
-					$error++;
1047
-					break;
1048
-				}
1049
-				else $nbok++;
1050
-			}
1051
-			else
1052
-			{
1053
-				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1054
-				$error++;
1055
-				break;
1056
-			}
1057
-		}
1058
-
1059
-		if (! $error)
1060
-		{
1061
-			if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062
-			else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1063
-			$db->commit();
1064
-		}
1065
-		else
1066
-		{
1067
-			$db->rollback();
1068
-		}
1069
-		//var_dump($listofobjectthirdparties);exit;
1070
-	}
1009
+    $objecttmp=new $objectclass($db);
1010
+
1011
+    if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
1012
+    {
1013
+        $langs->load("errors");
1014
+        setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1015
+        $error++;
1016
+    }
1017
+    if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1018
+    {
1019
+        $langs->load("errors");
1020
+        setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1021
+        $error++;
1022
+    }
1023
+    if (! $error)
1024
+    {
1025
+        $db->begin();
1026
+
1027
+        $nbok = 0;
1028
+        foreach($toselect as $toselectid)
1029
+        {
1030
+            $result=$objecttmp->fetch($toselectid);
1031
+            if ($result > 0)
1032
+            {
1033
+                //if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1034
+                //else
1035
+                $result = $objecttmp->validate($user);
1036
+                if ($result == 0)
1037
+                {
1038
+                    $langs->load("errors");
1039
+                    setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1040
+                    $error++;
1041
+                    break;
1042
+                }
1043
+                elseif ($result < 0)
1044
+                {
1045
+                    setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1046
+                    $error++;
1047
+                    break;
1048
+                }
1049
+                else $nbok++;
1050
+            }
1051
+            else
1052
+            {
1053
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1054
+                $error++;
1055
+                break;
1056
+            }
1057
+        }
1058
+
1059
+        if (! $error)
1060
+        {
1061
+            if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062
+            else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1063
+            $db->commit();
1064
+        }
1065
+        else
1066
+        {
1067
+            $db->rollback();
1068
+        }
1069
+        //var_dump($listofobjectthirdparties);exit;
1070
+    }
1071 1071
 }
1072 1072
 // Closed records
1073 1073
 if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permtoclose) {
@@ -1107,127 +1107,127 @@  discard block
 block discarded – undo
1107 1107
 // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1108 1108
 if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
1109 1109
 {
1110
-	$db->begin();
1111
-
1112
-	$objecttmp=new $objectclass($db);
1113
-	$nbok = 0;
1114
-	foreach($toselect as $toselectid)
1115
-	{
1116
-		$result=$objecttmp->fetch($toselectid);
1117
-		if ($result > 0)
1118
-		{
1119
-			// Refuse deletion for some objects/status
1120
-			if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT)
1121
-			{
1122
-				$langs->load("errors");
1123
-				$nbignored++;
1124
-				$resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
1125
-				continue;
1126
-			}
1127
-
1128
-			if ($objectclass == "Task" && $objecttmp->hasChildren() > 0)
1129
-			{
1130
-				$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id;
1131
-				$res = $db->query($sql);
1132
-
1133
-				if (!$res)
1134
-				{
1135
-					setEventMessage('ErrorRecordParentingNotModified', 'errors');
1136
-					$error++;
1137
-				}
1138
-			}
1139
-
1140
-			if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1141
-			else $result = $objecttmp->delete($user);
1142
-
1143
-			if ($result <= 0)
1144
-			{
1145
-			    setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1146
-			    $error++;
1147
-			    break;
1148
-			}
1149
-			else $nbok++;
1150
-		}
1151
-		else
1152
-		{
1153
-			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1154
-			$error++;
1155
-			break;
1156
-		}
1157
-	}
1158
-
1159
-	if (! $error)
1160
-	{
1161
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162
-		else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1163
-		$db->commit();
1164
-	}
1165
-	else
1166
-	{
1167
-		$db->rollback();
1168
-	}
1169
-	//var_dump($listofobjectthirdparties);exit;
1110
+    $db->begin();
1111
+
1112
+    $objecttmp=new $objectclass($db);
1113
+    $nbok = 0;
1114
+    foreach($toselect as $toselectid)
1115
+    {
1116
+        $result=$objecttmp->fetch($toselectid);
1117
+        if ($result > 0)
1118
+        {
1119
+            // Refuse deletion for some objects/status
1120
+            if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT)
1121
+            {
1122
+                $langs->load("errors");
1123
+                $nbignored++;
1124
+                $resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
1125
+                continue;
1126
+            }
1127
+
1128
+            if ($objectclass == "Task" && $objecttmp->hasChildren() > 0)
1129
+            {
1130
+                $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id;
1131
+                $res = $db->query($sql);
1132
+
1133
+                if (!$res)
1134
+                {
1135
+                    setEventMessage('ErrorRecordParentingNotModified', 'errors');
1136
+                    $error++;
1137
+                }
1138
+            }
1139
+
1140
+            if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1141
+            else $result = $objecttmp->delete($user);
1142
+
1143
+            if ($result <= 0)
1144
+            {
1145
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1146
+                $error++;
1147
+                break;
1148
+            }
1149
+            else $nbok++;
1150
+        }
1151
+        else
1152
+        {
1153
+            setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1154
+            $error++;
1155
+            break;
1156
+        }
1157
+    }
1158
+
1159
+    if (! $error)
1160
+    {
1161
+        if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162
+        else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1163
+        $db->commit();
1164
+    }
1165
+    else
1166
+    {
1167
+        $db->rollback();
1168
+    }
1169
+    //var_dump($listofobjectthirdparties);exit;
1170 1170
 }
1171 1171
 
1172 1172
 // Generate document foreach object according to model linked to object
1173 1173
 // @TODO : propose model selection
1174 1174
 if (! $error && $massaction == 'generate_doc' && $permtoread)
1175 1175
 {
1176
-	$db->begin();
1177
-
1178
-	$objecttmp=new $objectclass($db);
1179
-	$nbok = 0;
1180
-	foreach($toselect as $toselectid)
1181
-	{
1182
-		$result=$objecttmp->fetch($toselectid);
1183
-		if ($result > 0)
1184
-		{
1185
-			$outputlangs = $langs;
1186
-			$newlang='';
1176
+    $db->begin();
1177
+
1178
+    $objecttmp=new $objectclass($db);
1179
+    $nbok = 0;
1180
+    foreach($toselect as $toselectid)
1181
+    {
1182
+        $result=$objecttmp->fetch($toselectid);
1183
+        if ($result > 0)
1184
+        {
1185
+            $outputlangs = $langs;
1186
+            $newlang='';
1187 1187
 	
1188
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1191
-			if (! empty($newlang))
1192
-			{
1193
-				$outputlangs = new Translate("",$conf);
1194
-				$outputlangs->setDefaultLang($newlang);
1195
-			}
1188
+            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
+            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
+            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1191
+            if (! empty($newlang))
1192
+            {
1193
+                $outputlangs = new Translate("",$conf);
1194
+                $outputlangs->setDefaultLang($newlang);
1195
+            }
1196 1196
 	
1197
-			// To be sure vars is defined
1198
-			if (empty($hidedetails)) $hidedetails=0;
1199
-			if (empty($hidedesc)) $hidedesc=0;
1200
-			if (empty($hideref)) $hideref=0;
1201
-			if (empty($moreparams)) $moreparams=null;
1197
+            // To be sure vars is defined
1198
+            if (empty($hidedetails)) $hidedetails=0;
1199
+            if (empty($hidedesc)) $hidedesc=0;
1200
+            if (empty($hideref)) $hideref=0;
1201
+            if (empty($moreparams)) $moreparams=null;
1202 1202
 			
1203
-			$result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204
-
1205
-			if ($result <= 0)
1206
-			{
1207
-				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1208
-				$error++;
1209
-				break;
1210
-			}
1211
-			else $nbok++;
1212
-		}
1213
-		else
1214
-		{
1215
-			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1216
-			$error++;
1217
-			break;
1218
-		}
1219
-	}
1220
-
1221
-	if (! $error)
1222
-	{
1223
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224
-		else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1225
-		$db->commit();
1226
-	}
1227
-	else
1228
-	{
1229
-		$db->rollback();
1230
-	}
1203
+            $result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204
+
1205
+            if ($result <= 0)
1206
+            {
1207
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1208
+                $error++;
1209
+                break;
1210
+            }
1211
+            else $nbok++;
1212
+        }
1213
+        else
1214
+        {
1215
+            setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1216
+            $error++;
1217
+            break;
1218
+        }
1219
+    }
1220
+
1221
+    if (! $error)
1222
+    {
1223
+        if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224
+        else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1225
+        $db->commit();
1226
+    }
1227
+    else
1228
+    {
1229
+        $db->rollback();
1230
+    }
1231 1231
 }
1232 1232
 
1233 1233
 $parameters['toselect']=$toselect;
Please login to merge, or discard this patch.
Spacing   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -42,23 +42,23 @@  discard block
 block discarded – undo
42 42
 
43 43
 
44 44
 // Mass actions. Controls on number of lines checked.
45
-$maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
46
-if (! empty($massaction) && count($toselect) < 1)
45
+$maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
46
+if (!empty($massaction) && count($toselect) < 1)
47 47
 {
48 48
 	$error++;
49 49
 	setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
50 50
 }
51
-if (! $error && is_array($toselect) && count($toselect) > $maxformassaction)
51
+if (!$error && is_array($toselect) && count($toselect) > $maxformassaction)
52 52
 {
53
-	setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
53
+	setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
54 54
 	$error++;
55 55
 }
56 56
 
57
-if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
57
+if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
58 58
 {
59
-	$massaction='presend';
59
+	$massaction = 'presend';
60 60
 }
61
-if (! $error && $massaction == 'confirm_presend')
61
+if (!$error && $massaction == 'confirm_presend')
62 62
 {
63 63
 	$resaction = '';
64 64
 	$nbsent = 0;
@@ -66,64 +66,64 @@  discard block
 block discarded – undo
66 66
 	$langs->load("mails");
67 67
 	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68 68
 
69
-	$listofobjectid=array();
70
-	$listofobjectthirdparties=array();
71
-	$listofobjectref=array();
69
+	$listofobjectid = array();
70
+	$listofobjectthirdparties = array();
71
+	$listofobjectref = array();
72 72
 
73
-	if (! $error)
73
+	if (!$error)
74 74
 	{
75
-		$thirdparty=new Societe($db);
76
-		if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
-		if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
75
+		$thirdparty = new Societe($db);
76
+		if ($objecttmp->element == 'expensereport') $thirdparty = new User($db);
77
+		if ($objecttmp->element == 'holiday')       $thirdparty = new User($db);
78 78
 
79
-		$objecttmp=new $objectclass($db);
80
-		foreach($toselect as $toselectid)
79
+		$objecttmp = new $objectclass($db);
80
+		foreach ($toselect as $toselectid)
81 81
 		{
82
-			$objecttmp=new $objectclass($db);	// we must create new instance because instance is saved into $listofobjectref array for future use
83
-			$result=$objecttmp->fetch($toselectid);
82
+			$objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
83
+			$result = $objecttmp->fetch($toselectid);
84 84
 			if ($result > 0)
85 85
 			{
86
-				$listofobjectid[$toselectid]=$toselectid;
87
-				$thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
-				if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
-				if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
-				if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
91
-				$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92
-				$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
86
+				$listofobjectid[$toselectid] = $toselectid;
87
+				$thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
88
+				if ($objecttmp->element == 'societe')       $thirdpartyid = $objecttmp->id;
89
+				if ($objecttmp->element == 'expensereport') $thirdpartyid = $objecttmp->fk_user_author;
90
+				if ($objecttmp->element == 'holiday')       $thirdpartyid = $objecttmp->fk_user;
91
+				$listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
92
+				$listofobjectref[$thirdpartyid][$toselectid] = $objecttmp;
93 93
 			}
94 94
 		}
95 95
 	}
96 96
 
97 97
 	// Check mandatory parameters
98
-	if (GETPOST('fromtype','alpha') === 'user' && empty($user->email))
98
+	if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email))
99 99
 	{
100 100
 		$error++;
101 101
 		setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
102
-		$massaction='presend';
102
+		$massaction = 'presend';
103 103
 	}
104 104
 
105
-	$receiver=$_POST['receiver'];
106
-	if (! is_array($receiver))
105
+	$receiver = $_POST['receiver'];
106
+	if (!is_array($receiver))
107 107
 	{
108
-		if (empty($receiver) || $receiver == '-1') $receiver=array();
109
-		else $receiver=array($receiver);
108
+		if (empty($receiver) || $receiver == '-1') $receiver = array();
109
+		else $receiver = array($receiver);
110 110
 	}
111
-	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
111
+	if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
112 112
 	{
113 113
 	 	$error++;
114 114
 	   	setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115
-	   	$massaction='presend';
115
+	   	$massaction = 'presend';
116 116
 	}
117 117
 
118
-	if (! GETPOST('subject','none'))
118
+	if (!GETPOST('subject', 'none'))
119 119
 	{
120 120
 		$error++;
121 121
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
122
-		$massaction='presend';
122
+		$massaction = 'presend';
123 123
 	}
124 124
 
125 125
 	// Loop on each recipient/thirdparty
126
-	if (! $error)
126
+	if (!$error)
127 127
 	{
128 128
 		foreach ($listofobjectthirdparties as $thirdpartyid)
129 129
 		{
@@ -134,21 +134,21 @@  discard block
 block discarded – undo
134 134
 				exit;
135 135
 			}
136 136
 
137
-			$sendto='';
138
-			$sendtocc='';
139
-			$sendtobcc='';
137
+			$sendto = '';
138
+			$sendtocc = '';
139
+			$sendtobcc = '';
140 140
 			$sendtoid = array();
141 141
 
142 142
 			// Define $sendto
143
-			$tmparray=array();
143
+			$tmparray = array();
144 144
 			if (trim($_POST['sendto']))
145 145
 			{
146 146
 				// Recipients are provided into free text
147 147
 				$tmparray[] = trim($_POST['sendto']);
148 148
 			}
149
-			if (count($receiver)>0)
149
+			if (count($receiver) > 0)
150 150
 			{
151
-				foreach($receiver as $key=>$val)
151
+				foreach ($receiver as $key=>$val)
152 152
 				{
153 153
 					// Recipient was provided from combo list
154 154
 					if ($val == 'thirdparty') // Id of third party or user
@@ -157,28 +157,28 @@  discard block
 block discarded – undo
157 157
 					}
158 158
 					elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
159 159
 					{
160
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
160
+						$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
161 161
 						$sendtoid[] = $val;
162 162
 					}
163 163
 				}
164 164
 			}
165
-			$sendto=implode(',',$tmparray);
165
+			$sendto = implode(',', $tmparray);
166 166
 
167 167
 			// Define $sendtocc
168
-			$receivercc=$_POST['receivercc'];
169
-			if (! is_array($receivercc))
168
+			$receivercc = $_POST['receivercc'];
169
+			if (!is_array($receivercc))
170 170
 			{
171
-				if ($receivercc == '-1') $receivercc=array();
172
-				else $receivercc=array($receivercc);
171
+				if ($receivercc == '-1') $receivercc = array();
172
+				else $receivercc = array($receivercc);
173 173
 			}
174
-			$tmparray=array();
174
+			$tmparray = array();
175 175
 			if (trim($_POST['sendtocc']))
176 176
 			{
177 177
 				$tmparray[] = trim($_POST['sendtocc']);
178 178
 			}
179 179
 			if (count($receivercc) > 0)
180 180
 			{
181
-				foreach($receivercc as $key=>$val)
181
+				foreach ($receivercc as $key=>$val)
182 182
 				{
183 183
 					// Recipient was provided from combo list
184 184
 					if ($val == 'thirdparty') // Id of third party
@@ -187,41 +187,41 @@  discard block
 block discarded – undo
187 187
 					}
188 188
 					elseif ($val)	// Id du contact
189 189
 					{
190
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
190
+						$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
191 191
 						//$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192 192
 					}
193 193
 				}
194 194
 			}
195
-			$sendtocc=implode(',',$tmparray);
195
+			$sendtocc = implode(',', $tmparray);
196 196
 
197 197
 			//var_dump($listofobjectref);exit;
198
-			$attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
-			$listofqualifiedobj=array();
200
-			$listofqualifiedref=array();
201
-			$thirdpartywithoutemail=array();
198
+			$attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
+			$listofqualifiedobj = array();
200
+			$listofqualifiedref = array();
201
+			$thirdpartywithoutemail = array();
202 202
 
203
-			foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
203
+			foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
204 204
 			{
205 205
 				//var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
206 206
 				if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
207 207
 				{
208 208
 					$langs->load("errors");
209 209
 					$nbignored++;
210
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
210
+					$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
211 211
 					continue; // Payment done or started or canceled
212 212
 				}
213 213
 				if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
214 214
 				{
215 215
 					$langs->load("errors");
216 216
 					$nbignored++;
217
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
217
+					$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
218 218
 					continue;
219 219
 				}
220 220
 				if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
221 221
 				{
222 222
 					$langs->load("errors");
223 223
 					$nbignored++;
224
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
224
+					$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
225 225
 					continue; // Payment done or started or canceled
226 226
 				}
227 227
 
@@ -247,10 +247,10 @@  discard block
 block discarded – undo
247 247
 				   	$nbignored++;
248 248
 				   	if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
249 249
 					{
250
-						$resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
250
+						$resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
251 251
 					}
252 252
 					dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
253
-					$thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
253
+					$thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
254 254
 				   	continue;
255 255
 				}
256 256
 
@@ -258,33 +258,33 @@  discard block
 block discarded – undo
258 258
 				{
259 259
 					// TODO Use future field $objectobj->fullpathdoc to know where is stored default file
260 260
 					// TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
261
-					$filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
262
-					$filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
263
-					$file = $filedir . '/' . $filename;
261
+					$filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
262
+					$filedir = $uploaddir.'/'.dol_sanitizeFileName($objectobj->ref);
263
+					$file = $filedir.'/'.$filename;
264 264
 					$mime = dol_mimetype($file);
265 265
 
266 266
 	   				if (dol_is_file($file))
267 267
 					{
268 268
 							// Create form object
269
-							$attachedfiles=array(
270
-							'paths'=>array_merge($attachedfiles['paths'],array($file)),
271
-							'names'=>array_merge($attachedfiles['names'],array($filename)),
272
-							'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
269
+							$attachedfiles = array(
270
+							'paths'=>array_merge($attachedfiles['paths'], array($file)),
271
+							'names'=>array_merge($attachedfiles['names'], array($filename)),
272
+							'mimes'=>array_merge($attachedfiles['mimes'], array($mime))
273 273
 							);
274 274
 					}
275 275
 					else
276 276
 					{
277 277
 							$nbignored++;
278 278
 							$langs->load("errors");
279
-							$resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
279
+							$resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file).'</div><br>';
280 280
 							dol_syslog('Failed to read file: '.$file, LOG_WARNING);
281 281
 							continue;
282 282
 					}
283 283
 				}
284 284
 
285 285
 				// Object of thirdparty qualified
286
-				$listofqualifiedobj[$objectid]=$objectobj;
287
-				$listofqualifiedref[$objectid]=$objectobj->ref;
286
+				$listofqualifiedobj[$objectid] = $objectobj;
287
+				$listofqualifiedref[$objectid] = $objectobj->ref;
288 288
 
289 289
 
290 290
 				//var_dump($listofqualifiedref);
@@ -297,21 +297,21 @@  discard block
 block discarded – undo
297 297
 
298 298
 				$fromtype = GETPOST('fromtype');
299 299
 				if ($fromtype === 'user') {
300
-					$from = $user->getFullName($langs) .' <'.$user->email.'>';
300
+					$from = $user->getFullName($langs).' <'.$user->email.'>';
301 301
 				}
302 302
 				elseif ($fromtype === 'company') {
303
-					$from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
303
+					$from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304 304
 				}
305 305
 				elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306
-					$tmp=explode(',', $user->email_aliases);
306
+					$tmp = explode(',', $user->email_aliases);
307 307
 					$from = trim($tmp[($reg[1] - 1)]);
308 308
 				}
309 309
 				elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310
-					$tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
310
+					$tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311 311
 					$from = trim($tmp[($reg[1] - 1)]);
312 312
 				}
313 313
 				elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314
-					$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
314
+					$sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315 315
 					$resql = $db->query($sql);
316 316
 					$obj = $db->fetch_object($resql);
317 317
 					if ($obj)
@@ -320,25 +320,25 @@  discard block
 block discarded – undo
320 320
 					}
321 321
 				}
322 322
 				else {
323
-					$from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
323
+					$from = $_POST['fromname'].' <'.$_POST['frommail'].'>';
324 324
 				}
325 325
 
326 326
 				$replyto = $from;
327
-				$subject = GETPOST('subject','none');
328
-				$message = GETPOST('message','none');
327
+				$subject = GETPOST('subject', 'none');
328
+				$message = GETPOST('message', 'none');
329 329
 
330 330
 				$sendtobcc = GETPOST('sendtoccc');
331
-				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
-				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
-				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
-				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
-				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
-				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
331
+				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
+				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
+				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
+				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
+				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
+				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
337 337
 
338 338
 				// $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339
-				$oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
340
-				$looparray=array();
341
-				if (! $oneemailperrecipient)
339
+				$oneemailperrecipient = (GETPOST('oneemailperrecipient') == 'on' ? 1 : 0);
340
+				$looparray = array();
341
+				if (!$oneemailperrecipient)
342 342
 				{
343 343
 					$looparray = $listofqualifiedobj;
344 344
 					foreach ($looparray as $key => $objecttmp)
@@ -348,34 +348,34 @@  discard block
 block discarded – undo
348 348
 				}
349 349
 				else
350 350
 				{
351
-					$objectforloop=new $objectclass($db);
351
+					$objectforloop = new $objectclass($db);
352 352
 					$objectforloop->thirdparty = $thirdparty;
353
-					$looparray[0]=$objectforloop;
353
+					$looparray[0] = $objectforloop;
354 354
 				}
355 355
 				//var_dump($looparray);exit;
356 356
 
357 357
 				foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358 358
 				{
359 359
 					// Make substitution in email content
360
-					$substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
-					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362
-					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
360
+					$substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
+					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
362
+					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
363 363
 					$substitutionarray['__EMAIL__'] = $thirdparty->email;
364 364
 					$substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
365 365
 
366
-					$parameters=array('mode'=>'formemail');
366
+					$parameters = array('mode'=>'formemail');
367 367
 
368
-					if ( ! empty( $listofobjectthirdparties ) ) {
368
+					if (!empty($listofobjectthirdparties)) {
369 369
 						$parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
370 370
 					}
371
-					if ( ! empty( $listofobjectref ) ) {
371
+					if (!empty($listofobjectref)) {
372 372
 						$parameters['listofobjectref'] = $listofobjectref;
373 373
 					}
374 374
 
375 375
 					complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
376 376
 
377
-					$subject=make_substitutions($subject, $substitutionarray);
378
-					$message=make_substitutions($message, $substitutionarray);
377
+					$subject = make_substitutions($subject, $substitutionarray);
378
+					$message = make_substitutions($message, $substitutionarray);
379 379
 
380 380
 					$filepath = $attachedfiles['paths'];
381 381
 					$filename = $attachedfiles['names'];
@@ -384,44 +384,44 @@  discard block
 block discarded – undo
384 384
 					// Define the trackid when emails sent from the mass action
385 385
 					if ($oneemailperrecipient)
386 386
 					{
387
-						$trackid='thi'.$thirdparty->id;
388
-						if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
-						if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
387
+						$trackid = 'thi'.$thirdparty->id;
388
+						if ($objecttmp->element == 'expensereport') $trackid = 'use'.$thirdparty->id;
389
+						if ($objecttmp->element == 'holiday') $trackid = 'use'.$thirdparty->id;
390 390
 					}
391 391
 					else
392 392
 					{
393
-						$trackid=strtolower(get_class($objecttmp));
394
-						if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
-						if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
-						if (get_class($objecttmp)=='Commande') $trackid='ord';
397
-						if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
-						if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
-						if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
-						if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
401
-
402
-						$trackid.=$objecttmp->id;
393
+						$trackid = strtolower(get_class($objecttmp));
394
+						if (get_class($objecttmp) == 'Contrat')  $trackid = 'con';
395
+						if (get_class($objecttmp) == 'Propal')   $trackid = 'pro';
396
+						if (get_class($objecttmp) == 'Commande') $trackid = 'ord';
397
+						if (get_class($objecttmp) == 'Facture')  $trackid = 'inv';
398
+						if (get_class($objecttmp) == 'Supplier_Proposal')   $trackid = 'spr';
399
+						if (get_class($objecttmp) == 'CommandeFournisseur') $trackid = 'sor';
400
+						if (get_class($objecttmp) == 'FactureFournisseur')  $trackid = 'sin';
401
+
402
+						$trackid .= $objecttmp->id;
403 403
 					}
404 404
 					//var_dump($filepath);
405 405
 					//var_dump($trackid);exit;
406 406
 
407 407
 					// Send mail (substitutionarray must be done just before this)
408 408
 					require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
409
-					$mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
409
+					$mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid);
410 410
 					if ($mailfile->error)
411 411
 					{
412
-						$resaction.='<div class="error">'.$mailfile->error.'</div>';
412
+						$resaction .= '<div class="error">'.$mailfile->error.'</div>';
413 413
 					}
414 414
 					else
415 415
 					{
416
-						$result=$mailfile->sendfile();
416
+						$result = $mailfile->sendfile();
417 417
 						if ($result)
418 418
 						{
419
-							$resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>';		// Must not contain "
419
+							$resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'<br>'; // Must not contain "
420 420
 
421
-							$error=0;
421
+							$error = 0;
422 422
 
423 423
 							// Insert logs into agenda
424
-							foreach($listofqualifiedobj as $objid => $objectobj)
424
+							foreach ($listofqualifiedobj as $objid => $objectobj)
425 425
 							{
426 426
 								/*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
427 427
 	                            if ($objectclass == 'Commande') $actiontypecode='AC_COM';
@@ -430,24 +430,24 @@  discard block
 block discarded – undo
430 430
 	                            if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
431 431
 	                            if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
432 432
 
433
-								$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
433
+								$actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434 434
 								if ($message)
435 435
 								{
436
-									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
437
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
436
+									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
437
+									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
438
+									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
439 439
 									$actionmsg = dol_concatdesc($actionmsg, $message);
440 440
 								}
441
-								$actionmsg2='';
441
+								$actionmsg2 = '';
442 442
 
443 443
 								// Initialisation donnees
444
-								$objectobj->sendtoid		= 0;
445
-								$objectobj->actionmsg		= $actionmsg;  // Long text
444
+								$objectobj->sendtoid = 0;
445
+								$objectobj->actionmsg = $actionmsg; // Long text
446 446
 								$objectobj->actionmsg2		= $actionmsg2; // Short text
447 447
 								$objectobj->fk_element		= $objid;
448 448
 								$objectobj->elementtype	= $objectobj->element;
449 449
 
450
-								$triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
450
+								$triggername = strtoupper(get_class($objectobj)).'_SENTBYMAIL';
451 451
 								if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452 452
 								if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453 453
 								if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
@@ -457,13 +457,13 @@  discard block
 block discarded – undo
457 457
 								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458 458
 								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
459 459
 
460
-								if (! empty($triggername))
460
+								if (!empty($triggername))
461 461
 								{
462 462
 									// Appel des triggers
463
-									include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
464
-									$interface=new Interfaces($db);
465
-									$result=$interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
-									if ($result < 0) { $error++; $errors=$interface->errors; }
463
+									include_once DOL_DOCUMENT_ROOT."/core/class/interfaces.class.php";
464
+									$interface = new Interfaces($db);
465
+									$result = $interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
+									if ($result < 0) { $error++; $errors = $interface->errors; }
467 467
 									// Fin appel triggers
468 468
 
469 469
 									if ($error)
@@ -481,12 +481,12 @@  discard block
 block discarded – undo
481 481
 							$langs->load("other");
482 482
 							if ($mailfile->error)
483 483
 							{
484
-								$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485
-								$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
484
+								$resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
485
+								$resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
486 486
 							}
487 487
 							else
488 488
 							{
489
-								$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
489
+								$resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490 490
 							}
491 491
 						}
492 492
 					}
@@ -494,15 +494,15 @@  discard block
 block discarded – undo
494 494
 			}
495 495
 		}
496 496
 
497
-		$resaction.=($resaction?'<br>':$resaction);
498
-		$resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
-		$resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
-		$resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
501
-		$resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
497
+		$resaction .= ($resaction ? '<br>' : $resaction);
498
+		$resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
+		$resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
+		$resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
501
+		$resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
502 502
 
503 503
 		if ($nbsent)
504 504
 		{
505
-			$action='';	// Do not show form post if there was at least one successfull sent
505
+			$action = ''; // Do not show form post if there was at least one successfull sent
506 506
 			//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507 507
 			setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508 508
 			setEventMessages($resaction, null, 'mesgs');
@@ -513,14 +513,14 @@  discard block
 block discarded – undo
513 513
 			setEventMessages($resaction, null, 'warnings');
514 514
 		}
515 515
 
516
-		$action='list';
517
-		$massaction='';
516
+		$action = 'list';
517
+		$massaction = '';
518 518
 	}
519 519
 }
520 520
 
521 521
 if ($massaction == 'confirm_createbills')
522 522
 {
523
-	$orders = GETPOST('toselect','array');
523
+	$orders = GETPOST('toselect', 'array');
524 524
 	$createbills_onebythird = GETPOST('createbills_onebythird', 'int');
525 525
 	$validate_invoices = GETPOST('valdate_invoices', 'int');
526 526
 
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 
532 532
 	$db->begin();
533 533
 
534
-	foreach($orders as $id_order)
534
+	foreach ($orders as $id_order)
535 535
 	{
536 536
 		$cmd = new Commande($db);
537 537
 		if ($cmd->fetch($id_order) <= 0) continue;
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 			$objecttmp->type = Facture::TYPE_STANDARD;
545 545
 			$objecttmp->cond_reglement_id	= $cmd->cond_reglement_id;
546 546
 			$objecttmp->mode_reglement_id	= $cmd->mode_reglement_id;
547
-			$objecttmp->fk_project			= $cmd->fk_project;
547
+			$objecttmp->fk_project = $cmd->fk_project;
548 548
 
549 549
 			$datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
550 550
 			if (empty($datefacture))
@@ -558,29 +558,29 @@  discard block
 block discarded – undo
558 558
 
559 559
 			$res = $objecttmp->create($user);
560 560
 
561
-			if($res > 0) $nb_bills_created++;
561
+			if ($res > 0) $nb_bills_created++;
562 562
 		}
563 563
 
564 564
 		if ($objecttmp->id > 0)
565 565
 		{
566 566
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
567
-			$sql.= "fk_source";
568
-			$sql.= ", sourcetype";
569
-			$sql.= ", fk_target";
570
-			$sql.= ", targettype";
571
-			$sql.= ") VALUES (";
572
-			$sql.= $id_order;
573
-			$sql.= ", '".$objecttmp->origin."'";
574
-			$sql.= ", ".$objecttmp->id;
575
-			$sql.= ", '".$objecttmp->element."'";
576
-			$sql.= ")";
577
-
578
-			if (! $db->query($sql))
567
+			$sql .= "fk_source";
568
+			$sql .= ", sourcetype";
569
+			$sql .= ", fk_target";
570
+			$sql .= ", targettype";
571
+			$sql .= ") VALUES (";
572
+			$sql .= $id_order;
573
+			$sql .= ", '".$objecttmp->origin."'";
574
+			$sql .= ", ".$objecttmp->id;
575
+			$sql .= ", '".$objecttmp->element."'";
576
+			$sql .= ")";
577
+
578
+			if (!$db->query($sql))
579 579
 			{
580 580
 				$error++;
581 581
 			}
582 582
 
583
-			if (! $error)
583
+			if (!$error)
584 584
 			{
585 585
 				$lines = $cmd->lines;
586 586
 				if (empty($lines) && method_exists($cmd, 'fetch_lines'))
@@ -589,27 +589,27 @@  discard block
 block discarded – undo
589 589
 					$lines = $cmd->lines;
590 590
 				}
591 591
 
592
-				$fk_parent_line=0;
593
-				$num=count($lines);
592
+				$fk_parent_line = 0;
593
+				$num = count($lines);
594 594
 
595
-				for ($i=0;$i<$num;$i++)
595
+				for ($i = 0; $i < $num; $i++)
596 596
 				{
597
-					$desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
597
+					$desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
598 598
 					if ($lines[$i]->subprice < 0)
599 599
 					{
600 600
 						// Negative line, we create a discount line
601 601
 						$discount = new DiscountAbsolute($db);
602
-						$discount->fk_soc=$objecttmp->socid;
603
-						$discount->amount_ht=abs($lines[$i]->total_ht);
604
-						$discount->amount_tva=abs($lines[$i]->total_tva);
605
-						$discount->amount_ttc=abs($lines[$i]->total_ttc);
606
-						$discount->tva_tx=$lines[$i]->tva_tx;
607
-						$discount->fk_user=$user->id;
608
-						$discount->description=$desc;
609
-						$discountid=$discount->create($user);
602
+						$discount->fk_soc = $objecttmp->socid;
603
+						$discount->amount_ht = abs($lines[$i]->total_ht);
604
+						$discount->amount_tva = abs($lines[$i]->total_tva);
605
+						$discount->amount_ttc = abs($lines[$i]->total_ttc);
606
+						$discount->tva_tx = $lines[$i]->tva_tx;
607
+						$discount->fk_user = $user->id;
608
+						$discount->description = $desc;
609
+						$discountid = $discount->create($user);
610 610
 						if ($discountid > 0)
611 611
 						{
612
-							$result=$objecttmp->insert_discount($discountid);
612
+							$result = $objecttmp->insert_discount($discountid);
613 613
 							//$result=$discount->link_to_invoice($lineid,$id);
614 614
 						}
615 615
 						else
@@ -622,17 +622,17 @@  discard block
 block discarded – undo
622 622
 					else
623 623
 					{
624 624
 						// Positive line
625
-						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
625
+						$product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
626 626
 						// Date start
627
-						$date_start=false;
628
-						if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
-						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
-						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
627
+						$date_start = false;
628
+						if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue;
629
+						if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel;
630
+						if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start;
631 631
 						//Date end
632
-						$date_end=false;
633
-						if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
-						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
-						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
632
+						$date_end = false;
633
+						if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue;
634
+						if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel;
635
+						if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end;
636 636
 						// Reset fk_parent_line for no child products and special product
637 637
 						if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638 638
 						{
@@ -674,11 +674,11 @@  discard block
 block discarded – undo
674 674
 							);
675 675
 						if ($result > 0)
676 676
 						{
677
-							$lineid=$result;
677
+							$lineid = $result;
678 678
 						}
679 679
 						else
680 680
 						{
681
-							$lineid=0;
681
+							$lineid = 0;
682 682
 							$error++;
683 683
 							break;
684 684
 						}
@@ -694,7 +694,7 @@  discard block
 block discarded – undo
694 694
 
695 695
 		//$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696 696
 
697
-		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
697
+		if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698 698
 		else $TFact[$objecttmp->id] = $objecttmp;
699 699
 	}
700 700
 
@@ -702,10 +702,10 @@  discard block
 block discarded – undo
702 702
 	$TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
703 703
 	$toselect = array();
704 704
 
705
-	if (! $error && $validate_invoices)
705
+	if (!$error && $validate_invoices)
706 706
 	{
707 707
 		$massaction = $action = 'builddoc';
708
-		foreach($TAllFact as &$objecttmp)
708
+		foreach ($TAllFact as &$objecttmp)
709 709
 		{
710 710
 			$result = $objecttmp->validate($user);
711 711
 			if ($result <= 0)
@@ -720,43 +720,43 @@  discard block
 block discarded – undo
720 720
 			// Builddoc
721 721
 			$donotredirect = 1;
722 722
 			$upload_dir = $conf->facture->dir_output;
723
-			$permissioncreate=$user->rights->facture->creer;
723
+			$permissioncreate = $user->rights->facture->creer;
724 724
 			include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
725 725
 		}
726 726
 
727 727
 		$massaction = $action = 'confirm_createbills';
728 728
 	}
729 729
 
730
-	if (! $error)
730
+	if (!$error)
731 731
 	{
732 732
 		$db->commit();
733 733
 		setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
734 734
 
735 735
 		// Make a redirect to avoid to bill twice if we make a refresh or back
736
-		$param='';
737
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
-		if ($sall)					$param.='&sall='.urlencode($sall);
740
-		if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
-		if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
-		if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
-		if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
-		if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
-		if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
-		if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
-		if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
-		if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
-		if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
-		if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
-		if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
-		if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
-		if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
-		if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
-		if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
-		if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
-		if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
-		if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
-		if ($billed != '')			$param.='&billed='.urlencode($billed);
736
+		$param = '';
737
+		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
738
+		if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
739
+		if ($sall)					$param .= '&sall='.urlencode($sall);
740
+		if ($socid > 0)             $param .= '&socid='.urlencode($socid);
741
+		if ($viewstatut != '')      $param .= '&viewstatut='.urlencode($viewstatut);
742
+		if ($search_orderday)      		$param .= '&search_orderday='.urlencode($search_orderday);
743
+		if ($search_ordermonth)      		$param .= '&search_ordermonth='.urlencode($search_ordermonth);
744
+		if ($search_orderyear)       		$param .= '&search_orderyear='.urlencode($search_orderyear);
745
+		if ($search_deliveryday)   		$param .= '&search_deliveryday='.urlencode($search_deliveryday);
746
+		if ($search_deliverymonth)   		$param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
747
+		if ($search_deliveryyear)    		$param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
748
+		if ($search_ref)      		$param .= '&search_ref='.urlencode($search_ref);
749
+		if ($search_company)  		$param .= '&search_company='.urlencode($search_company);
750
+		if ($search_ref_customer)	$param .= '&search_ref_customer='.urlencode($search_ref_customer);
751
+		if ($search_user > 0) 		$param .= '&search_user='.urlencode($search_user);
752
+		if ($search_sale > 0) 		$param .= '&search_sale='.urlencode($search_sale);
753
+		if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht);
754
+		if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat);
755
+		if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc);
756
+		if ($search_project_ref >= 0)  	$param .= "&search_project_ref=".urlencode($search_project_ref);
757
+		if ($show_files)            $param .= '&show_files='.urlencode($show_files);
758
+		if ($optioncss != '')       $param .= '&optioncss='.urlencode($optioncss);
759
+		if ($billed != '')			$param .= '&billed='.urlencode($billed);
760 760
 
761 761
 		header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762 762
 		exit;
@@ -764,9 +764,9 @@  discard block
 block discarded – undo
764 764
 	else
765 765
 	{
766 766
 		$db->rollback();
767
-		$action='create';
768
-		$_GET["origin"]=$_POST["origin"];
769
-		$_GET["originid"]=$_POST["originid"];
767
+		$action = 'create';
768
+		$_GET["origin"] = $_POST["origin"];
769
+		$_GET["originid"] = $_POST["originid"];
770 770
 		setEventMessages("Error", null, 'errors');
771 771
 		$error++;
772 772
 	}
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
 }
823 823
 
824 824
 
825
-if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search'))
825
+if (!$error && $massaction == "builddoc" && $permtoread && !GETPOST('button_search'))
826 826
 {
827 827
 	if (empty($diroutputmassaction))
828 828
 	{
@@ -834,36 +834,36 @@  discard block
 block discarded – undo
834 834
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
835 835
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
836 836
 
837
-	$objecttmp=new $objectclass($db);
838
-	$listofobjectid=array();
839
-	$listofobjectthirdparties=array();
840
-	$listofobjectref=array();
841
-	foreach($toselect as $toselectid)
837
+	$objecttmp = new $objectclass($db);
838
+	$listofobjectid = array();
839
+	$listofobjectthirdparties = array();
840
+	$listofobjectref = array();
841
+	foreach ($toselect as $toselectid)
842 842
 	{
843
-		$objecttmp=new $objectclass($db);	// must create new instance because instance is saved into $listofobjectref array for future use
844
-		$result=$objecttmp->fetch($toselectid);
843
+		$objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
844
+		$result = $objecttmp->fetch($toselectid);
845 845
 		if ($result > 0)
846 846
 		{
847
-			$listofobjectid[$toselectid]=$toselectid;
848
-			$thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
849
-			$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
850
-			$listofobjectref[$toselectid]=$objecttmp->ref;
847
+			$listofobjectid[$toselectid] = $toselectid;
848
+			$thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
849
+			$listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
850
+			$listofobjectref[$toselectid] = $objecttmp->ref;
851 851
 		}
852 852
 	}
853 853
 
854
-	$arrayofinclusion=array();
855
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
857
-	$listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
854
+	$arrayofinclusion = array();
855
+	foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
856
+	foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files
857
+	$listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
858 858
 
859 859
 	// build list of files with full path
860 860
 	$files = array();
861
-	foreach($listofobjectref as $basename)
861
+	foreach ($listofobjectref as $basename)
862 862
 	{
863 863
 		$basename = dol_sanitizeFileName($basename);
864
-		foreach($listoffiles as $filefound)
864
+		foreach ($listoffiles as $filefound)
865 865
 		{
866
-			if (strstr($filefound["name"],$basename))
866
+			if (strstr($filefound["name"], $basename))
867 867
 			{
868 868
 				$files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
869 869
 				break;
@@ -873,12 +873,12 @@  discard block
 block discarded – undo
873 873
 
874 874
 	// Define output language (Here it is not used because we do only merging existing PDF)
875 875
 	$outputlangs = $langs;
876
-	$newlang='';
877
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
879
-	if (! empty($newlang))
876
+	$newlang = '';
877
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
878
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $objecttmp->thirdparty->default_lang;
879
+	if (!empty($newlang))
880 880
 	{
881
-		$outputlangs = new Translate("",$conf);
881
+		$outputlangs = new Translate("", $conf);
882 882
 		$outputlangs->setDefaultLang($newlang);
883 883
 	}
884 884
 
@@ -888,36 +888,36 @@  discard block
 block discarded – undo
888 888
 		dol_mkdir($diroutputmassaction);
889 889
 
890 890
 		// Defined name of merged file
891
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
-		$filename=preg_replace('/\s/','_',$filename);
891
+		$filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
+		$filename = preg_replace('/\s/', '_', $filename);
893 893
 
894 894
 		// Save merged file
895 895
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896 896
 		{
897
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
897
+			if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
+			else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899 899
 		}
900
-		if ($year) $filename.='_'.$year;
901
-		if ($month) $filename.='_'.$month;
900
+		if ($year) $filename .= '_'.$year;
901
+		if ($month) $filename .= '_'.$month;
902 902
 
903
-		if (count($files)>0)
903
+		if (count($files) > 0)
904 904
 		{
905
-			$now=dol_now();
906
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
905
+			$now = dol_now();
906
+			$file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
907 907
 
908 908
 			$input_files = '';
909
-			foreach($files as $f) {
910
-				$input_files.=' '.escapeshellarg($f);
909
+			foreach ($files as $f) {
910
+				$input_files .= ' '.escapeshellarg($f);
911 911
 			}
912 912
 
913 913
 			$cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914 914
 			exec($cmd);
915 915
 
916
-			if (! empty($conf->global->MAIN_UMASK))
916
+			if (!empty($conf->global->MAIN_UMASK))
917 917
 				@chmod($file, octdec($conf->global->MAIN_UMASK));
918 918
 
919 919
 			$langs->load("exports");
920
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
920
+			setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
921 921
 		}
922 922
 		else
923 923
 		{
@@ -926,12 +926,12 @@  discard block
 block discarded – undo
926 926
 	}
927 927
 	else {
928 928
 		// Create empty PDF
929
-		$formatarray=pdf_getFormat();
929
+		$formatarray = pdf_getFormat();
930 930
 		$page_largeur = $formatarray['width'];
931 931
 		$page_hauteur = $formatarray['height'];
932
-		$format = array($page_largeur,$page_hauteur);
932
+		$format = array($page_largeur, $page_hauteur);
933 933
 
934
-		$pdf=pdf_getInstance($format);
934
+		$pdf = pdf_getInstance($format);
935 935
 
936 936
 		if (class_exists('TCPDF'))
937 937
 		{
@@ -940,10 +940,10 @@  discard block
 block discarded – undo
940 940
 		}
941 941
 		$pdf->SetFont(pdf_getPDFFont($outputlangs));
942 942
 
943
-		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
943
+		if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
944 944
 
945 945
 		// Add all others
946
-		foreach($files as $file)
946
+		foreach ($files as $file)
947 947
 		{
948 948
 			// Charge un document PDF depuis un fichier.
949 949
 			$pagecount = $pdf->setSourceFile($file);
@@ -960,27 +960,27 @@  discard block
 block discarded – undo
960 960
 		dol_mkdir($diroutputmassaction);
961 961
 
962 962
 		// Defined name of merged file
963
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
-		$filename=preg_replace('/\s/','_',$filename);
963
+		$filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
+		$filename = preg_replace('/\s/', '_', $filename);
965 965
 
966 966
 		// Save merged file
967 967
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968 968
 		{
969
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
969
+			if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
+			else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
971 971
 		}
972
-		if ($year) $filename.='_'.$year;
973
-		if ($month) $filename.='_'.$month;
972
+		if ($year) $filename .= '_'.$year;
973
+		if ($month) $filename .= '_'.$month;
974 974
 		if ($pagecount)
975 975
 		{
976
-			$now=dol_now();
977
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978
-			$pdf->Output($file,'F');
979
-			if (! empty($conf->global->MAIN_UMASK))
976
+			$now = dol_now();
977
+			$file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
978
+			$pdf->Output($file, 'F');
979
+			if (!empty($conf->global->MAIN_UMASK))
980 980
 				@chmod($file, octdec($conf->global->MAIN_UMASK));
981 981
 
982 982
 			$langs->load("exports");
983
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
983
+			setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
984 984
 		}
985 985
 		else
986 986
 		{
@@ -996,38 +996,38 @@  discard block
 block discarded – undo
996 996
 
997 997
 	$langs->load("other");
998 998
 	$upload_dir = $diroutputmassaction;
999
-	$file = $upload_dir . '/' . GETPOST('file');
1000
-	$ret=dol_delete_file($file);
999
+	$file = $upload_dir.'/'.GETPOST('file');
1000
+	$ret = dol_delete_file($file);
1001 1001
 	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002 1002
 	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1003
-	$action='';
1003
+	$action = '';
1004 1004
 }
1005 1005
 
1006 1006
 // Validate records
1007
-if (! $error && $massaction == 'validate' && $permtocreate)
1007
+if (!$error && $massaction == 'validate' && $permtocreate)
1008 1008
 {
1009
-	$objecttmp=new $objectclass($db);
1009
+	$objecttmp = new $objectclass($db);
1010 1010
 
1011
-	if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
1011
+	if ($objecttmp->element == 'invoice' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL))
1012 1012
 	{
1013 1013
 		$langs->load("errors");
1014 1014
 		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1015 1015
 		$error++;
1016 1016
 	}
1017
-	if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1017
+	if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1018 1018
 	{
1019 1019
 		$langs->load("errors");
1020 1020
 		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1021 1021
 		$error++;
1022 1022
 	}
1023
-	if (! $error)
1023
+	if (!$error)
1024 1024
 	{
1025 1025
 		$db->begin();
1026 1026
 
1027 1027
 		$nbok = 0;
1028
-		foreach($toselect as $toselectid)
1028
+		foreach ($toselect as $toselectid)
1029 1029
 		{
1030
-			$result=$objecttmp->fetch($toselectid);
1030
+			$result = $objecttmp->fetch($toselectid);
1031 1031
 			if ($result > 0)
1032 1032
 			{
1033 1033
 				//if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
 			}
1057 1057
 		}
1058 1058
 
1059
-		if (! $error)
1059
+		if (!$error)
1060 1060
 		{
1061 1061
 			if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062 1062
 			else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
@@ -1105,15 +1105,15 @@  discard block
 block discarded – undo
1105 1105
     }
1106 1106
 }
1107 1107
 // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1108
-if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
1108
+if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
1109 1109
 {
1110 1110
 	$db->begin();
1111 1111
 
1112
-	$objecttmp=new $objectclass($db);
1112
+	$objecttmp = new $objectclass($db);
1113 1113
 	$nbok = 0;
1114
-	foreach($toselect as $toselectid)
1114
+	foreach ($toselect as $toselectid)
1115 1115
 	{
1116
-		$result=$objecttmp->fetch($toselectid);
1116
+		$result = $objecttmp->fetch($toselectid);
1117 1117
 		if ($result > 0)
1118 1118
 		{
1119 1119
 			// Refuse deletion for some objects/status
@@ -1121,7 +1121,7 @@  discard block
 block discarded – undo
1121 1121
 			{
1122 1122
 				$langs->load("errors");
1123 1123
 				$nbignored++;
1124
-				$resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
1124
+				$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1125 1125
 				continue;
1126 1126
 			}
1127 1127
 
@@ -1156,7 +1156,7 @@  discard block
 block discarded – undo
1156 1156
 		}
1157 1157
 	}
1158 1158
 
1159
-	if (! $error)
1159
+	if (!$error)
1160 1160
 	{
1161 1161
 		if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162 1162
 		else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
@@ -1171,36 +1171,36 @@  discard block
 block discarded – undo
1171 1171
 
1172 1172
 // Generate document foreach object according to model linked to object
1173 1173
 // @TODO : propose model selection
1174
-if (! $error && $massaction == 'generate_doc' && $permtoread)
1174
+if (!$error && $massaction == 'generate_doc' && $permtoread)
1175 1175
 {
1176 1176
 	$db->begin();
1177 1177
 
1178
-	$objecttmp=new $objectclass($db);
1178
+	$objecttmp = new $objectclass($db);
1179 1179
 	$nbok = 0;
1180
-	foreach($toselect as $toselectid)
1180
+	foreach ($toselect as $toselectid)
1181 1181
 	{
1182
-		$result=$objecttmp->fetch($toselectid);
1182
+		$result = $objecttmp->fetch($toselectid);
1183 1183
 		if ($result > 0)
1184 1184
 		{
1185 1185
 			$outputlangs = $langs;
1186
-			$newlang='';
1186
+			$newlang = '';
1187 1187
 	
1188
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1191
-			if (! empty($newlang))
1188
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1189
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1190
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang = $objecttmp->default_lang; // for thirdparty
1191
+			if (!empty($newlang))
1192 1192
 			{
1193
-				$outputlangs = new Translate("",$conf);
1193
+				$outputlangs = new Translate("", $conf);
1194 1194
 				$outputlangs->setDefaultLang($newlang);
1195 1195
 			}
1196 1196
 	
1197 1197
 			// To be sure vars is defined
1198
-			if (empty($hidedetails)) $hidedetails=0;
1199
-			if (empty($hidedesc)) $hidedesc=0;
1200
-			if (empty($hideref)) $hideref=0;
1201
-			if (empty($moreparams)) $moreparams=null;
1198
+			if (empty($hidedetails)) $hidedetails = 0;
1199
+			if (empty($hidedesc)) $hidedesc = 0;
1200
+			if (empty($hideref)) $hideref = 0;
1201
+			if (empty($moreparams)) $moreparams = null;
1202 1202
 			
1203
-			$result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1203
+			$result = $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204 1204
 
1205 1205
 			if ($result <= 0)
1206 1206
 			{
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
 		}
1219 1219
 	}
1220 1220
 
1221
-	if (! $error)
1221
+	if (!$error)
1222 1222
 	{
1223 1223
 		if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224 1224
 		else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
@@ -1230,10 +1230,10 @@  discard block
 block discarded – undo
1230 1230
 	}
1231 1231
 }
1232 1232
 
1233
-$parameters['toselect']=$toselect;
1234
-$parameters['uploaddir']=$uploaddir;
1233
+$parameters['toselect'] = $toselect;
1234
+$parameters['uploaddir'] = $uploaddir;
1235 1235
 
1236
-$reshook=$hookmanager->executeHooks('doMassActions',$parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1236
+$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1237 1237
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1238 1238
 
1239 1239
 
Please login to merge, or discard this patch.
Braces   +372 added lines, -189 removed lines patch added patch discarded remove patch
@@ -54,10 +54,12 @@  discard block
 block discarded – undo
54 54
 	$error++;
55 55
 }
56 56
 
57
-if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
57
+if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail')) {
58
+    // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
58 59
 {
59 60
 	$massaction='presend';
60 61
 }
62
+}
61 63
 if (! $error && $massaction == 'confirm_presend')
62 64
 {
63 65
 	$resaction = '';
@@ -73,8 +75,12 @@  discard block
 block discarded – undo
73 75
 	if (! $error)
74 76
 	{
75 77
 		$thirdparty=new Societe($db);
76
-		if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
-		if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
78
+		if ($objecttmp->element == 'expensereport') {
79
+		    $thirdparty=new User($db);
80
+		}
81
+		if ($objecttmp->element == 'holiday') {
82
+		    $thirdparty=new User($db);
83
+		}
78 84
 
79 85
 		$objecttmp=new $objectclass($db);
80 86
 		foreach($toselect as $toselectid)
@@ -85,9 +91,15 @@  discard block
 block discarded – undo
85 91
 			{
86 92
 				$listofobjectid[$toselectid]=$toselectid;
87 93
 				$thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
-				if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
-				if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
-				if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
94
+				if ($objecttmp->element == 'societe') {
95
+				    $thirdpartyid=$objecttmp->id;
96
+				}
97
+				if ($objecttmp->element == 'expensereport') {
98
+				    $thirdpartyid=$objecttmp->fk_user_author;
99
+				}
100
+				if ($objecttmp->element == 'holiday') {
101
+				    $thirdpartyid=$objecttmp->fk_user;
102
+				}
91 103
 				$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92 104
 				$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
93 105
 			}
@@ -105,12 +117,17 @@  discard block
 block discarded – undo
105 117
 	$receiver=$_POST['receiver'];
106 118
 	if (! is_array($receiver))
107 119
 	{
108
-		if (empty($receiver) || $receiver == '-1') $receiver=array();
109
-		else $receiver=array($receiver);
120
+		if (empty($receiver) || $receiver == '-1') {
121
+		    $receiver=array();
122
+		} else {
123
+		    $receiver=array($receiver);
124
+		}
110 125
 	}
111
-	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
126
+	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) {
127
+	    // if only one recipient, receiver is mandatory
112 128
 	{
113 129
 	 	$error++;
130
+	}
114 131
 	   	setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115 132
 	   	$massaction='presend';
116 133
 	}
@@ -151,13 +168,16 @@  discard block
 block discarded – undo
151 168
 				foreach($receiver as $key=>$val)
152 169
 				{
153 170
 					// Recipient was provided from combo list
154
-					if ($val == 'thirdparty') // Id of third party or user
171
+					if ($val == 'thirdparty') {
172
+					    // Id of third party or user
155 173
 					{
156 174
 						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
157 175
 					}
158
-					elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
176
+					} elseif ($val && method_exists($thirdparty, 'contact_get_property')) {
177
+					    // Id of contact
159 178
 					{
160 179
 						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
180
+					}
161 181
 						$sendtoid[] = $val;
162 182
 					}
163 183
 				}
@@ -168,8 +188,11 @@  discard block
 block discarded – undo
168 188
 			$receivercc=$_POST['receivercc'];
169 189
 			if (! is_array($receivercc))
170 190
 			{
171
-				if ($receivercc == '-1') $receivercc=array();
172
-				else $receivercc=array($receivercc);
191
+				if ($receivercc == '-1') {
192
+				    $receivercc=array();
193
+				} else {
194
+				    $receivercc=array($receivercc);
195
+				}
173 196
 			}
174 197
 			$tmparray=array();
175 198
 			if (trim($_POST['sendtocc']))
@@ -181,13 +204,16 @@  discard block
 block discarded – undo
181 204
 				foreach($receivercc as $key=>$val)
182 205
 				{
183 206
 					// Recipient was provided from combo list
184
-					if ($val == 'thirdparty') // Id of third party
207
+					if ($val == 'thirdparty') {
208
+					    // Id of third party
185 209
 					{
186 210
 						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
187 211
 					}
188
-					elseif ($val)	// Id du contact
212
+					} elseif ($val) {
213
+					    // Id du contact
189 214
 					{
190 215
 						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
216
+					}
191 217
 						//$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192 218
 					}
193 219
 				}
@@ -226,15 +252,16 @@  discard block
 block discarded – undo
226 252
 				}
227 253
 
228 254
 				// Test recipient
229
-				if (empty($sendto)) 	// For the case, no recipient were set (multi thirdparties send)
255
+				if (empty($sendto)) {
256
+				    // For the case, no recipient were set (multi thirdparties send)
230 257
 				{
231 258
 					if ($objectobj->element == 'expensereport')
232 259
 					{
233 260
 						$fuser = new User($db);
261
+				}
234 262
 						$fuser->fetch($objectobj->fk_user_author);
235 263
 						$sendto = $fuser->email;
236
-					}
237
-					else
264
+					} else
238 265
 					{
239 266
 						$objectobj->fetch_thirdparty();
240 267
 						$sendto = $objectobj->thirdparty->email;
@@ -271,8 +298,7 @@  discard block
 block discarded – undo
271 298
 							'names'=>array_merge($attachedfiles['names'],array($filename)),
272 299
 							'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
273 300
 							);
274
-					}
275
-					else
301
+					} else
276 302
 					{
277 303
 							$nbignored++;
278 304
 							$langs->load("errors");
@@ -298,19 +324,15 @@  discard block
 block discarded – undo
298 324
 				$fromtype = GETPOST('fromtype');
299 325
 				if ($fromtype === 'user') {
300 326
 					$from = $user->getFullName($langs) .' <'.$user->email.'>';
301
-				}
302
-				elseif ($fromtype === 'company') {
327
+				} elseif ($fromtype === 'company') {
303 328
 					$from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304
-				}
305
-				elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
329
+				} elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306 330
 					$tmp=explode(',', $user->email_aliases);
307 331
 					$from = trim($tmp[($reg[1] - 1)]);
308
-				}
309
-				elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
332
+				} elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310 333
 					$tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311 334
 					$from = trim($tmp[($reg[1] - 1)]);
312
-				}
313
-				elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
335
+				} elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314 336
 					$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315 337
 					$resql = $db->query($sql);
316 338
 					$obj = $db->fetch_object($resql);
@@ -318,8 +340,7 @@  discard block
 block discarded – undo
318 340
 					{
319 341
 						$from = $obj->label.' <'.$obj->email.'>';
320 342
 					}
321
-				}
322
-				else {
343
+				} else {
323 344
 					$from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
324 345
 				}
325 346
 
@@ -328,12 +349,24 @@  discard block
 block discarded – undo
328 349
 				$message = GETPOST('message','none');
329 350
 
330 351
 				$sendtobcc = GETPOST('sendtoccc');
331
-				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
-				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
-				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
-				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
-				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
-				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
352
+				if ($objectclass == 'Propal') {
353
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
354
+				}
355
+				if ($objectclass == 'Commande') {
356
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
357
+				}
358
+				if ($objectclass == 'Facture') {
359
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
360
+				}
361
+				if ($objectclass == 'Supplier_Proposal') {
362
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
363
+				}
364
+				if ($objectclass == 'CommandeFournisseur') {
365
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
366
+				}
367
+				if ($objectclass == 'FactureFournisseur') {
368
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
369
+				}
337 370
 
338 371
 				// $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339 372
 				$oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
@@ -345,8 +378,7 @@  discard block
 block discarded – undo
345 378
 					{
346 379
 						$looparray[$key]->thirdparty = $thirdparty;
347 380
 					}
348
-				}
349
-				else
381
+				} else
350 382
 				{
351 383
 					$objectforloop=new $objectclass($db);
352 384
 					$objectforloop->thirdparty = $thirdparty;
@@ -354,10 +386,12 @@  discard block
 block discarded – undo
354 386
 				}
355 387
 				//var_dump($looparray);exit;
356 388
 
357
-				foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
389
+				foreach ($looparray as $objecttmp) {
390
+				    // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358 391
 				{
359 392
 					// Make substitution in email content
360 393
 					$substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
394
+				}
361 395
 					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362 396
 					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
363 397
 					$substitutionarray['__EMAIL__'] = $thirdparty->email;
@@ -385,19 +419,36 @@  discard block
 block discarded – undo
385 419
 					if ($oneemailperrecipient)
386 420
 					{
387 421
 						$trackid='thi'.$thirdparty->id;
388
-						if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
-						if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
390
-					}
391
-					else
422
+						if ($objecttmp->element == 'expensereport') {
423
+						    $trackid='use'.$thirdparty->id;
424
+						}
425
+						if ($objecttmp->element == 'holiday') {
426
+						    $trackid='use'.$thirdparty->id;
427
+						}
428
+					} else
392 429
 					{
393 430
 						$trackid=strtolower(get_class($objecttmp));
394
-						if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
-						if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
-						if (get_class($objecttmp)=='Commande') $trackid='ord';
397
-						if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
-						if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
-						if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
-						if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
431
+						if (get_class($objecttmp)=='Contrat') {
432
+						    $trackid='con';
433
+						}
434
+						if (get_class($objecttmp)=='Propal') {
435
+						    $trackid='pro';
436
+						}
437
+						if (get_class($objecttmp)=='Commande') {
438
+						    $trackid='ord';
439
+						}
440
+						if (get_class($objecttmp)=='Facture') {
441
+						    $trackid='inv';
442
+						}
443
+						if (get_class($objecttmp)=='Supplier_Proposal') {
444
+						    $trackid='spr';
445
+						}
446
+						if (get_class($objecttmp)=='CommandeFournisseur') {
447
+						    $trackid='sor';
448
+						}
449
+						if (get_class($objecttmp)=='FactureFournisseur') {
450
+						    $trackid='sin';
451
+						}
401 452
 
402 453
 						$trackid.=$objecttmp->id;
403 454
 					}
@@ -410,8 +461,7 @@  discard block
 block discarded – undo
410 461
 					if ($mailfile->error)
411 462
 					{
412 463
 						$resaction.='<div class="error">'.$mailfile->error.'</div>';
413
-					}
414
-					else
464
+					} else
415 465
 					{
416 466
 						$result=$mailfile->sendfile();
417 467
 						if ($result)
@@ -433,7 +483,9 @@  discard block
 block discarded – undo
433 483
 								$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434 484
 								if ($message)
435 485
 								{
436
-									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
486
+									if ($sendtocc) {
487
+									    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
488
+									}
437 489
 									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438 490
 									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
439 491
 									$actionmsg = dol_concatdesc($actionmsg, $message);
@@ -448,14 +500,30 @@  discard block
 block discarded – undo
448 500
 								$objectobj->elementtype	= $objectobj->element;
449 501
 
450 502
 								$triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
451
-								if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452
-								if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453
-								if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
454
-								if ($triggername == 'FACTURE_SENTBYMAIL')    $triggername = 'BILL_SENTBYMAIL';
455
-								if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
456
-								if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
457
-								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458
-								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
503
+								if ($triggername == 'SOCIETE_SENTBYMAIL') {
504
+								    $triggername = 'COMPANY_SENTBYEMAIL';
505
+								}
506
+								if ($triggername == 'CONTRAT_SENTBYMAIL') {
507
+								    $triggername = 'CONTRACT_SENTBYEMAIL';
508
+								}
509
+								if ($triggername == 'COMMANDE_SENTBYMAIL') {
510
+								    $triggername = 'ORDER_SENTBYEMAIL';
511
+								}
512
+								if ($triggername == 'FACTURE_SENTBYMAIL') {
513
+								    $triggername = 'BILL_SENTBYMAIL';
514
+								}
515
+								if ($triggername == 'EXPEDITION_SENTBYMAIL') {
516
+								    $triggername = 'SHIPPING_SENTBYEMAIL';
517
+								}
518
+								if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
519
+								    $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
520
+								}
521
+								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
522
+								    $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
523
+								}
524
+								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
525
+								    $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
526
+								}
459 527
 
460 528
 								if (! empty($triggername))
461 529
 								{
@@ -475,16 +543,14 @@  discard block
 block discarded – undo
475 543
 
476 544
 								$nbsent++;
477 545
 							}
478
-						}
479
-						else
546
+						} else
480 547
 						{
481 548
 							$langs->load("other");
482 549
 							if ($mailfile->error)
483 550
 							{
484 551
 								$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485 552
 								$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
486
-							}
487
-							else
553
+							} else
488 554
 							{
489 555
 								$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490 556
 							}
@@ -506,8 +572,7 @@  discard block
 block discarded – undo
506 572
 			//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507 573
 			setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508 574
 			setEventMessages($resaction, null, 'mesgs');
509
-		}
510
-		else
575
+		} else
511 576
 		{
512 577
 			//setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings');  // May be object has no generated PDF file
513 578
 			setEventMessages($resaction, null, 'warnings');
@@ -534,10 +599,15 @@  discard block
 block discarded – undo
534 599
 	foreach($orders as $id_order)
535 600
 	{
536 601
 		$cmd = new Commande($db);
537
-		if ($cmd->fetch($id_order) <= 0) continue;
602
+		if ($cmd->fetch($id_order) <= 0) {
603
+		    continue;
604
+		}
538 605
 
539 606
 		$objecttmp = new Facture($db);
540
-		if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
607
+		if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) {
608
+		    $objecttmp = $TFactThird[$cmd->socid];
609
+		}
610
+		// If option "one bill per third" is set, we use already created order.
541 611
 		else {
542 612
 
543 613
 			$objecttmp->socid = $cmd->socid;
@@ -558,7 +628,9 @@  discard block
 block discarded – undo
558 628
 
559 629
 			$res = $objecttmp->create($user);
560 630
 
561
-			if($res > 0) $nb_bills_created++;
631
+			if($res > 0) {
632
+			    $nb_bills_created++;
633
+			}
562 634
 		}
563 635
 
564 636
 		if ($objecttmp->id > 0)
@@ -611,28 +683,38 @@  discard block
 block discarded – undo
611 683
 						{
612 684
 							$result=$objecttmp->insert_discount($discountid);
613 685
 							//$result=$discount->link_to_invoice($lineid,$id);
614
-						}
615
-						else
686
+						} else
616 687
 						{
617 688
 							setEventMessages($discount->error, $discount->errors, 'errors');
618 689
 							$error++;
619 690
 							break;
620 691
 						}
621
-					}
622
-					else
692
+					} else
623 693
 					{
624 694
 						// Positive line
625 695
 						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
626 696
 						// Date start
627 697
 						$date_start=false;
628
-						if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
-						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
-						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
698
+						if ($lines[$i]->date_debut_prevue) {
699
+						    $date_start=$lines[$i]->date_debut_prevue;
700
+						}
701
+						if ($lines[$i]->date_debut_reel) {
702
+						    $date_start=$lines[$i]->date_debut_reel;
703
+						}
704
+						if ($lines[$i]->date_start) {
705
+						    $date_start=$lines[$i]->date_start;
706
+						}
631 707
 						//Date end
632 708
 						$date_end=false;
633
-						if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
-						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
-						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
709
+						if ($lines[$i]->date_fin_prevue) {
710
+						    $date_end=$lines[$i]->date_fin_prevue;
711
+						}
712
+						if ($lines[$i]->date_fin_reel) {
713
+						    $date_end=$lines[$i]->date_fin_reel;
714
+						}
715
+						if ($lines[$i]->date_end) {
716
+						    $date_end=$lines[$i]->date_end;
717
+						}
636 718
 						// Reset fk_parent_line for no child products and special product
637 719
 						if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638 720
 						{
@@ -675,8 +757,7 @@  discard block
 block discarded – undo
675 757
 						if ($result > 0)
676 758
 						{
677 759
 							$lineid=$result;
678
-						}
679
-						else
760
+						} else
680 761
 						{
681 762
 							$lineid=0;
682 763
 							$error++;
@@ -694,8 +775,11 @@  discard block
 block discarded – undo
694 775
 
695 776
 		//$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696 777
 
697
-		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698
-		else $TFact[$objecttmp->id] = $objecttmp;
778
+		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) {
779
+		    $TFactThird[$cmd->socid] = $objecttmp;
780
+		} else {
781
+		    $TFact[$objecttmp->id] = $objecttmp;
782
+		}
699 783
 	}
700 784
 
701 785
 	// Build doc with all invoices
@@ -734,34 +818,79 @@  discard block
 block discarded – undo
734 818
 
735 819
 		// Make a redirect to avoid to bill twice if we make a refresh or back
736 820
 		$param='';
737
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
-		if ($sall)					$param.='&sall='.urlencode($sall);
740
-		if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
-		if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
-		if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
-		if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
-		if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
-		if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
-		if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
-		if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
-		if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
-		if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
-		if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
-		if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
-		if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
-		if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
-		if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
-		if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
-		if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
-		if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
-		if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
-		if ($billed != '')			$param.='&billed='.urlencode($billed);
821
+		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
822
+		    $param.='&contextpage='.urlencode($contextpage);
823
+		}
824
+		if ($limit > 0 && $limit != $conf->liste_limit) {
825
+		    $param.='&limit='.urlencode($limit);
826
+		}
827
+		if ($sall) {
828
+		    $param.='&sall='.urlencode($sall);
829
+		}
830
+		if ($socid > 0) {
831
+		    $param.='&socid='.urlencode($socid);
832
+		}
833
+		if ($viewstatut != '') {
834
+		    $param.='&viewstatut='.urlencode($viewstatut);
835
+		}
836
+		if ($search_orderday) {
837
+		    $param.='&search_orderday='.urlencode($search_orderday);
838
+		}
839
+		if ($search_ordermonth) {
840
+		    $param.='&search_ordermonth='.urlencode($search_ordermonth);
841
+		}
842
+		if ($search_orderyear) {
843
+		    $param.='&search_orderyear='.urlencode($search_orderyear);
844
+		}
845
+		if ($search_deliveryday) {
846
+		    $param.='&search_deliveryday='.urlencode($search_deliveryday);
847
+		}
848
+		if ($search_deliverymonth) {
849
+		    $param.='&search_deliverymonth='.urlencode($search_deliverymonth);
850
+		}
851
+		if ($search_deliveryyear) {
852
+		    $param.='&search_deliveryyear='.urlencode($search_deliveryyear);
853
+		}
854
+		if ($search_ref) {
855
+		    $param.='&search_ref='.urlencode($search_ref);
856
+		}
857
+		if ($search_company) {
858
+		    $param.='&search_company='.urlencode($search_company);
859
+		}
860
+		if ($search_ref_customer) {
861
+		    $param.='&search_ref_customer='.urlencode($search_ref_customer);
862
+		}
863
+		if ($search_user > 0) {
864
+		    $param.='&search_user='.urlencode($search_user);
865
+		}
866
+		if ($search_sale > 0) {
867
+		    $param.='&search_sale='.urlencode($search_sale);
868
+		}
869
+		if ($search_total_ht != '') {
870
+		    $param.='&search_total_ht='.urlencode($search_total_ht);
871
+		}
872
+		if ($search_total_vat != '') {
873
+		    $param.='&search_total_vat='.urlencode($search_total_vat);
874
+		}
875
+		if ($search_total_ttc != '') {
876
+		    $param.='&search_total_ttc='.urlencode($search_total_ttc);
877
+		}
878
+		if ($search_project_ref >= 0) {
879
+		    $param.="&search_project_ref=".urlencode($search_project_ref);
880
+		}
881
+		if ($show_files) {
882
+		    $param.='&show_files=' .urlencode($show_files);
883
+		}
884
+		if ($optioncss != '') {
885
+		    $param.='&optioncss='.urlencode($optioncss);
886
+		}
887
+		if ($billed != '') {
888
+		    $param.='&billed='.urlencode($billed);
889
+		}
760 890
 
761 891
 		header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762 892
 		exit;
763
-	}
764
-	else
893
+	} else
765 894
 	{
766 895
 		$db->rollback();
767 896
 		$action='create';
@@ -785,8 +914,9 @@  discard block
 block discarded – undo
785 914
 	{
786 915
 
787 916
 		$cmd = new Commande($db);
788
-		if ($cmd->fetch($id_order) <= 0)
789
-			continue;
917
+		if ($cmd->fetch($id_order) <= 0) {
918
+					continue;
919
+		}
790 920
 
791 921
 		if ($cmd->statut != Commande::STATUS_VALIDATED)
792 922
 		{
@@ -794,28 +924,28 @@  discard block
 block discarded – undo
794 924
 			setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
795 925
 			$error++;
796 926
 			break;
927
+		} else {
928
+					$result = $cmd->cancel();
797 929
 		}
798
-		else
799
-			$result = $cmd->cancel();
800 930
 
801 931
 		if ($result < 0)
802 932
 		{
803 933
 			setEventMessages($cmd->error, $cmd->errors, 'errors');
804 934
 			$error++;
805 935
 			break;
936
+		} else {
937
+					$nbok++;
806 938
 		}
807
-		else
808
-			$nbok++;
809 939
 	}
810 940
 	if (!$error)
811 941
 	{
812
-		if ($nbok > 1)
813
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814
-		else
815
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
942
+		if ($nbok > 1) {
943
+					setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
944
+		} else {
945
+					setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
946
+		}
816 947
 		$db->commit();
817
-	}
818
-	else
948
+	} else
819 949
 	{
820 950
 		$db->rollback();
821 951
 	}
@@ -852,8 +982,13 @@  discard block
 block discarded – undo
852 982
 	}
853 983
 
854 984
 	$arrayofinclusion=array();
855
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
985
+	foreach($listofobjectref as $tmppdf) {
986
+	    $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
987
+	}
988
+	foreach($listofobjectref as $tmppdf) {
989
+	    $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';
990
+	}
991
+	// To include PDF generated from ODX files
857 992
 	$listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
858 993
 
859 994
 	// build list of files with full path
@@ -874,8 +1009,12 @@  discard block
 block discarded – undo
874 1009
 	// Define output language (Here it is not used because we do only merging existing PDF)
875 1010
 	$outputlangs = $langs;
876 1011
 	$newlang='';
877
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
1012
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
1013
+	    $newlang=GETPOST('lang_id','aZ09');
1014
+	}
1015
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
1016
+	    $newlang=$objecttmp->thirdparty->default_lang;
1017
+	}
879 1018
 	if (! empty($newlang))
880 1019
 	{
881 1020
 		$outputlangs = new Translate("",$conf);
@@ -894,11 +1033,18 @@  discard block
 block discarded – undo
894 1033
 		// Save merged file
895 1034
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896 1035
 		{
897
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1036
+			if ($option=='late') {
1037
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
1038
+			} else {
1039
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1040
+			}
1041
+		}
1042
+		if ($year) {
1043
+		    $filename.='_'.$year;
1044
+		}
1045
+		if ($month) {
1046
+		    $filename.='_'.$month;
899 1047
 		}
900
-		if ($year) $filename.='_'.$year;
901
-		if ($month) $filename.='_'.$month;
902 1048
 
903 1049
 		if (count($files)>0)
904 1050
 		{
@@ -913,18 +1059,17 @@  discard block
 block discarded – undo
913 1059
 			$cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914 1060
 			exec($cmd);
915 1061
 
916
-			if (! empty($conf->global->MAIN_UMASK))
917
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
1062
+			if (! empty($conf->global->MAIN_UMASK)) {
1063
+							@chmod($file, octdec($conf->global->MAIN_UMASK));
1064
+			}
918 1065
 
919 1066
 			$langs->load("exports");
920 1067
 			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
921
-		}
922
-		else
1068
+		} else
923 1069
 		{
924 1070
 			setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
925 1071
 		}
926
-	}
927
-	else {
1072
+	} else {
928 1073
 		// Create empty PDF
929 1074
 		$formatarray=pdf_getFormat();
930 1075
 		$page_largeur = $formatarray['width'];
@@ -940,7 +1085,9 @@  discard block
 block discarded – undo
940 1085
 		}
941 1086
 		$pdf->SetFont(pdf_getPDFFont($outputlangs));
942 1087
 
943
-		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
1088
+		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
1089
+		    $pdf->SetCompression(false);
1090
+		}
944 1091
 
945 1092
 		// Add all others
946 1093
 		foreach($files as $file)
@@ -966,23 +1113,30 @@  discard block
 block discarded – undo
966 1113
 		// Save merged file
967 1114
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968 1115
 		{
969
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1116
+			if ($option=='late') {
1117
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
1118
+			} else {
1119
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1120
+			}
1121
+		}
1122
+		if ($year) {
1123
+		    $filename.='_'.$year;
1124
+		}
1125
+		if ($month) {
1126
+		    $filename.='_'.$month;
971 1127
 		}
972
-		if ($year) $filename.='_'.$year;
973
-		if ($month) $filename.='_'.$month;
974 1128
 		if ($pagecount)
975 1129
 		{
976 1130
 			$now=dol_now();
977 1131
 			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978 1132
 			$pdf->Output($file,'F');
979
-			if (! empty($conf->global->MAIN_UMASK))
980
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
1133
+			if (! empty($conf->global->MAIN_UMASK)) {
1134
+							@chmod($file, octdec($conf->global->MAIN_UMASK));
1135
+			}
981 1136
 
982 1137
 			$langs->load("exports");
983 1138
 			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
984
-		}
985
-		else
1139
+		} else
986 1140
 		{
987 1141
 		setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
988 1142
 		}
@@ -998,8 +1152,11 @@  discard block
 block discarded – undo
998 1152
 	$upload_dir = $diroutputmassaction;
999 1153
 	$file = $upload_dir . '/' . GETPOST('file');
1000 1154
 	$ret=dol_delete_file($file);
1001
-	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002
-	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1155
+	if ($ret) {
1156
+	    setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1157
+	} else {
1158
+	    setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1159
+	}
1003 1160
 	$action='';
1004 1161
 }
1005 1162
 
@@ -1039,16 +1196,15 @@  discard block
 block discarded – undo
1039 1196
 					setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1040 1197
 					$error++;
1041 1198
 					break;
1042
-				}
1043
-				elseif ($result < 0)
1199
+				} elseif ($result < 0)
1044 1200
 				{
1045 1201
 					setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1046 1202
 					$error++;
1047 1203
 					break;
1204
+				} else {
1205
+				    $nbok++;
1048 1206
 				}
1049
-				else $nbok++;
1050
-			}
1051
-			else
1207
+			} else
1052 1208
 			{
1053 1209
 				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1054 1210
 				$error++;
@@ -1058,11 +1214,13 @@  discard block
 block discarded – undo
1058 1214
 
1059 1215
 		if (! $error)
1060 1216
 		{
1061
-			if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062
-			else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1217
+			if ($nbok > 1) {
1218
+			    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1219
+			} else {
1220
+			    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1221
+			}
1063 1222
 			$db->commit();
1064
-		}
1065
-		else
1223
+		} else
1066 1224
 		{
1067 1225
 			$db->rollback();
1068 1226
 		}
@@ -1083,10 +1241,10 @@  discard block
 block discarded – undo
1083 1241
                 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1084 1242
                 $error++;
1085 1243
                 break;
1086
-            } else
1087
-                $nbok++;
1088
-        }
1089
-        else {
1244
+            } else {
1245
+                            $nbok++;
1246
+            }
1247
+        } else {
1090 1248
             setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1091 1249
             $error++;
1092 1250
             break;
@@ -1094,13 +1252,13 @@  discard block
 block discarded – undo
1094 1252
     }
1095 1253
 
1096 1254
     if (!$error) {
1097
-        if ($nbok > 1)
1098
-            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1099
-        else
1100
-            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1255
+        if ($nbok > 1) {
1256
+                    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1257
+        } else {
1258
+                    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1259
+        }
1101 1260
         $db->commit();
1102
-    }
1103
-    else {
1261
+    } else {
1104 1262
         $db->rollback();
1105 1263
     }
1106 1264
 }
@@ -1137,18 +1295,21 @@  discard block
 block discarded – undo
1137 1295
 				}
1138 1296
 			}
1139 1297
 
1140
-			if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1141
-			else $result = $objecttmp->delete($user);
1298
+			if (in_array($objecttmp->element, array('societe', 'member'))) {
1299
+			    $result = $objecttmp->delete($objecttmp->id, $user, 1);
1300
+			} else {
1301
+			    $result = $objecttmp->delete($user);
1302
+			}
1142 1303
 
1143 1304
 			if ($result <= 0)
1144 1305
 			{
1145 1306
 			    setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1146 1307
 			    $error++;
1147 1308
 			    break;
1309
+			} else {
1310
+			    $nbok++;
1148 1311
 			}
1149
-			else $nbok++;
1150
-		}
1151
-		else
1312
+		} else
1152 1313
 		{
1153 1314
 			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1154 1315
 			$error++;
@@ -1158,11 +1319,13 @@  discard block
 block discarded – undo
1158 1319
 
1159 1320
 	if (! $error)
1160 1321
 	{
1161
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162
-		else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1322
+		if ($nbok > 1) {
1323
+		    setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1324
+		} else {
1325
+		    setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1326
+		}
1163 1327
 		$db->commit();
1164
-	}
1165
-	else
1328
+	} else
1166 1329
 	{
1167 1330
 		$db->rollback();
1168 1331
 	}
@@ -1185,9 +1348,17 @@  discard block
 block discarded – undo
1185 1348
 			$outputlangs = $langs;
1186 1349
 			$newlang='';
1187 1350
 	
1188
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1351
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
1352
+			    $newlang=GETPOST('lang_id','aZ09');
1353
+			}
1354
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1355
+			    $newlang=$objecttmp->thirdparty->default_lang;
1356
+			}
1357
+			// for proposal, order, invoice, ...
1358
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) {
1359
+			    $newlang=$objecttmp->default_lang;
1360
+			}
1361
+			// for thirdparty
1191 1362
 			if (! empty($newlang))
1192 1363
 			{
1193 1364
 				$outputlangs = new Translate("",$conf);
@@ -1195,10 +1366,18 @@  discard block
 block discarded – undo
1195 1366
 			}
1196 1367
 	
1197 1368
 			// To be sure vars is defined
1198
-			if (empty($hidedetails)) $hidedetails=0;
1199
-			if (empty($hidedesc)) $hidedesc=0;
1200
-			if (empty($hideref)) $hideref=0;
1201
-			if (empty($moreparams)) $moreparams=null;
1369
+			if (empty($hidedetails)) {
1370
+			    $hidedetails=0;
1371
+			}
1372
+			if (empty($hidedesc)) {
1373
+			    $hidedesc=0;
1374
+			}
1375
+			if (empty($hideref)) {
1376
+			    $hideref=0;
1377
+			}
1378
+			if (empty($moreparams)) {
1379
+			    $moreparams=null;
1380
+			}
1202 1381
 			
1203 1382
 			$result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204 1383
 
@@ -1207,10 +1386,10 @@  discard block
 block discarded – undo
1207 1386
 				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1208 1387
 				$error++;
1209 1388
 				break;
1389
+			} else {
1390
+			    $nbok++;
1210 1391
 			}
1211
-			else $nbok++;
1212
-		}
1213
-		else
1392
+		} else
1214 1393
 		{
1215 1394
 			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1216 1395
 			$error++;
@@ -1220,11 +1399,13 @@  discard block
 block discarded – undo
1220 1399
 
1221 1400
 	if (! $error)
1222 1401
 	{
1223
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224
-		else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1402
+		if ($nbok > 1) {
1403
+		    setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1404
+		} else {
1405
+		    setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1406
+		}
1225 1407
 		$db->commit();
1226
-	}
1227
-	else
1408
+	} else
1228 1409
 	{
1229 1410
 		$db->rollback();
1230 1411
 	}
@@ -1234,7 +1415,9 @@  discard block
 block discarded – undo
1234 1415
 $parameters['uploaddir']=$uploaddir;
1235 1416
 
1236 1417
 $reshook=$hookmanager->executeHooks('doMassActions',$parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1237
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1418
+if ($reshook < 0) {
1419
+    setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1420
+}
1238 1421
 
1239 1422
 
1240 1423
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/js/lib_notification.js.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 
29 29
 require_once '../../main.inc.php';
30 30
 
31
-if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/index.php'
31
+if (!($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root.'/' || $_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root.'/index.php'
32 32
     || preg_match('/getmenu_div\.php/', $_SERVER['HTTP_REFERER'])))
33 33
 {
34 34
     global $langs, $conf;
@@ -44,17 +44,17 @@  discard block
 block discarded – undo
44 44
     header('Cache-Control: no-cache');
45 45
     session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
46 46
     session_start();*/
47
-    if (! isset($_SESSION['auto_check_events_not_before']))
47
+    if (!isset($_SESSION['auto_check_events_not_before']))
48 48
     {
49 49
         print 'console.log("_SESSION[auto_check_events_not_before] is not set");'."\n";
50 50
         // Round to eliminate the seconds
51 51
         $_SESSION['auto_check_events_not_before'] = $nowtime;
52 52
     }
53
-    print 'var nowtime = ' . $nowtime . ';' . "\n";
54
-    print 'var login = \'' . $_SESSION['dol_login'] . '\';' . "\n";
55
-    print 'var auto_check_events_not_before = '.$_SESSION['auto_check_events_not_before']. ';'."\n";
53
+    print 'var nowtime = '.$nowtime.';'."\n";
54
+    print 'var login = \''.$_SESSION['dol_login'].'\';'."\n";
55
+    print 'var auto_check_events_not_before = '.$_SESSION['auto_check_events_not_before'].';'."\n";
56 56
     print 'var time_js_next_test = Math.max(nowtime, auto_check_events_not_before);'."\n";
57
-    print 'var time_auto_update = '.$conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY.';'."\n";   // Always defined
57
+    print 'var time_auto_update = '.$conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY.';'."\n"; // Always defined
58 58
     ?>
59 59
 
60 60
 	/* Check if permission ok */
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
                     if (arr.length > 0) {
91 91
                     	var audio = null;
92 92
                         <?php
93
-                        if (! empty($conf->global->AGENDA_REMINDER_BROWSER_SOUND)) {
93
+                        if (!empty($conf->global->AGENDA_REMINDER_BROWSER_SOUND)) {
94 94
                             print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav'.'\');';
95 95
                         }
96 96
                         ?>
Please login to merge, or discard this patch.
Braces   +21 added lines, -7 removed lines patch added patch discarded remove patch
@@ -18,13 +18,27 @@
 block discarded – undo
18 18
  * Library javascript to enable Browser notifications
19 19
  */
20 20
 
21
-if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1');
22
-if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1');
23
-if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1);
24
-if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1);
25
-if (!defined('NOLOGIN')) define('NOLOGIN', 1);
26
-if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1);
27
-if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1);
21
+if (!defined('NOREQUIREUSER')) {
22
+    define('NOREQUIREUSER', '1');
23
+}
24
+if (!defined('NOREQUIRESOC')) {
25
+    define('NOREQUIRESOC', '1');
26
+}
27
+if (!defined('NOCSRFCHECK')) {
28
+    define('NOCSRFCHECK', 1);
29
+}
30
+if (!defined('NOTOKENRENEWAL')) {
31
+    define('NOTOKENRENEWAL', 1);
32
+}
33
+if (!defined('NOLOGIN')) {
34
+    define('NOLOGIN', 1);
35
+}
36
+if (!defined('NOREQUIREMENU')) {
37
+    define('NOREQUIREMENU', 1);
38
+}
39
+if (!defined('NOREQUIREHTML')) {
40
+    define('NOREQUIREHTML', 1);
41
+}
28 42
 
29 43
 require_once '../../main.inc.php';
30 44
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/js/lib_gravatar.js.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -24,14 +24,14 @@
 block discarded – undo
24 24
 
25 25
 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');	// Not disabled cause need to load personalized language
26 26
 //if (! defined('NOREQUIREDB'))   define('NOREQUIREDB','1');
27
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
27
+if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', '1');
28 28
 //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');	// Not disabled cause need to do translations
29
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
30
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
31
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
32
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
33
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
34
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
29
+if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', 1);
30
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
31
+if (!defined('NOLOGIN'))         define('NOLOGIN', 1);
32
+if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
33
+if (!defined('NOREQUIREHTML'))   define('NOREQUIREHTML', 1);
34
+if (!defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX', '1');
35 35
 
36 36
 session_cache_limiter('public');
37 37
 
Please login to merge, or discard this patch.
Braces   +26 added lines, -9 removed lines patch added patch discarded remove patch
@@ -24,14 +24,28 @@  discard block
 block discarded – undo
24 24
 
25 25
 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');	// Not disabled cause need to load personalized language
26 26
 //if (! defined('NOREQUIREDB'))   define('NOREQUIREDB','1');
27
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
27
+if (! defined('NOREQUIRESOC')) {
28
+    define('NOREQUIRESOC','1');
29
+}
28 30
 //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');	// Not disabled cause need to do translations
29
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
30
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
31
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
32
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
33
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
34
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
31
+if (! defined('NOCSRFCHECK')) {
32
+    define('NOCSRFCHECK',1);
33
+}
34
+if (! defined('NOTOKENRENEWAL')) {
35
+    define('NOTOKENRENEWAL',1);
36
+}
37
+if (! defined('NOLOGIN')) {
38
+    define('NOLOGIN',1);
39
+}
40
+if (! defined('NOREQUIREMENU')) {
41
+    define('NOREQUIREMENU',1);
42
+}
43
+if (! defined('NOREQUIREHTML')) {
44
+    define('NOREQUIREHTML',1);
45
+}
46
+if (! defined('NOREQUIREAJAX')) {
47
+    define('NOREQUIREAJAX','1');
48
+}
35 49
 
36 50
 session_cache_limiter('public');
37 51
 
@@ -40,8 +54,11 @@  discard block
 block discarded – undo
40 54
 // Define javascript type
41 55
 top_httphead('text/javascript; charset=UTF-8');
42 56
 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
43
-if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate');
44
-else header('Cache-Control: no-cache');
57
+if (empty($dolibarr_nocache)) {
58
+    header('Cache-Control: max-age=10800, public, must-revalidate');
59
+} else {
60
+    header('Cache-Control: no-cache');
61
+}
45 62
 
46 63
 ?>
47 64
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/js/timepicker.js.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -21,13 +21,13 @@  discard block
 block discarded – undo
21 21
  * \brief      File that include javascript functions for timepicker
22 22
  */
23 23
 
24
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
25
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
26
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
27
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
28
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
29
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
30
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
24
+if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', '1');
25
+if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', 1);
26
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
27
+if (!defined('NOLOGIN'))         define('NOLOGIN', 1);
28
+if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
29
+if (!defined('NOREQUIREHTML'))   define('NOREQUIREHTML', 1);
30
+if (!defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX', '1');
31 31
 
32 32
 session_cache_limiter('public');
33 33
 
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 		timeFormat: 'HH:mm',
56 56
 		amNames: ['AM', 'A'],
57 57
 		pmNames: ['PM', 'P'],
58
-		isRTL: <?php echo ($langs->trans("DIRECTION")=='rtl'?'true':'false'); ?>
58
+		isRTL: <?php echo ($langs->trans("DIRECTION") == 'rtl' ? 'true' : 'false'); ?>
59 59
 	};
60 60
 	$.timepicker.setDefaults($.timepicker.regional['<?php echo $langs->defaultlang ?>']);
61 61
 });
Please login to merge, or discard this patch.
Braces   +29 added lines, -10 removed lines patch added patch discarded remove patch
@@ -21,13 +21,27 @@  discard block
 block discarded – undo
21 21
  * \brief      File that include javascript functions for timepicker
22 22
  */
23 23
 
24
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
25
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
26
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
27
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
28
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
29
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
30
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
24
+if (! defined('NOREQUIRESOC')) {
25
+    define('NOREQUIRESOC','1');
26
+}
27
+if (! defined('NOCSRFCHECK')) {
28
+    define('NOCSRFCHECK',1);
29
+}
30
+if (! defined('NOTOKENRENEWAL')) {
31
+    define('NOTOKENRENEWAL',1);
32
+}
33
+if (! defined('NOLOGIN')) {
34
+    define('NOLOGIN',1);
35
+}
36
+if (! defined('NOREQUIREMENU')) {
37
+    define('NOREQUIREMENU',1);
38
+}
39
+if (! defined('NOREQUIREHTML')) {
40
+    define('NOREQUIREHTML',1);
41
+}
42
+if (! defined('NOREQUIREAJAX')) {
43
+    define('NOREQUIREAJAX','1');
44
+}
31 45
 
32 46
 session_cache_limiter('public');
33 47
 
@@ -36,8 +50,11 @@  discard block
 block discarded – undo
36 50
 // Define javascript type
37 51
 top_httphead('text/javascript; charset=UTF-8');
38 52
 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
39
-if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate');
40
-else header('Cache-Control: no-cache');
53
+if (empty($dolibarr_nocache)) {
54
+    header('Cache-Control: max-age=10800, public, must-revalidate');
55
+} else {
56
+    header('Cache-Control: no-cache');
57
+}
41 58
 ?>
42 59
 
43 60
 // For JQuery Timepicker
@@ -61,4 +78,6 @@  discard block
 block discarded – undo
61 78
 });
62 79
 
63 80
 <?php
64
-if (is_object($db)) $db->close();
81
+if (is_object($db)) {
82
+    $db->close();
83
+}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_linkedfiles.inc.php 3 patches
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -29,41 +29,41 @@  discard block
 block discarded – undo
29 29
 // Submit file/link
30 30
 if (GETPOST('sendit','alpha') && ! empty($conf->global->MAIN_UPLOAD_DOC))
31 31
 {
32
-	if (! empty($_FILES))
33
-	{
34
-		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
-		else $userfiles=array($_FILES['userfile']['tmp_name']);
32
+    if (! empty($_FILES))
33
+    {
34
+        if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
+        else $userfiles=array($_FILES['userfile']['tmp_name']);
36 36
 
37
-		foreach($userfiles as $key => $userfile)
38
-		{
39
-			if (empty($_FILES['userfile']['tmp_name'][$key]))
40
-			{
41
-				$error++;
42
-				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
43
-					setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44
-				}
45
-				else {
46
-					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
47
-				}
48
-			}
49
-		}
37
+        foreach($userfiles as $key => $userfile)
38
+        {
39
+            if (empty($_FILES['userfile']['tmp_name'][$key]))
40
+            {
41
+                $error++;
42
+                if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
43
+                    setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44
+                }
45
+                else {
46
+                    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
47
+                }
48
+            }
49
+        }
50 50
 
51
-		if (! $error)
52
-		{
53
-			// Define if we have to generate thumbs or not
54
-			$generatethumbs = 1;
55
-			if (GETPOST('section_dir')) $generatethumbs=0;
51
+        if (! $error)
52
+        {
53
+            // Define if we have to generate thumbs or not
54
+            $generatethumbs = 1;
55
+            if (GETPOST('section_dir')) $generatethumbs=0;
56 56
 
57
-			if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58
-			{
59
-				$result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60
-			}
61
-			elseif (! empty($upload_dir))
62
-			{
63
-				$result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64
-			}
65
-		}
66
-	}
57
+            if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58
+            {
59
+                $result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60
+            }
61
+            elseif (! empty($upload_dir))
62
+            {
63
+                $result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64
+            }
65
+        }
66
+    }
67 67
 }
68 68
 elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
69 69
 {
@@ -84,39 +84,39 @@  discard block
 block discarded – undo
84 84
         $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);				// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
85 85
         if (GETPOST('section', 'alpha')) 	// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
86 86
         {
87
-        	$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
87
+            $file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
88 88
         }
89 89
         else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
90
-		{
91
-       		$urlfile=basename($urlfile);
92
-       		$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
-			if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
94
-		}
90
+        {
91
+                $urlfile=basename($urlfile);
92
+                $file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
+            if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
94
+        }
95 95
         $linkid = GETPOST('linkid', 'int');
96 96
 
97 97
         if ($urlfile)		// delete of a file
98 98
         {
99
-	        $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
100
-	        $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
99
+            $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
100
+            $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
101 101
 
102
-	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
102
+            $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
103 103
             if (! empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));     // Delete file using old path
104 104
 
105
-	        // Si elle existe, on efface la vignette
106
-	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
107
-	        {
108
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_small'.$regs[0]);
109
-		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
110
-		        {
111
-			        dol_delete_file($dirthumb.$photo_vignette);
112
-		        }
105
+            // Si elle existe, on efface la vignette
106
+            if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
107
+            {
108
+                $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_small'.$regs[0]);
109
+                if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
110
+                {
111
+                    dol_delete_file($dirthumb.$photo_vignette);
112
+                }
113 113
 
114
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_mini'.$regs[0]);
115
-		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
116
-		        {
117
-			        dol_delete_file($dirthumb.$photo_vignette);
118
-		        }
119
-	        }
114
+                $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_mini'.$regs[0]);
115
+                if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
116
+                {
117
+                    dol_delete_file($dirthumb.$photo_vignette);
118
+                }
119
+            }
120 120
 
121 121
             if ($ret) setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
122 122
             else setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
@@ -143,16 +143,16 @@  discard block
 block discarded – undo
143 143
 
144 144
         if (is_object($object) && $object->id > 0)
145 145
         {
146
-        	if ($backtopage)
147
-        	{
148
-        		header('Location: ' . $backtopage);
149
-        		exit;
150
-        	}
151
-        	else
152
-        	{
153
-        		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
154
-        		exit;
155
-        	}
146
+            if ($backtopage)
147
+            {
148
+                header('Location: ' . $backtopage);
149
+                exit;
150
+            }
151
+            else
152
+            {
153
+                header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
154
+                exit;
155
+            }
156 156
         }
157 157
 }
158 158
 elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
@@ -183,101 +183,101 @@  discard block
 block discarded – undo
183 183
 }
184 184
 elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
185 185
 {
186
-	// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187
-	if (! empty($upload_dir))
188
-	{
189
-		$filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0);	// Do not remove accents
190
-		$filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0);		// Do not remove accents
186
+    // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187
+    if (! empty($upload_dir))
188
+    {
189
+        $filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0);	// Do not remove accents
190
+        $filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0);		// Do not remove accents
191 191
 
192 192
         if ($filenamefrom != $filenameto)
193 193
         {
194
-	        // Security:
195
-	        // Disallow file with some extensions. We rename them.
196
-	        // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
197
-	        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
198
-	        {
199
-	            $filenameto.= '.noexe';
200
-	        }
194
+            // Security:
195
+            // Disallow file with some extensions. We rename them.
196
+            // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
197
+            if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
198
+            {
199
+                $filenameto.= '.noexe';
200
+            }
201 201
 
202
-	        if ($filenamefrom && $filenameto)
203
-	        {
204
-	            $srcpath = $upload_dir.'/'.$filenamefrom;
205
-	            $destpath = $upload_dir.'/'.$filenameto;
202
+            if ($filenamefrom && $filenameto)
203
+            {
204
+                $srcpath = $upload_dir.'/'.$filenamefrom;
205
+                $destpath = $upload_dir.'/'.$filenameto;
206 206
 
207
-	            $reshook=$hookmanager->initHooks(array('actionlinkedfiles'));
208
-	            $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
-	            $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
207
+                $reshook=$hookmanager->initHooks(array('actionlinkedfiles'));
208
+                $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
+                $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
210 210
 
211
-	            if (empty($reshook))
212
-	            {
213
-	            	if (! file_exists($destpath))
214
-	            	{
215
-	            		$result = dol_move($srcpath, $destpath);
216
-			            if ($result)
217
-			            {
218
-			            	// Define if we have to generate thumbs or not
219
-			            	$generatethumbs = 1;
220
-			            	// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221
-			            	// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222
-			            	// but when we rename from a tab "Documents", we must regenerate thumbs
223
-			            	if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
211
+                if (empty($reshook))
212
+                {
213
+                    if (! file_exists($destpath))
214
+                    {
215
+                        $result = dol_move($srcpath, $destpath);
216
+                        if ($result)
217
+                        {
218
+                            // Define if we have to generate thumbs or not
219
+                            $generatethumbs = 1;
220
+                            // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221
+                            // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222
+                            // but when we rename from a tab "Documents", we must regenerate thumbs
223
+                            if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
224 224
 
225
-			            	if ($generatethumbs)
226
-			            	{
227
-			            		if ($object->id)
228
-				            	{
229
-				                	$object->addThumbs($destpath);
230
-				            	}
225
+                            if ($generatethumbs)
226
+                            {
227
+                                if ($object->id)
228
+                                {
229
+                                    $object->addThumbs($destpath);
230
+                                }
231 231
 
232
-				                // TODO Add revert function of addThumbs to remove thumbs with old name
233
-				                //$object->delThumbs($srcpath);
234
-			            	}
232
+                                // TODO Add revert function of addThumbs to remove thumbs with old name
233
+                                //$object->delThumbs($srcpath);
234
+                            }
235 235
 
236
-			                setEventMessages($langs->trans("FileRenamed"), null);
237
-			            }
238
-			            else
239
-			            {
240
-			                $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
241
-			                setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
242
-			            }
243
-	            	}
244
-	            	else
245
-	            	{
246
-	            		$langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
247
-	            		setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
248
-	            	}
249
-	            }
250
-	        }
236
+                            setEventMessages($langs->trans("FileRenamed"), null);
237
+                        }
238
+                        else
239
+                        {
240
+                            $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
241
+                            setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
242
+                        }
243
+                    }
244
+                    else
245
+                    {
246
+                        $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
247
+                        setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
248
+                    }
249
+                }
250
+            }
251 251
         }
252 252
     }
253 253
 
254 254
     // Update properties in ECM table
255 255
     if (GETPOST('ecmfileid', 'int') > 0)
256 256
     {
257
-    	$shareenabled = GETPOST('shareenabled', 'alpha');
257
+        $shareenabled = GETPOST('shareenabled', 'alpha');
258 258
 
259
-    	include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
260
-	    $ecmfile=new EcmFiles($db);
261
-	    $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
262
-	    if ($result > 0)
263
-	    {
264
-	    	if ($shareenabled)
265
-		    {
266
-		    	if (empty($ecmfile->share))
267
-		    	{
268
-		    		require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
269
-		    		$ecmfile->share = getRandomPassword(true);
270
-		    	}
271
-		    }
272
-		    else
273
-		    {
274
-		    	$ecmfile->share = '';
275
-		    }
276
-		    $result = $ecmfile->update($user);
277
-		    if ($result < 0)
278
-		    {
279
-		    	setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
280
-		    }
281
-	    }
259
+        include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
260
+        $ecmfile=new EcmFiles($db);
261
+        $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
262
+        if ($result > 0)
263
+        {
264
+            if ($shareenabled)
265
+            {
266
+                if (empty($ecmfile->share))
267
+                {
268
+                    require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
269
+                    $ecmfile->share = getRandomPassword(true);
270
+                }
271
+            }
272
+            else
273
+            {
274
+                $ecmfile->share = '';
275
+            }
276
+            $result = $ecmfile->update($user);
277
+            if ($result < 0)
278
+            {
279
+                setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
280
+            }
281
+        }
282 282
     }
283 283
 }
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -27,19 +27,19 @@  discard block
 block discarded – undo
27 27
 
28 28
 
29 29
 // Submit file/link
30
-if (GETPOST('sendit','alpha') && ! empty($conf->global->MAIN_UPLOAD_DOC))
30
+if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC))
31 31
 {
32
-	if (! empty($_FILES))
32
+	if (!empty($_FILES))
33 33
 	{
34
-		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
-		else $userfiles=array($_FILES['userfile']['tmp_name']);
34
+		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name'];
35
+		else $userfiles = array($_FILES['userfile']['tmp_name']);
36 36
 
37
-		foreach($userfiles as $key => $userfile)
37
+		foreach ($userfiles as $key => $userfile)
38 38
 		{
39 39
 			if (empty($_FILES['userfile']['tmp_name'][$key]))
40 40
 			{
41 41
 				$error++;
42
-				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
42
+				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
43 43
 					setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44 44
 				}
45 45
 				else {
@@ -48,30 +48,30 @@  discard block
 block discarded – undo
48 48
 			}
49 49
 		}
50 50
 
51
-		if (! $error)
51
+		if (!$error)
52 52
 		{
53 53
 			// Define if we have to generate thumbs or not
54 54
 			$generatethumbs = 1;
55
-			if (GETPOST('section_dir')) $generatethumbs=0;
55
+			if (GETPOST('section_dir')) $generatethumbs = 0;
56 56
 
57
-			if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
57
+			if (!empty($upload_dirold) && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58 58
 			{
59 59
 				$result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60 60
 			}
61
-			elseif (! empty($upload_dir))
61
+			elseif (!empty($upload_dir))
62 62
 			{
63 63
 				$result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64 64
 			}
65 65
 		}
66 66
 	}
67 67
 }
68
-elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
68
+elseif (GETPOST('linkit', 'none') && !empty($conf->global->MAIN_UPLOAD_DOC))
69 69
 {
70 70
     $link = GETPOST('link', 'alpha');
71 71
     if ($link)
72 72
     {
73 73
         if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') {
74
-            $link = 'http://' . $link;
74
+            $link = 'http://'.$link;
75 75
         }
76 76
         dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link, '', 0);
77 77
     }
@@ -81,37 +81,37 @@  discard block
 block discarded – undo
81 81
 // Delete file/link
82 82
 if ($action == 'confirm_deletefile' && $confirm == 'yes')
83 83
 {
84
-        $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);				// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
84
+        $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
85 85
         if (GETPOST('section', 'alpha')) 	// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
86 86
         {
87
-        	$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
87
+        	$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
88 88
         }
89 89
         else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
90 90
 		{
91
-       		$urlfile=basename($urlfile);
92
-       		$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
-			if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
91
+       		$urlfile = basename($urlfile);
92
+       		$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
93
+			if (!empty($upload_dirold)) $fileold = $upload_dirold."/".$urlfile;
94 94
 		}
95 95
         $linkid = GETPOST('linkid', 'int');
96 96
 
97 97
         if ($urlfile)		// delete of a file
98 98
         {
99
-	        $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
100
-	        $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
99
+	        $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
100
+	        $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
101 101
 
102
-	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
103
-            if (! empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));     // Delete file using old path
102
+	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
103
+            if (!empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
104 104
 
105 105
 	        // Si elle existe, on efface la vignette
106
-	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
106
+	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs))
107 107
 	        {
108
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_small'.$regs[0]);
108
+		        $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
109 109
 		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
110 110
 		        {
111 111
 			        dol_delete_file($dirthumb.$photo_vignette);
112 112
 		        }
113 113
 
114
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_mini'.$regs[0]);
114
+		        $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
115 115
 		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
116 116
 		        {
117 117
 			        dol_delete_file($dirthumb.$photo_vignette);
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
         }
124 124
         elseif ($linkid)	// delete of external link
125 125
         {
126
-            require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
126
+            require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
127 127
             $link = new Link($db);
128 128
             $link->id = $linkid;
129 129
             $link->fetch();
@@ -145,19 +145,19 @@  discard block
 block discarded – undo
145 145
         {
146 146
         	if ($backtopage)
147 147
         	{
148
-        		header('Location: ' . $backtopage);
148
+        		header('Location: '.$backtopage);
149 149
         		exit;
150 150
         	}
151 151
         	else
152 152
         	{
153
-        		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
153
+        		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : ''));
154 154
         		exit;
155 155
         	}
156 156
         }
157 157
 }
158
-elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
158
+elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
159 159
 {
160
-    require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
160
+    require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
161 161
     $langs->load('link');
162 162
     $link = new Link($db);
163 163
     $link->id = GETPOST('linkid', 'int');
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
         $link->url = GETPOST('link', 'alpha');
168 168
         if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://')
169 169
         {
170
-            $link->url = 'http://' . $link->url;
170
+            $link->url = 'http://'.$link->url;
171 171
         }
172 172
         $link->label = GETPOST('label', 'alpha');
173 173
         $res = $link->update($user);
@@ -181,22 +181,22 @@  discard block
 block discarded – undo
181 181
         //error fetching
182 182
     }
183 183
 }
184
-elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
184
+elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))
185 185
 {
186 186
 	// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187
-	if (! empty($upload_dir))
187
+	if (!empty($upload_dir))
188 188
 	{
189
-		$filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0);	// Do not remove accents
190
-		$filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0);		// Do not remove accents
189
+		$filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
190
+		$filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
191 191
 
192 192
         if ($filenamefrom != $filenameto)
193 193
         {
194 194
 	        // Security:
195 195
 	        // Disallow file with some extensions. We rename them.
196 196
 	        // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
197
-	        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
197
+	        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i', $filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
198 198
 	        {
199
-	            $filenameto.= '.noexe';
199
+	            $filenameto .= '.noexe';
200 200
 	        }
201 201
 
202 202
 	        if ($filenamefrom && $filenameto)
@@ -204,13 +204,13 @@  discard block
 block discarded – undo
204 204
 	            $srcpath = $upload_dir.'/'.$filenamefrom;
205 205
 	            $destpath = $upload_dir.'/'.$filenameto;
206 206
 
207
-	            $reshook=$hookmanager->initHooks(array('actionlinkedfiles'));
208
-	            $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
-	            $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
207
+	            $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
208
+	            $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
+	            $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
210 210
 
211 211
 	            if (empty($reshook))
212 212
 	            {
213
-	            	if (! file_exists($destpath))
213
+	            	if (!file_exists($destpath))
214 214
 	            	{
215 215
 	            		$result = dol_move($srcpath, $destpath);
216 216
 			            if ($result)
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 			            	// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221 221
 			            	// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222 222
 			            	// but when we rename from a tab "Documents", we must regenerate thumbs
223
-			            	if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
223
+			            	if (GETPOST('modulepart') == 'medias') $generatethumbs = 0;
224 224
 
225 225
 			            	if ($generatethumbs)
226 226
 			            	{
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
     	$shareenabled = GETPOST('shareenabled', 'alpha');
258 258
 
259 259
     	include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
260
-	    $ecmfile=new EcmFiles($db);
260
+	    $ecmfile = new EcmFiles($db);
261 261
 	    $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
262 262
 	    if ($result > 0)
263 263
 	    {
Please login to merge, or discard this patch.
Braces   +44 added lines, -34 removed lines patch added patch discarded remove patch
@@ -31,8 +31,11 @@  discard block
 block discarded – undo
31 31
 {
32 32
 	if (! empty($_FILES))
33 33
 	{
34
-		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
-		else $userfiles=array($_FILES['userfile']['tmp_name']);
34
+		if (is_array($_FILES['userfile']['tmp_name'])) {
35
+		    $userfiles=$_FILES['userfile']['tmp_name'];
36
+		} else {
37
+		    $userfiles=array($_FILES['userfile']['tmp_name']);
38
+		}
36 39
 
37 40
 		foreach($userfiles as $key => $userfile)
38 41
 		{
@@ -41,8 +44,7 @@  discard block
 block discarded – undo
41 44
 				$error++;
42 45
 				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
43 46
 					setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44
-				}
45
-				else {
47
+				} else {
46 48
 					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
47 49
 				}
48 50
 			}
@@ -52,20 +54,20 @@  discard block
 block discarded – undo
52 54
 		{
53 55
 			// Define if we have to generate thumbs or not
54 56
 			$generatethumbs = 1;
55
-			if (GETPOST('section_dir')) $generatethumbs=0;
57
+			if (GETPOST('section_dir')) {
58
+			    $generatethumbs=0;
59
+			}
56 60
 
57 61
 			if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58 62
 			{
59 63
 				$result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60
-			}
61
-			elseif (! empty($upload_dir))
64
+			} elseif (! empty($upload_dir))
62 65
 			{
63 66
 				$result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64 67
 			}
65 68
 		}
66 69
 	}
67
-}
68
-elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
70
+} elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
69 71
 {
70 72
     $link = GETPOST('link', 'alpha');
71 73
     if ($link)
@@ -82,25 +84,34 @@  discard block
 block discarded – undo
82 84
 if ($action == 'confirm_deletefile' && $confirm == 'yes')
83 85
 {
84 86
         $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);				// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
85
-        if (GETPOST('section', 'alpha')) 	// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
87
+        if (GETPOST('section', 'alpha')) {
88
+            // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
86 89
         {
87 90
         	$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
88 91
         }
89
-        else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
92
+        } else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
90 93
 		{
91 94
        		$urlfile=basename($urlfile);
92 95
        		$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
-			if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
96
+			if (! empty($upload_dirold)) {
97
+			    $fileold = $upload_dirold . "/" . $urlfile;
98
+			}
94 99
 		}
95 100
         $linkid = GETPOST('linkid', 'int');
96 101
 
97
-        if ($urlfile)		// delete of a file
102
+        if ($urlfile) {
103
+            // delete of a file
98 104
         {
99
-	        $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
105
+	        $dir = dirname($file).'/';
106
+        }
107
+        // Chemin du dossier contenant l'image d'origine
100 108
 	        $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
101 109
 
102 110
 	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
103
-            if (! empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));     // Delete file using old path
111
+            if (! empty($fileold)) {
112
+                dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));
113
+            }
114
+            // Delete file using old path
104 115
 
105 116
 	        // Si elle existe, on efface la vignette
106 117
 	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
@@ -118,12 +129,16 @@  discard block
 block discarded – undo
118 129
 		        }
119 130
 	        }
120 131
 
121
-            if ($ret) setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
122
-            else setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
123
-        }
124
-        elseif ($linkid)	// delete of external link
132
+            if ($ret) {
133
+                setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
134
+            } else {
135
+                setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
136
+            }
137
+        } elseif ($linkid) {
138
+            // delete of external link
125 139
         {
126 140
             require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
141
+        }
127 142
             $link = new Link($db);
128 143
             $link->id = $linkid;
129 144
             $link->fetch();
@@ -147,15 +162,13 @@  discard block
 block discarded – undo
147 162
         	{
148 163
         		header('Location: ' . $backtopage);
149 164
         		exit;
150
-        	}
151
-        	else
165
+        	} else
152 166
         	{
153 167
         		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
154 168
         		exit;
155 169
         	}
156 170
         }
157
-}
158
-elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
171
+} elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
159 172
 {
160 173
     require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
161 174
     $langs->load('link');
@@ -175,13 +188,11 @@  discard block
 block discarded – undo
175 188
         {
176 189
             setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
177 190
         }
178
-    }
179
-    else
191
+    } else
180 192
     {
181 193
         //error fetching
182 194
     }
183
-}
184
-elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
195
+} elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
185 196
 {
186 197
 	// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187 198
 	if (! empty($upload_dir))
@@ -220,7 +231,9 @@  discard block
 block discarded – undo
220 231
 			            	// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221 232
 			            	// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222 233
 			            	// but when we rename from a tab "Documents", we must regenerate thumbs
223
-			            	if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
234
+			            	if (GETPOST('modulepart') == 'medias') {
235
+			            	    $generatethumbs=0;
236
+			            	}
224 237
 
225 238
 			            	if ($generatethumbs)
226 239
 			            	{
@@ -234,14 +247,12 @@  discard block
 block discarded – undo
234 247
 			            	}
235 248
 
236 249
 			                setEventMessages($langs->trans("FileRenamed"), null);
237
-			            }
238
-			            else
250
+			            } else
239 251
 			            {
240 252
 			                $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
241 253
 			                setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
242 254
 			            }
243
-	            	}
244
-	            	else
255
+	            	} else
245 256
 	            	{
246 257
 	            		$langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
247 258
 	            		setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
@@ -268,8 +279,7 @@  discard block
 block discarded – undo
268 279
 		    		require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
269 280
 		    		$ecmfile->share = getRandomPassword(true);
270 281
 		    	}
271
-		    }
272
-		    else
282
+		    } else
273 283
 		    {
274 284
 		    	$ecmfile->share = '';
275 285
 		    }
Please login to merge, or discard this patch.