Passed
Push — master ( 49af33...3cffbe )
by Alxarafe
21:21
created
dolibarr/htdocs/core/class/dolreceiptprinter.class.php 2 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -545,8 +545,7 @@
 block discarded – undo
545 545
         $ret = $this->InitPrinter($printerid);
546 546
         if ($ret>0) {
547 547
             setEventMessages($this->error, $this->errors, 'errors');
548
-        }
549
-        else
548
+        } else
550 549
         {
551 550
             $nboflines = count($vals);
552 551
             for ($line=0; $line < $nboflines; $line++)
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
  *
93 93
  */
94 94
 
95
-require_once DOL_DOCUMENT_ROOT .'/includes/mike42/escpos-php/Escpos.php';
95
+require_once DOL_DOCUMENT_ROOT.'/includes/mike42/escpos-php/Escpos.php';
96 96
 
97 97
 
98 98
 /**
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     /**
119 119
      * @var string Error code (or message)
120 120
      */
121
-    public $error='';
121
+    public $error = '';
122 122
 
123 123
     /**
124 124
      * @var string[] Error codes (or messages)
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
      */
135 135
     function __construct($db)
136 136
     {
137
-        $this->db=$db;
137
+        $this->db = $db;
138 138
         $this->tags = array(
139 139
             'dol_align_left',
140 140
             'dol_align_center',
@@ -218,8 +218,8 @@  discard block
 block discarded – undo
218 218
         $line = 0;
219 219
         $obj = array();
220 220
         $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter';
221
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
222
-        $sql.= ' WHERE entity = '.$conf->entity;
221
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
222
+        $sql .= ' WHERE entity = '.$conf->entity;
223 223
         $resql = $this->db->query($sql);
224 224
         if ($resql) {
225 225
             $num = $this->db->num_rows($resql);
@@ -286,8 +286,8 @@  discard block
 block discarded – undo
286 286
         $line = 0;
287 287
         $obj = array();
288 288
         $sql = 'SELECT rowid, name, template';
289
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
290
-        $sql.= ' WHERE entity = '.$conf->entity;
289
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
290
+        $sql .= ' WHERE entity = '.$conf->entity;
291 291
         $resql = $this->db->query($sql);
292 292
         if ($resql) {
293 293
             $num = $this->db->num_rows($resql);
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
      *  @param    string    $htmlname       select html name
312 312
      *  @return  int                        0 if OK; >0 if KO
313 313
      */
314
-    function selectTypePrinter($selected='', $htmlname='printertypeid')
314
+    function selectTypePrinter($selected = '', $htmlname = 'printertypeid')
315 315
     {
316 316
         global $langs;
317 317
 
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
      *  @param    string    $htmlname       select html name
336 336
      *  @return  int                        0 if OK; >0 if KO
337 337
      */
338
-    function selectProfilePrinter($selected='', $htmlname='printerprofileid')
338
+    function selectProfilePrinter($selected = '', $htmlname = 'printerprofileid')
339 339
     {
340 340
         global $langs;
341 341
 
@@ -368,10 +368,10 @@  discard block
 block discarded – undo
368 368
         global $conf;
369 369
         $error = 0;
370 370
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt';
371
-        $sql.= ' (name, fk_type, fk_profile, parameter, entity)';
372
-        $sql.= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')';
371
+        $sql .= ' (name, fk_type, fk_profile, parameter, entity)';
372
+        $sql .= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')';
373 373
         $resql = $this->db->query($sql);
374
-        if (! $resql) {
374
+        if (!$resql) {
375 375
             $error++;
376 376
             $this->errors[] = $this->db->lasterror;
377 377
         }
@@ -395,13 +395,13 @@  discard block
 block discarded – undo
395 395
         global $conf;
396 396
         $error = 0;
397 397
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt';
398
-        $sql.= ' SET name="'.$this->db->escape($name).'"';
399
-        $sql.= ', fk_type='.$type;
400
-        $sql.= ', fk_profile='.$profile;
401
-        $sql.= ', parameter="'.$this->db->escape($parameter).'"';
402
-        $sql.= ' WHERE rowid='.$printerid;
398
+        $sql .= ' SET name="'.$this->db->escape($name).'"';
399
+        $sql .= ', fk_type='.$type;
400
+        $sql .= ', fk_profile='.$profile;
401
+        $sql .= ', parameter="'.$this->db->escape($parameter).'"';
402
+        $sql .= ' WHERE rowid='.$printerid;
403 403
         $resql = $this->db->query($sql);
404
-        if (! $resql) {
404
+        if (!$resql) {
405 405
             $error++;
406 406
             $this->errors[] = $this->db->lasterror;
407 407
         }
@@ -421,9 +421,9 @@  discard block
 block discarded – undo
421 421
         global $conf;
422 422
         $error = 0;
423 423
         $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt';
424
-        $sql.= ' WHERE rowid='.$printerid;
424
+        $sql .= ' WHERE rowid='.$printerid;
425 425
         $resql = $this->db->query($sql);
426
-        if (! $resql) {
426
+        if (!$resql) {
427 427
             $error++;
428 428
             $this->errors[] = $this->db->lasterror;
429 429
         }
@@ -445,11 +445,11 @@  discard block
 block discarded – undo
445 445
         global $conf;
446 446
         $error = 0;
447 447
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt_template';
448
-        $sql.= ' SET name="'.$this->db->escape($name).'"';
449
-        $sql.= ', template="'.$this->db->escape($template).'"';
450
-        $sql.= ' WHERE rowid='.$templateid;
448
+        $sql .= ' SET name="'.$this->db->escape($name).'"';
449
+        $sql .= ', template="'.$this->db->escape($template).'"';
450
+        $sql .= ' WHERE rowid='.$templateid;
451 451
         $resql = $this->db->query($sql);
452
-        if (! $resql) {
452
+        if (!$resql) {
453 453
             $error++;
454 454
             $this->errors[] = $this->db->lasterror;
455 455
         }
@@ -469,9 +469,9 @@  discard block
 block discarded – undo
469 469
         // phpcs:enable
470 470
         global $conf;
471 471
         $error = 0;
472
-        $img = new EscposImage(DOL_BASE_URI . '/theme/common/dolibarr_logo_bw.png');
472
+        $img = new EscposImage(DOL_BASE_URI.'/theme/common/dolibarr_logo_bw.png');
473 473
         $ret = $this->InitPrinter($printerid);
474
-        if ($ret>0) {
474
+        if ($ret > 0) {
475 475
             setEventMessages($this->error, $this->errors, 'errors');
476 476
         } else {
477 477
             try {
@@ -543,35 +543,35 @@  discard block
 block discarded – undo
543 543
         $level = 0;
544 544
         $html = '<table border="1" style="width:210px"><pre>';
545 545
         $ret = $this->InitPrinter($printerid);
546
-        if ($ret>0) {
546
+        if ($ret > 0) {
547 547
             setEventMessages($this->error, $this->errors, 'errors');
548 548
         }
549 549
         else
550 550
         {
551 551
             $nboflines = count($vals);
552
-            for ($line=0; $line < $nboflines; $line++)
552
+            for ($line = 0; $line < $nboflines; $line++)
553 553
             {
554 554
                 switch ($vals[$line]['tag']) {
555 555
                     case 'DOL_ALIGN_CENTER':
556 556
                         $this->printer->setJustification(Escpos::JUSTIFY_CENTER);
557
-                        $html.='<center>';
557
+                        $html .= '<center>';
558 558
                         $this->printer->text($vals[$line]['value']);
559 559
                         break;
560 560
                     case 'DOL_ALIGN_RIGHT':
561 561
                         $this->printer->setJustification(Escpos::JUSTIFY_RIGHT);
562
-                        $html.='<right>';
562
+                        $html .= '<right>';
563 563
                         break;
564 564
                     case 'DOL_ALIGN_LEFT':
565 565
                         $this->printer->setJustification(Escpos::JUSTIFY_LEFT);
566
-                        $html.='<left>';
566
+                        $html .= '<left>';
567 567
                         break;
568 568
                     case 'DOL_OPEN_DRAWER':
569 569
                         $this->printer->pulse();
570
-                        $html.= ' &#991;'.nl2br($vals[$line]['value']);
570
+                        $html .= ' &#991;'.nl2br($vals[$line]['value']);
571 571
                         break;
572 572
                     case 'DOL_ACTIVATE_BUZZER':
573 573
                         //$this->printer->buzzer();
574
-                        $html.= ' &#x266b;'.nl2br($vals[$line]['value']);
574
+                        $html .= ' &#x266b;'.nl2br($vals[$line]['value']);
575 575
                         break;
576 576
                     case 'DOL_PRINT_BARCODE':
577 577
                         // $vals[$line]['value'] -> barcode($content, $type)
@@ -584,15 +584,15 @@  discard block
 block discarded – undo
584 584
                     case 'DOL_PRINT_QRCODE':
585 585
                         // $vals[$line]['value'] -> qrCode($content, $ec, $size, $model)
586 586
                         $this->printer->qrcode($vals[$line]['value']);
587
-                        $html.='QRCODE: '.$vals[$line]['value'];
587
+                        $html .= 'QRCODE: '.$vals[$line]['value'];
588 588
                         break;
589 589
                     case 'DOL_CUT_PAPER_FULL':
590 590
                         $this->printer->cut(Escpos::CUT_FULL);
591
-                        $html.= ' &#9986;'.nl2br($vals[$line]['value']);
591
+                        $html .= ' &#9986;'.nl2br($vals[$line]['value']);
592 592
                         break;
593 593
                     case 'DOL_CUT_PAPER_PARTIAL':
594 594
                         $this->printer->cut(Escpos::CUT_PARTIAL);
595
-                        $html.= ' &#9986;'.nl2br($vals[$line]['value']);
595
+                        $html .= ' &#9986;'.nl2br($vals[$line]['value']);
596 596
                         break;
597 597
                     case 'DOL_USE_FONT_A':
598 598
                         $this->printer->setFont(Escpos::FONT_A);
@@ -608,13 +608,13 @@  discard block
 block discarded – undo
608 608
                         break;
609 609
                     default:
610 610
                         $this->printer->text($vals[$line]['value']);
611
-                        $html.= nl2br($vals[$line]['value']);
611
+                        $html .= nl2br($vals[$line]['value']);
612 612
                         $this->errors[] = 'UnknowTag: &lt;'.strtolower($vals[$line]['tag']).'&gt;';
613 613
                         $error++;
614 614
                         break;
615 615
                 }
616 616
             }
617
-            $html.= '</pre></table>';
617
+            $html .= '</pre></table>';
618 618
             print $html;
619 619
             // Close and print
620 620
             // uncomment next line to see content sent to printer
@@ -635,9 +635,9 @@  discard block
 block discarded – undo
635 635
         global $conf;
636 636
         $error = 0;
637 637
         $sql = 'SELECT template';
638
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
639
-        $sql.= ' WHERE rowid='.$templateid;
640
-        $sql.= ' AND entity = '.$conf->entity;
638
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
639
+        $sql .= ' WHERE rowid='.$templateid;
640
+        $sql .= ' AND entity = '.$conf->entity;
641 641
         $resql = $this->db->query($sql);
642 642
         if ($resql) {
643 643
             $obj = $this->db->fetch_array($resql);
@@ -667,11 +667,11 @@  discard block
 block discarded – undo
667 667
     {
668 668
         // phpcs:enable
669 669
         global $conf;
670
-        $error=0;
670
+        $error = 0;
671 671
         $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter';
672
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
673
-        $sql.= ' WHERE rowid = '.$printerid;
674
-        $sql.= ' AND entity = '.$conf->entity;
672
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
673
+        $sql .= ' WHERE rowid = '.$printerid;
674
+        $sql .= ' AND entity = '.$conf->entity;
675 675
         $resql = $this->db->query($sql);
676 676
         if ($resql) {
677 677
             $obj = $this->db->fetch_array($resql);
@@ -683,12 +683,12 @@  discard block
 block discarded – undo
683 683
             $error++;
684 684
             $this->errors[] = 'PrinterDontExist';
685 685
         }
686
-        if (! $error) {
686
+        if (!$error) {
687 687
             $parameter = $obj['parameter'];
688 688
             try {
689 689
                 switch ($obj['fk_type']) {
690 690
                     case 1:
691
-                        require_once DOL_DOCUMENT_ROOT .'/includes/mike42/escpos-php/src/DummyPrintConnector.php';
691
+                        require_once DOL_DOCUMENT_ROOT.'/includes/mike42/escpos-php/src/DummyPrintConnector.php';
692 692
                         $this->connector = new DummyPrintConnector();
693 693
                         break;
694 694
                     case 2:
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/smtps.class.php 3 patches
Indentation   +1668 added lines, -1668 removed lines patch added patch discarded remove patch
@@ -45,188 +45,188 @@  discard block
 block discarded – undo
45 45
  */
46 46
 class SMTPs
47 47
 {
48
-	/**
49
-	 * Host Name or IP of SMTP Server to use
50
-	 */
51
-	var $_smtpsHost = 'localhost';
52
-
53
-	/**
54
-	 * SMTP Server Port definition. 25 is default value
55
-	 * This can be defined via a INI file or via a setter method
56
-	 */
57
-	var $_smtpsPort = '25';
58
-
59
-	/**
60
-	 * Secure SMTP Server access ID
61
-	 * This can be defined via a INI file or via a setter method
62
-	 */
63
-	var $_smtpsID = null;
64
-
65
-	/**
66
-	 * Secure SMTP Server access Password
67
-	 * This can be defined via a INI file or via a setter method
68
-	 */
69
-	var $_smtpsPW = null;
70
-
71
-	/**
72
-	 * Who sent the Message
73
-	 * This can be defined via a INI file or via a setter method
74
-	 */
75
-	var $_msgFrom = null;
76
-
77
-	/**
78
-	 * Where are replies and errors to be sent to
79
-	 * This can be defined via a INI file or via a setter method
80
-	 */
81
-	var $_msgReplyTo = null;
82
-
83
-	/**
84
-	 * Who will the Message be sent to; TO, CC, BCC
85
-	 * Multi-diminsional array containg addresses the message will
86
-	 * be sent TO, CC or BCC
87
-	 */
88
-	var $_msgRecipients = null;
89
-
90
-	/**
91
-	 * Message Subject
92
-	 */
93
-	var $_msgSubject = null;
94
-
95
-	/**
96
-	 * Message Content
97
-	 */
98
-	var $_msgContent = null;
99
-
100
-	/**
101
-	 * Custom X-Headers
102
-	 */
103
-	var $_msgXheader = null;
104
-
105
-	/**
106
-	 * Character set
107
-	 * Defaulted to 'iso-8859-1'
108
-	 */
109
-	var $_smtpsCharSet = 'iso-8859-1';
110
-
111
-	/**
112
-	 * Message Sensitivity
113
-	 * Defaults to ZERO - None
114
-	 */
115
-	var $_msgSensitivity = 0;
116
-
117
-	/**
118
-	 * Message Sensitivity
119
-	 */
120
-	var $_arySensitivity = array ( false,
121
-                                  'Personal',
122
-                                  'Private',
123
-                                  'Company Confidential' );
124
-
125
-	/**
126
-	 * Message Sensitivity
127
-	 * Defaults to 3 - Normal
128
-	 */
129
-	var $_msgPriority = 3;
130
-
131
-	/**
132
-	 * Message Priority
133
-	 */
134
-	var $_aryPriority = array ( 'Bulk',
48
+    /**
49
+     * Host Name or IP of SMTP Server to use
50
+     */
51
+    var $_smtpsHost = 'localhost';
52
+
53
+    /**
54
+     * SMTP Server Port definition. 25 is default value
55
+     * This can be defined via a INI file or via a setter method
56
+     */
57
+    var $_smtpsPort = '25';
58
+
59
+    /**
60
+     * Secure SMTP Server access ID
61
+     * This can be defined via a INI file or via a setter method
62
+     */
63
+    var $_smtpsID = null;
64
+
65
+    /**
66
+     * Secure SMTP Server access Password
67
+     * This can be defined via a INI file or via a setter method
68
+     */
69
+    var $_smtpsPW = null;
70
+
71
+    /**
72
+     * Who sent the Message
73
+     * This can be defined via a INI file or via a setter method
74
+     */
75
+    var $_msgFrom = null;
76
+
77
+    /**
78
+     * Where are replies and errors to be sent to
79
+     * This can be defined via a INI file or via a setter method
80
+     */
81
+    var $_msgReplyTo = null;
82
+
83
+    /**
84
+     * Who will the Message be sent to; TO, CC, BCC
85
+     * Multi-diminsional array containg addresses the message will
86
+     * be sent TO, CC or BCC
87
+     */
88
+    var $_msgRecipients = null;
89
+
90
+    /**
91
+     * Message Subject
92
+     */
93
+    var $_msgSubject = null;
94
+
95
+    /**
96
+     * Message Content
97
+     */
98
+    var $_msgContent = null;
99
+
100
+    /**
101
+     * Custom X-Headers
102
+     */
103
+    var $_msgXheader = null;
104
+
105
+    /**
106
+     * Character set
107
+     * Defaulted to 'iso-8859-1'
108
+     */
109
+    var $_smtpsCharSet = 'iso-8859-1';
110
+
111
+    /**
112
+     * Message Sensitivity
113
+     * Defaults to ZERO - None
114
+     */
115
+    var $_msgSensitivity = 0;
116
+
117
+    /**
118
+     * Message Sensitivity
119
+     */
120
+    var $_arySensitivity = array ( false,
121
+                                    'Personal',
122
+                                    'Private',
123
+                                    'Company Confidential' );
124
+
125
+    /**
126
+     * Message Sensitivity
127
+     * Defaults to 3 - Normal
128
+     */
129
+    var $_msgPriority = 3;
130
+
131
+    /**
132
+     * Message Priority
133
+     */
134
+    var $_aryPriority = array ( 'Bulk',
135 135
                                 'Highest',
136 136
                                 'High',
137 137
                                 'Normal',
138 138
                                 'Low',
139 139
                                 'Lowest' );
140 140
 
141
-	/**
142
-	 * Content-Transfer-Encoding
143
-	 * Defaulted to 0 - 7bit
144
-	 */
145
-	var $_smtpsTransEncodeType = 0;
146
-
147
-	/**
148
-	 * Content-Transfer-Encoding
149
-	 */
150
-	var $_smtpsTransEncodeTypes = array( '7bit',               // Simple 7-bit ASCII
151
-                                         '8bit',               // 8-bit coding with line termination characters
152
-                                         'base64',             // 3 octets encoded into 4 sextets with offset
153
-                                         'binary',             // Arbitrary binary stream
154
-                                         'mac-binhex40',       // Macintosh binary to hex encoding
155
-                                         'quoted-printable',   // Mostly 7-bit, with 8-bit characters encoded as "=HH"
156
-                                         'uuencode' );         // UUENCODE encoding
157
-
158
-	/**
159
-	 * Content-Transfer-Encoding
160
-	 * Defaulted to '7bit'
161
-	 */
162
-	var $_smtpsTransEncode = '7bit';
163
-
164
-	/**
165
-	 * Boundary String for MIME seperation
166
-	 */
167
-	var $_smtpsBoundary = null;
168
-
169
-	/**
170
-	 * Related Boundary
171
-	 */
172
-	var $_smtpsRelatedBoundary = null;
173
-
174
-	/**
175
-	 * Alternative Boundary
176
-	 */
177
-	var $_smtpsAlternativeBoundary = null;
178
-
179
-	/**
180
-	 * Determines the method inwhich the message are to be sent.
181
-	 * - 'sockets' [0] - conect via network to SMTP server - default
182
-	 * - 'pipe     [1] - use UNIX path to EXE
183
-	 * - 'phpmail  [2] - use the PHP built-in mail function
184
-	 * NOTE: Only 'sockets' is implemented
185
-	 */
186
-	var $_transportType = 0;
187
-
188
-	/**
189
-	 * If '$_transportType' is set to '1', then this variable is used
190
-	 * to define the UNIX file system path to the sendmail execuable
191
-	 */
192
-	var $_mailPath = '/usr/lib/sendmail';
193
-
194
-	/**
195
-	 * Sets the SMTP server timeout in seconds.
196
-	 */
197
-	var $_smtpTimeout = 10;
198
-
199
-	/**
200
-	 * Determines whether to calculate message MD5 checksum.
201
-	 */
202
-	var $_smtpMD5 = false;
203
-
204
-	/**
205
-	 * Class error codes and messages
206
-	 */
207
-	var $_smtpsErrors = null;
208
-
209
-	/**
210
-	 * Defines log level
211
-	 *  0 - no logging
212
-	 *  1 - connectivity logging
213
-	 *  2 - message generation logging
214
-	 *  3 - detail logging
215
-	 */
216
-	var $_log_level = 0;
217
-
218
-	/**
219
-	 * Place Class in" debug" mode
220
-	 */
221
-	var $_debug = false;
222
-
223
-
224
-	// @CHANGE LDR
225
-	var $log = '';
226
-	var $_errorsTo = '';
227
-	var $_deliveryReceipt = 0;
228
-	var $_trackId = '';
229
-	var $_moreInHeader = '';
141
+    /**
142
+     * Content-Transfer-Encoding
143
+     * Defaulted to 0 - 7bit
144
+     */
145
+    var $_smtpsTransEncodeType = 0;
146
+
147
+    /**
148
+     * Content-Transfer-Encoding
149
+     */
150
+    var $_smtpsTransEncodeTypes = array( '7bit',               // Simple 7-bit ASCII
151
+                                            '8bit',               // 8-bit coding with line termination characters
152
+                                            'base64',             // 3 octets encoded into 4 sextets with offset
153
+                                            'binary',             // Arbitrary binary stream
154
+                                            'mac-binhex40',       // Macintosh binary to hex encoding
155
+                                            'quoted-printable',   // Mostly 7-bit, with 8-bit characters encoded as "=HH"
156
+                                            'uuencode' );         // UUENCODE encoding
157
+
158
+    /**
159
+     * Content-Transfer-Encoding
160
+     * Defaulted to '7bit'
161
+     */
162
+    var $_smtpsTransEncode = '7bit';
163
+
164
+    /**
165
+     * Boundary String for MIME seperation
166
+     */
167
+    var $_smtpsBoundary = null;
168
+
169
+    /**
170
+     * Related Boundary
171
+     */
172
+    var $_smtpsRelatedBoundary = null;
173
+
174
+    /**
175
+     * Alternative Boundary
176
+     */
177
+    var $_smtpsAlternativeBoundary = null;
178
+
179
+    /**
180
+     * Determines the method inwhich the message are to be sent.
181
+     * - 'sockets' [0] - conect via network to SMTP server - default
182
+     * - 'pipe     [1] - use UNIX path to EXE
183
+     * - 'phpmail  [2] - use the PHP built-in mail function
184
+     * NOTE: Only 'sockets' is implemented
185
+     */
186
+    var $_transportType = 0;
187
+
188
+    /**
189
+     * If '$_transportType' is set to '1', then this variable is used
190
+     * to define the UNIX file system path to the sendmail execuable
191
+     */
192
+    var $_mailPath = '/usr/lib/sendmail';
193
+
194
+    /**
195
+     * Sets the SMTP server timeout in seconds.
196
+     */
197
+    var $_smtpTimeout = 10;
198
+
199
+    /**
200
+     * Determines whether to calculate message MD5 checksum.
201
+     */
202
+    var $_smtpMD5 = false;
203
+
204
+    /**
205
+     * Class error codes and messages
206
+     */
207
+    var $_smtpsErrors = null;
208
+
209
+    /**
210
+     * Defines log level
211
+     *  0 - no logging
212
+     *  1 - connectivity logging
213
+     *  2 - message generation logging
214
+     *  3 - detail logging
215
+     */
216
+    var $_log_level = 0;
217
+
218
+    /**
219
+     * Place Class in" debug" mode
220
+     */
221
+    var $_debug = false;
222
+
223
+
224
+    // @CHANGE LDR
225
+    var $log = '';
226
+    var $_errorsTo = '';
227
+    var $_deliveryReceipt = 0;
228
+    var $_trackId = '';
229
+    var $_moreInHeader = '';
230 230
 
231 231
 
232 232
     /**
@@ -235,20 +235,20 @@  discard block
 block discarded – undo
235 235
      * @param	int		$_val		Value
236 236
      * @return	void
237 237
      */
238
-	function setDeliveryReceipt($_val = 0)
239
-	{
240
-		$this->_deliveryReceipt = $_val;
241
-	}
238
+    function setDeliveryReceipt($_val = 0)
239
+    {
240
+        $this->_deliveryReceipt = $_val;
241
+    }
242 242
 
243 243
     /**
244 244
      * get delivery receipt
245 245
      *
246 246
      * @return	int		Delivery receipt
247 247
      */
248
-	function getDeliveryReceipt()
249
-	{
250
-		return $this->_deliveryReceipt;
251
-	}
248
+    function getDeliveryReceipt()
249
+    {
250
+        return $this->_deliveryReceipt;
251
+    }
252 252
 
253 253
     /**
254 254
      * Set trackid
@@ -256,10 +256,10 @@  discard block
 block discarded – undo
256 256
      * @param	string		$_val		Value
257 257
      * @return	void
258 258
      */
259
-	function setTrackId($_val = '')
260
-	{
261
-		$this->_trackId = $_val;
262
-	}
259
+    function setTrackId($_val = '')
260
+    {
261
+        $this->_trackId = $_val;
262
+    }
263 263
 
264 264
     /**
265 265
      * Set moreInHeader
@@ -267,30 +267,30 @@  discard block
 block discarded – undo
267 267
      * @param	string		$_val		Value
268 268
      * @return	void
269 269
      */
270
-	function setMoreInHeader($_val = '')
271
-	{
272
-		$this->_moreinheader = $_val;
273
-	}
270
+    function setMoreInHeader($_val = '')
271
+    {
272
+        $this->_moreinheader = $_val;
273
+    }
274 274
 
275
-	/**
275
+    /**
276 276
      * get trackid
277 277
      *
278 278
      * @return	string		Track id
279 279
      */
280
-	function getTrackId()
281
-	{
282
-		return $this->_trackId;
283
-	}
280
+    function getTrackId()
281
+    {
282
+        return $this->_trackId;
283
+    }
284 284
 
285
-	/**
286
-	 * get moreInHeader
287
-	 *
288
-	 * @return	string		moreInHeader
289
-	 */
290
-	function getMoreInHeader()
291
-	{
292
-	    return $this->_moreinheader;
293
-	}
285
+    /**
286
+     * get moreInHeader
287
+     *
288
+     * @return	string		moreInHeader
289
+     */
290
+    function getMoreInHeader()
291
+    {
292
+        return $this->_moreinheader;
293
+    }
294 294
 
295 295
     /**
296 296
      * Set errors to
@@ -298,11 +298,11 @@  discard block
 block discarded – undo
298 298
      * @param	string		$_strErrorsTo		Errors to
299 299
      * @return	void
300 300
      */
301
-	function setErrorsTo($_strErrorsTo)
302
-	{
303
-		if ( $_strErrorsTo )
304
-		$this->_errorsTo = $this->_strip_email($_strErrorsTo);
305
-	}
301
+    function setErrorsTo($_strErrorsTo)
302
+    {
303
+        if ( $_strErrorsTo )
304
+        $this->_errorsTo = $this->_strip_email($_strErrorsTo);
305
+    }
306 306
 
307 307
     /**
308 308
      * Get errors to
@@ -310,143 +310,143 @@  discard block
 block discarded – undo
310 310
      * @param	boolean		$_part		Variant
311 311
      * @return	string					Errors to
312 312
      */
313
-	function getErrorsTo($_part = true )
314
-	{
315
-		$_retValue = '';
316
-
317
-		if ( $_part === true )
318
-		$_retValue = $this->_errorsTo;
319
-		else
320
-		$_retValue = $this->_errorsTo[$_part];
321
-
322
-		return $_retValue;
323
-	}
324
-
325
-	/**
326
-	 * Set debug
327
-	 *
328
-	 * @param	boolean		$_vDebug		Value for debug
329
-	 * @return 	void
330
-	 */
331
-	function setDebug($_vDebug = false )
332
-	{
333
-		$this->_debug = $_vDebug;
334
-	}
335
-
336
-	/**
337
-	 * build RECIPIENT List, all addresses who will recieve this message
338
-	 *
339
-	 * @return void
340
-	 */
341
-	function buildRCPTlist()
342
-	{
343
-		// Pull TO list
344
-		$_aryToList = $this->getTO();
345
-	}
313
+    function getErrorsTo($_part = true )
314
+    {
315
+        $_retValue = '';
316
+
317
+        if ( $_part === true )
318
+        $_retValue = $this->_errorsTo;
319
+        else
320
+        $_retValue = $this->_errorsTo[$_part];
321
+
322
+        return $_retValue;
323
+    }
324
+
325
+    /**
326
+     * Set debug
327
+     *
328
+     * @param	boolean		$_vDebug		Value for debug
329
+     * @return 	void
330
+     */
331
+    function setDebug($_vDebug = false )
332
+    {
333
+        $this->_debug = $_vDebug;
334
+    }
335
+
336
+    /**
337
+     * build RECIPIENT List, all addresses who will recieve this message
338
+     *
339
+     * @return void
340
+     */
341
+    function buildRCPTlist()
342
+    {
343
+        // Pull TO list
344
+        $_aryToList = $this->getTO();
345
+    }
346 346
 
347 347
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
348
-	/**
349
-	 * Attempt a connection to mail server
350
-	 *
351
-	 * @return mixed  $_retVal   Boolean indicating success or failure on connection
352
-	 */
353
-	function _server_connect()
354
-	{
348
+    /**
349
+     * Attempt a connection to mail server
350
+     *
351
+     * @return mixed  $_retVal   Boolean indicating success or failure on connection
352
+     */
353
+    function _server_connect()
354
+    {
355 355
         // phpcs:enable
356
-		// Default return value
357
-		$_retVal = true;
358
-
359
-		// We have to make sure the HOST given is valid
360
-		// This is done here because '@fsockopen' will not give me this
361
-		// information if it failes to connect because it can't find the HOST
362
-		$host=$this->getHost();
363
-		$usetls = preg_match('@tls://@i',$host);
364
-
365
-		$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
366
-		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
367
-		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
368
-
369
-		// @CHANGE LDR
370
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
371
-
372
-		if ( (! is_ip($host)) && ((gethostbyname($host)) == $host))
373
-		{
374
-			$this->_setErr(99, $host . ' is either offline or is an invalid host name.');
375
-			$_retVal = false;
376
-		}
377
-		else
378
-		{
379
-			//See if we can connect to the SMTP server
380
-			if ($this->socket = @fsockopen(
381
-    			preg_replace('@tls://@i','',$this->getHost()),       // Host to 'hit', IP or domain
382
-    			$this->getPort(),       // which Port number to use
383
-    			$this->errno,           // actual system level error
384
-    			$this->errstr,          // and any text that goes with the error
385
-    			$this->_smtpTimeout
386
-			))  // timeout for reading/writing data over the socket
387
-			{
388
-				// Fix from PHP SMTP class by 'Chris Ryan'
389
-				// Sometimes the SMTP server takes a little longer to respond
390
-				// so we will give it a longer timeout for the first read
391
-				// Windows still does not have support for this timeout function
392
-				if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
393
-
394
-				// Check response from Server
395
-				if ( $_retVal = $this->server_parse($this->socket, "220") )
396
-				$_retVal = $this->socket;
397
-			}
398
-			// This connection attempt failed.
399
-			else
400
-			{
401
-				// @CHANGE LDR
402
-				if (empty($this->errstr)) $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
403
-				$this->_setErr($this->errno, $this->errstr);
404
-				$_retVal = false;
405
-			}
406
-		}
407
-
408
-		return $_retVal;
409
-	}
356
+        // Default return value
357
+        $_retVal = true;
358
+
359
+        // We have to make sure the HOST given is valid
360
+        // This is done here because '@fsockopen' will not give me this
361
+        // information if it failes to connect because it can't find the HOST
362
+        $host=$this->getHost();
363
+        $usetls = preg_match('@tls://@i',$host);
364
+
365
+        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
366
+        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
367
+        $host=preg_replace('@tls://@i','',$host);	// Remove prefix
368
+
369
+        // @CHANGE LDR
370
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
371
+
372
+        if ( (! is_ip($host)) && ((gethostbyname($host)) == $host))
373
+        {
374
+            $this->_setErr(99, $host . ' is either offline or is an invalid host name.');
375
+            $_retVal = false;
376
+        }
377
+        else
378
+        {
379
+            //See if we can connect to the SMTP server
380
+            if ($this->socket = @fsockopen(
381
+                preg_replace('@tls://@i','',$this->getHost()),       // Host to 'hit', IP or domain
382
+                $this->getPort(),       // which Port number to use
383
+                $this->errno,           // actual system level error
384
+                $this->errstr,          // and any text that goes with the error
385
+                $this->_smtpTimeout
386
+            ))  // timeout for reading/writing data over the socket
387
+            {
388
+                // Fix from PHP SMTP class by 'Chris Ryan'
389
+                // Sometimes the SMTP server takes a little longer to respond
390
+                // so we will give it a longer timeout for the first read
391
+                // Windows still does not have support for this timeout function
392
+                if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
393
+
394
+                // Check response from Server
395
+                if ( $_retVal = $this->server_parse($this->socket, "220") )
396
+                $_retVal = $this->socket;
397
+            }
398
+            // This connection attempt failed.
399
+            else
400
+            {
401
+                // @CHANGE LDR
402
+                if (empty($this->errstr)) $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
403
+                $this->_setErr($this->errno, $this->errstr);
404
+                $_retVal = false;
405
+            }
406
+        }
407
+
408
+        return $_retVal;
409
+    }
410 410
 
411 411
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
412
-	/**
413
-	 * Attempt mail server authentication for a secure connection
414
-	 *
415
-	 * @return boolean|null  $_retVal   Boolean indicating success or failure of authentication
416
-	 */
417
-	function _server_authenticate()
418
-	{
412
+    /**
413
+     * Attempt mail server authentication for a secure connection
414
+     *
415
+     * @return boolean|null  $_retVal   Boolean indicating success or failure of authentication
416
+     */
417
+    function _server_authenticate()
418
+    {
419 419
         // phpcs:enable
420
-		global $conf;
421
-
422
-		// Send the RFC2554 specified EHLO.
423
-		// This improvment as provided by 'SirSir' to
424
-		// accomodate both SMTP AND ESMTP capable servers
425
-		$host=$this->getHost();
426
-		$usetls = preg_match('@tls://@i',$host);
427
-
428
-		$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
429
-		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
430
-		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
431
-
432
-		if ($usetls) $host='tls://'.$host;
433
-
434
-		$hosth = $host;
435
-
436
-		if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
437
-		{
438
-			// If the from to is 'aaa <[email protected]>', we will keep 'ccc.com'
439
-			$hosth = $this->getFrom('addr');
440
-			$hosth = preg_replace('/^.*</', '', $hosth);
441
-			$hosth = preg_replace('/>.*$/', '', $hosth);
442
-			$hosth = preg_replace('/.*@/', '', $hosth);
443
-		}
444
-
445
-		if ( $_retVal = $this->socket_send_str('EHLO ' . $hosth, '250') )
446
-		{
447
-			if ($usetls)
448
-			{
449
-			    /*
420
+        global $conf;
421
+
422
+        // Send the RFC2554 specified EHLO.
423
+        // This improvment as provided by 'SirSir' to
424
+        // accomodate both SMTP AND ESMTP capable servers
425
+        $host=$this->getHost();
426
+        $usetls = preg_match('@tls://@i',$host);
427
+
428
+        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
429
+        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
430
+        $host=preg_replace('@tls://@i','',$host);	// Remove prefix
431
+
432
+        if ($usetls) $host='tls://'.$host;
433
+
434
+        $hosth = $host;
435
+
436
+        if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
437
+        {
438
+            // If the from to is 'aaa <[email protected]>', we will keep 'ccc.com'
439
+            $hosth = $this->getFrom('addr');
440
+            $hosth = preg_replace('/^.*</', '', $hosth);
441
+            $hosth = preg_replace('/>.*$/', '', $hosth);
442
+            $hosth = preg_replace('/.*@/', '', $hosth);
443
+        }
444
+
445
+        if ( $_retVal = $this->socket_send_str('EHLO ' . $hosth, '250') )
446
+        {
447
+            if ($usetls)
448
+            {
449
+                /*
450 450
 			    The following dialog illustrates how a client and server can start a TLS STARTTLS session
451 451
 			    S: <waits for connection on TCP port 25>
452 452
 			    C: <opens connection>
@@ -465,130 +465,130 @@  discard block
 block discarded – undo
465 465
                 S: 250 AUTH LOGIN
466 466
 			    C: <continues by sending an SMTP command
467 467
 			    */
468
-				if (!$_retVal = $this->socket_send_str('STARTTLS', 220))
469
-				{
470
-					$this->_setErr(131, 'STARTTLS connection is not supported.');
471
-					return $_retVal;
472
-				}
473
-
474
-				// Before 5.6.7:
475
-				// STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_SSLv2_CLIENT|STREAM_CRYPTO_METHOD_SSLv3_CLIENT
476
-				// STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
477
-				// PHP >= 5.6.7:
478
-				// STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
479
-				// STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
480
-
481
-				$crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
482
-				if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
483
-					$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
484
-					$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
485
-				}
486
-
487
-				if (!stream_socket_enable_crypto($this->socket, true, $crypto_method))
488
-				{
489
-					$this->_setErr(132, 'STARTTLS connection failed.');
490
-					return $_retVal;
491
-				}
492
-				// Most server servers expect a 2nd pass of EHLO after TLS is established to get another time
493
-				// the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
494
-				if (!$_retVal = $this->socket_send_str('EHLO '.$host, '250'))
495
-				{
496
-					$this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
497
-					return $_retVal;
498
-				}
499
-			}
500
-			// Send Authentication to Server
501
-			// Check for errors along the way
502
-			$this->socket_send_str('AUTH LOGIN', '334');
503
-
504
-			// User name will not return any error, server will take anything we give it.
505
-			$this->socket_send_str(base64_encode($this->_smtpsID), '334');
506
-
507
-			// The error here just means the ID/password combo doesn't work.
508
-			// There is not a method to determine which is the problem, ID or password
509
-			if ( ! $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235') )
510
-			$this->_setErr(130, 'Invalid Authentication Credentials.');
511
-		}
512
-		else
513
-		{
514
-			$this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
515
-		}
516
-
517
-		return $_retVal;
518
-	}
519
-
520
-	/**
521
-	 * Now send the message
522
-	 *
523
-	 * @param  boolean $_bolTestMsg  whether to run this method in 'Test' mode.
524
-	 * @param  boolean $_bolDebug    whether to log all communication between this Class and the Mail Server.
525
-	 * @return boolean|null   void
526
-	 *                 $_strMsg      If this is run in 'Test' mode, the actual message structure will be returned
527
-	 */
528
-	function sendMsg($_bolTestMsg = false, $_bolDebug = false)
529
-	{
530
-		global $conf;
531
-
532
-		/**
533
-		 * Default return value
534
-		 */
535
-		$_retVal = false;
536
-
537
-		// Connect to Server
538
-		if ( $this->socket = $this->_server_connect() )
539
-		{
540
-			// If a User ID *and* a password is given, assume Authentication is desired
541
-			if( !empty($this->_smtpsID) && !empty($this->_smtpsPW) )
542
-			{
543
-				// Send the RFC2554 specified EHLO.
544
-				$_retVal = $this->_server_authenticate();
545
-			}
546
-
547
-			// This is a "normal" SMTP Server "handshack"
548
-			else
549
-			{
550
-				// Send the RFC821 specified HELO.
551
-				$host=$this->getHost();
552
-				$usetls = preg_match('@tls://@i',$host);
553
-
554
-				$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
555
-				$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
556
-				$host=preg_replace('@tls://@i','',$host);	// Remove prefix
557
-
558
-				$hosth = $host;
559
-
560
-				if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
561
-				{
562
-					// If the from to is 'aaa <[email protected]>', we will keep 'ccc.com'
563
-					$hosth = $this->getFrom('addr');
564
-					$hosth = preg_replace('/^.*</', '', $hosth);
565
-					$hosth = preg_replace('/>.*$/', '', $hosth);
566
-					$hosth = preg_replace('/.*@/', '', $hosth);
567
-				}
568
-
569
-				$_retVal = $this->socket_send_str('HELO ' . $hosth, '250');
570
-			}
571
-
572
-			// Well, did we get to the server?
573
-			if ( $_retVal )
574
-			{
575
-				// From this point onward most server response codes should be 250
576
-				// Specify who the mail is from....
577
-				// This has to be the raw email address, strip the "name" off
578
-				$this->socket_send_str('MAIL FROM: ' . $this->getFrom('addr'), '250');
579
-
580
-				// 'RCPT TO:' must be given a single address, so this has to loop
581
-				// through the list of addresses, regardless of TO, CC or BCC
582
-				// and send it out "single file"
583
-				foreach ( $this->get_RCPT_list() as $_address )
584
-				{
585
-				    /* Note:
468
+                if (!$_retVal = $this->socket_send_str('STARTTLS', 220))
469
+                {
470
+                    $this->_setErr(131, 'STARTTLS connection is not supported.');
471
+                    return $_retVal;
472
+                }
473
+
474
+                // Before 5.6.7:
475
+                // STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_SSLv2_CLIENT|STREAM_CRYPTO_METHOD_SSLv3_CLIENT
476
+                // STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
477
+                // PHP >= 5.6.7:
478
+                // STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
479
+                // STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
480
+
481
+                $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
482
+                if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
483
+                    $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
484
+                    $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
485
+                }
486
+
487
+                if (!stream_socket_enable_crypto($this->socket, true, $crypto_method))
488
+                {
489
+                    $this->_setErr(132, 'STARTTLS connection failed.');
490
+                    return $_retVal;
491
+                }
492
+                // Most server servers expect a 2nd pass of EHLO after TLS is established to get another time
493
+                // the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
494
+                if (!$_retVal = $this->socket_send_str('EHLO '.$host, '250'))
495
+                {
496
+                    $this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
497
+                    return $_retVal;
498
+                }
499
+            }
500
+            // Send Authentication to Server
501
+            // Check for errors along the way
502
+            $this->socket_send_str('AUTH LOGIN', '334');
503
+
504
+            // User name will not return any error, server will take anything we give it.
505
+            $this->socket_send_str(base64_encode($this->_smtpsID), '334');
506
+
507
+            // The error here just means the ID/password combo doesn't work.
508
+            // There is not a method to determine which is the problem, ID or password
509
+            if ( ! $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235') )
510
+            $this->_setErr(130, 'Invalid Authentication Credentials.');
511
+        }
512
+        else
513
+        {
514
+            $this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
515
+        }
516
+
517
+        return $_retVal;
518
+    }
519
+
520
+    /**
521
+     * Now send the message
522
+     *
523
+     * @param  boolean $_bolTestMsg  whether to run this method in 'Test' mode.
524
+     * @param  boolean $_bolDebug    whether to log all communication between this Class and the Mail Server.
525
+     * @return boolean|null   void
526
+     *                 $_strMsg      If this is run in 'Test' mode, the actual message structure will be returned
527
+     */
528
+    function sendMsg($_bolTestMsg = false, $_bolDebug = false)
529
+    {
530
+        global $conf;
531
+
532
+        /**
533
+         * Default return value
534
+         */
535
+        $_retVal = false;
536
+
537
+        // Connect to Server
538
+        if ( $this->socket = $this->_server_connect() )
539
+        {
540
+            // If a User ID *and* a password is given, assume Authentication is desired
541
+            if( !empty($this->_smtpsID) && !empty($this->_smtpsPW) )
542
+            {
543
+                // Send the RFC2554 specified EHLO.
544
+                $_retVal = $this->_server_authenticate();
545
+            }
546
+
547
+            // This is a "normal" SMTP Server "handshack"
548
+            else
549
+            {
550
+                // Send the RFC821 specified HELO.
551
+                $host=$this->getHost();
552
+                $usetls = preg_match('@tls://@i',$host);
553
+
554
+                $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
555
+                $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
556
+                $host=preg_replace('@tls://@i','',$host);	// Remove prefix
557
+
558
+                $hosth = $host;
559
+
560
+                if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
561
+                {
562
+                    // If the from to is 'aaa <[email protected]>', we will keep 'ccc.com'
563
+                    $hosth = $this->getFrom('addr');
564
+                    $hosth = preg_replace('/^.*</', '', $hosth);
565
+                    $hosth = preg_replace('/>.*$/', '', $hosth);
566
+                    $hosth = preg_replace('/.*@/', '', $hosth);
567
+                }
568
+
569
+                $_retVal = $this->socket_send_str('HELO ' . $hosth, '250');
570
+            }
571
+
572
+            // Well, did we get to the server?
573
+            if ( $_retVal )
574
+            {
575
+                // From this point onward most server response codes should be 250
576
+                // Specify who the mail is from....
577
+                // This has to be the raw email address, strip the "name" off
578
+                $this->socket_send_str('MAIL FROM: ' . $this->getFrom('addr'), '250');
579
+
580
+                // 'RCPT TO:' must be given a single address, so this has to loop
581
+                // through the list of addresses, regardless of TO, CC or BCC
582
+                // and send it out "single file"
583
+                foreach ( $this->get_RCPT_list() as $_address )
584
+                {
585
+                    /* Note:
586 586
 				     * BCC email addresses must be listed in the RCPT TO command list,
587 587
                      * but the BCC header should not be printed under the DATA command.
588 588
 				     * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
589 589
 				     */
590 590
 
591
-    				/*
591
+                    /*
592 592
 					 * TODO
593 593
 					 * After each 'RCPT TO:' is sent, we need to make sure it was kosher,
594 594
 					 * if not, the whole message will fail
@@ -596,1237 +596,1237 @@  discard block
 block discarded – undo
596 596
 					 * mark the last address as "bad" and start the address loop over again.
597 597
 					 * If any address fails, the entire message fails.
598 598
 					 */
599
-					$this->socket_send_str('RCPT TO: <' . $_address . '>', '250');
600
-				}
601
-
602
-				// Tell the server we are ready to start sending data
603
-				// with any custom headers...
604
-				// This is the last response code we look for until the end of the message.
605
-				$this->socket_send_str('DATA', '354');
606
-
607
-				// Now we are ready for the message...
608
-				// Ok, all the ingredients are mixed in let's cook this puppy...
609
-				$this->socket_send_str($this->getHeader().$this->getBodyContent() . "\r\n" . '.', '250');
610
-
611
-				// Now tell the server we are done and close the socket...
612
-				fputs($this->socket, 'QUIT');
613
-				fclose($this->socket);
614
-			}
615
-		}
616
-
617
-		return $_retVal;
618
-	}
619
-
620
-	// =============================================================
621
-	// ** Setter & Getter methods
622
-
623
-	// ** Basic System configuration
624
-
625
-	/**
626
-	 * setConfig() is used to populate select class properties from either
627
-	 * a user defined INI file or the systems 'php.ini' file
628
-	 *
629
-	 * If a user defined INI is to be used, the files complete path is passed
630
-	 * as the method single parameter. The INI can define any class and/or
631
-	 * user properties. Only properties defined within this file will be setter
632
-	 * and/or orverwritten
633
-	 *
634
-	 * If the systems 'php.ini' file is to be used, the method is called without
635
-	 * parameters. In this case, only HOST, PORT and FROM properties will be set
636
-	 * as they are the only properties that are defined within the 'php.ini'.
637
-	 *
638
-	 * If secure SMTP is to be used, the user ID and Password can be defined with
639
-	 * the user INI file, but the properties are not defined with the systems
640
-	 * 'php.ini'file, they must be defined via their setter methods
641
-	 *
642
-	 * This method can be called twice, if desired. Once without a parameter to
643
-	 * load the properties as defined within the systems 'php.ini' file, and a
644
-	 * second time, with a path to a user INI file for other properties to be
645
-	 * defined.
646
-	 *
647
-	 * @param mixed $_strConfigPath path to config file or VOID
648
-	 * @return boolean
649
-	 */
650
-	function setConfig($_strConfigPath = null)
651
-	{
652
-		/**
653
-		 * Returns constructed SELECT Object string or boolean upon failure
654
-		 * Default value is set at true
655
-		 */
656
-		$_retVal = true;
657
-
658
-		// if we have a path...
659
-		if ( ! empty ($_strConfigPath) )
660
-		{
661
-			// If the path is not valid, this will NOT generate an error,
662
-			// it will simply return false.
663
-			if ( ! @include $_strConfigPath)
664
-			{
665
-				$this->_setErr(110, '"' . $_strConfigPath . '" is not a valid path.');
666
-				$_retVal = false;
667
-			}
668
-		}
669
-
670
-		// Read the Systems php.ini file
671
-		else
672
-		{
673
-			// Set these properties ONLY if they are set in the php.ini file.
674
-			// Otherwise the default values will be used.
675
-			if ( $_host = ini_get('SMTPs') )
676
-			$this->setHost($_host);
677
-
678
-			if ( $_port = ini_get('smtp_port') )
679
-			$this->setPort($_port);
680
-
681
-			if ( $_from = ini_get('sendmail_from') )
682
-			$this->setFrom($_from);
683
-		}
684
-
685
-		// Send back what we have
686
-		return $_retVal;
687
-	}
688
-
689
-	/**
690
-	 * Determines the method inwhich the messages are to be sent.
691
-	 * - 'sockets' [0] - conect via network to SMTP server
692
-	 * - 'pipe     [1] - use UNIX path to EXE
693
-	 * - 'phpmail  [2] - use the PHP built-in mail function
694
-	 *
695
-	 * @param int $_type  Interger value representing Mail Transport Type
696
-	 * @return void
697
-	 */
698
-	function setTransportType($_type = 0)
699
-	{
700
-		if ( ( is_numeric($_type) ) &&
701
-		( ( $_type >= 0 ) && ( $_type <= 3 ) ) )
702
-		$this->_transportType = $_type;
703
-	}
704
-
705
-	/**
706
-	 * Return the method inwhich the message is to be sent.
707
-	 * - 'sockets' [0] - conect via network to SMTP server
708
-	 * - 'pipe     [1] - use UNIX path to EXE
709
-	 * - 'phpmail  [2] - use the PHP built-in mail function
710
-	 *
711
-	 * @return int $_strHost Host Name or IP of the Mail Server to use
712
-	 */
713
-	function getTransportType()
714
-	{
715
-		return $this->_transportType;
716
-	}
717
-
718
-	/**
719
-	 * Path to the sendmail execuable
720
-	 *
721
-	 * @param string $_path Path to the sendmail execuable
722
-	 * @return boolean
723
-	 *
724
-	 */
725
-	function setMailPath($_path)
726
-	{
727
-		// This feature is not yet implemented
728
-		return true;
729
-
730
-		//if ( $_path ) $this->_mailPath = $_path;
731
-	}
732
-
733
-	/**
734
-	 * Defines the Host Name or IP of the Mail Server to use.
735
-	 * This is defaulted to 'localhost'
736
-	 * This is  used only with 'socket' based mail transmission
737
-	 *
738
-	 * @param 	string 	$_strHost 		Host Name or IP of the Mail Server to use
739
-	 * @return 	void
740
-	 */
741
-	function setHost($_strHost)
742
-	{
743
-		if ( $_strHost )
744
-		$this->_smtpsHost = $_strHost;
745
-	}
746
-
747
-	/**
748
-	 * Retrieves the Host Name or IP of the Mail Server to use
749
-	 * This is  used only with 'socket' based mail transmission
750
-	 *
751
-	 * @return 	string 	$_strHost 		Host Name or IP of the Mail Server to use
752
-	 */
753
-	function getHost()
754
-	{
755
-		return $this->_smtpsHost;
756
-	}
757
-
758
-	/**
759
-	 * Defines the Port Number of the Mail Server to use
760
-	 * This is defaulted to '25'
761
-	 * This is  used only with 'socket' based mail transmission
762
-	 *
763
-	 * @param 	int 	$_intPort 		Port Number of the Mail Server to use
764
-	 * @return 	void
765
-	 */
766
-	function setPort($_intPort)
767
-	{
768
-		if ( ( is_numeric($_intPort) ) &&
769
-		( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) )
770
-		$this->_smtpsPort = $_intPort;
771
-	}
772
-
773
-	/**
774
-	 * Retrieves the Port Number of the Mail Server to use
775
-	 * This is  used only with 'socket' based mail transmission
776
-	 *
777
-	 * @return 	string 		Port Number of the Mail Server to use
778
-	 */
779
-	function getPort()
780
-	{
781
-		return $this->_smtpsPort;
782
-	}
783
-
784
-	/**
785
-	 * User Name for authentication on Mail Server
786
-	 *
787
-	 * @param 	string 	$_strID 	User Name for authentication on Mail Server
788
-	 * @return 	void
789
-	 */
790
-	function setID($_strID)
791
-	{
792
-		$this->_smtpsID = $_strID;
793
-	}
794
-
795
-	/**
796
-	 * Retrieves the User Name for authentication on Mail Server
797
-	 *
798
-	 * @return string 	User Name for authentication on Mail Server
799
-	 */
800
-	function getID()
801
-	{
802
-		return $this->_smtpsID;
803
-	}
804
-
805
-	/**
806
-	 * User Password for authentication on Mail Server
807
-	 *
808
-	 * @param 	string 	$_strPW 	User Password for authentication on Mail Server
809
-	 * @return 	void
810
-	 */
811
-	function setPW($_strPW)
812
-	{
813
-		$this->_smtpsPW = $_strPW;
814
-	}
815
-
816
-	/**
817
-	 * Retrieves the User Password for authentication on Mail Server
818
-	 *
819
-	 * @return 	string 		User Password for authentication on Mail Server
820
-	 */
821
-	function getPW()
822
-	{
823
-		return $this->_smtpsPW;
824
-	}
825
-
826
-	/**
827
-	 * Character set used for current message
828
-	 * Character set is defaulted to 'iso-8859-1';
829
-	 *
830
-	 * @param string $_strCharSet Character set used for current message
831
-	 * @return void
832
-	 */
833
-	function setCharSet($_strCharSet)
834
-	{
835
-		if ( $_strCharSet )
836
-		$this->_smtpsCharSet = $_strCharSet;
837
-	}
838
-
839
-	/**
840
-	 * Retrieves the Character set used for current message
841
-	 *
842
-	 * @return string $_smtpsCharSet Character set used for current message
843
-	 */
844
-	function getCharSet()
845
-	{
846
-		return $this->_smtpsCharSet;
847
-	}
848
-
849
-	/**
850
-	 * Content-Transfer-Encoding, Defaulted to '7bit'
851
-	 * This can be changed for 2byte characers sets
852
-	 * Known Encode Types
853
-	 *  - 7bit               Simple 7-bit ASCII
854
-	 *  - 8bit               8-bit coding with line termination characters
855
-	 *  - base64             3 octets encoded into 4 sextets with offset
856
-	 *  - binary             Arbitrary binary stream
857
-	 *  - mac-binhex40       Macintosh binary to hex encoding
858
-	 *  - quoted-printable   Mostly 7-bit, with 8-bit characters encoded as "=HH"
859
-	 *  - uuencode           UUENCODE encoding
860
-	 *
861
-	 * @param string $_strTransEncode Content-Transfer-Encoding
862
-	 * @return void
863
-	 */
864
-	function setTransEncode($_strTransEncode)
865
-	{
866
-		if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes))
867
-		$this->_smtpsTransEncode = $_strTransEncode;
868
-	}
869
-
870
-	/**
871
-	 * Retrieves the Content-Transfer-Encoding
872
-	 *
873
-	 * @return string $_smtpsTransEncode Content-Transfer-Encoding
874
-	 */
875
-	function getTransEncode()
876
-	{
877
-		return $this->_smtpsTransEncode;
878
-	}
879
-
880
-	/**
881
-	 * Content-Transfer-Encoding, Defaulted to '0' [ZERO]
882
-	 * This can be changed for 2byte characers sets
883
-	 * Known Encode Types
884
-	 *  - [0] 7bit               Simple 7-bit ASCII
885
-	 *  - [1] 8bit               8-bit coding with line termination characters
886
-	 *  - [2] base64             3 octets encoded into 4 sextets with offset
887
-	 *  - [3] binary             Arbitrary binary stream
888
-	 *  - [4] mac-binhex40       Macintosh binary to hex encoding
889
-	 *  - [5] quoted-printable   Mostly 7-bit, with 8-bit characters encoded as "=HH"
890
-	 *  - [6] uuencode           UUENCODE encoding
891
-	 *
892
-	 * @param string $_strTransEncodeType Content-Transfer-Encoding
893
-	 * @return void
894
-	 *
895
-	 */
896
-	function setTransEncodeType($_strTransEncodeType)
897
-	{
898
-		if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes))
899
-		$this->_smtpsTransEncodeType = $_strTransEncodeType;
900
-	}
901
-
902
-	/**
903
-	 * Retrieves the Content-Transfer-Encoding
904
-	 *
905
-	 * @return 	string 		Content-Transfer-Encoding
906
-	 */
907
-	function getTransEncodeType()
908
-	{
909
-		return $this->_smtpsTransEncodeTypes[$this->_smtpsTransEncodeType];
910
-	}
911
-
912
-
913
-	// ** Message Construction
914
-
915
-	/**
916
-	 * FROM Address from which mail will be sent
917
-	 *
918
-	 * @param 	string 	$_strFrom 	Address from which mail will be sent
919
-	 * @return 	void
920
-	 */
921
-	function setFrom($_strFrom)
922
-	{
923
-		if ( $_strFrom )
924
-		$this->_msgFrom = $this->_strip_email($_strFrom);
925
-	}
926
-
927
-	/**
928
-	 * Retrieves the Address from which mail will be sent
929
-	 *
930
-	 * @param  	boolean $_part		To "strip" 'Real name' from address
931
-	 * @return 	string 				Address from which mail will be sent
932
-	 */
933
-	function getFrom($_part = true)
934
-	{
935
-		$_retValue = '';
936
-
937
-		if ( $_part === true )
938
-		$_retValue = $this->_msgFrom;
939
-		else
940
-		$_retValue = $this->_msgFrom[$_part];
941
-
942
-		return $_retValue;
943
-	}
944
-
945
-	/**
946
-	 * Reply-To Address from which mail will be the reply-to
947
-	 *
948
-	 * @param 	string 	$_strReplyTo 	Address from which mail will be the reply-to
949
-	 * @return 	void
950
-	 */
951
-	function setReplyTo($_strReplyTo)
952
-	{
953
-	    if ( $_strReplyTo )
954
-	        $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
955
-	}
956
-
957
-	/**
958
-	 * Retrieves the Address from which mail will be the reply-to
959
-	 *
960
-	 * @param  	boolean $_part		To "strip" 'Real name' from address
961
-	 * @return 	string 				Address from which mail will be the reply-to
962
-	 */
963
-	function getReplyTo($_part = true)
964
-	{
965
-	    $_retValue = '';
966
-
967
-	    if ( $_part === true )
968
-	        $_retValue = $this->_msgReplyTo;
969
-	    else
970
-	        $_retValue = $this->_msgReplyTo[$_part];
971
-
972
-	    return $_retValue;
973
-	}
974
-
975
-	/**
976
-	 * Inserts given addresses into structured format.
977
-	 * This method takes a list of given addresses, via an array
978
-	 * or a COMMA delimted string, and inserts them into a highly
979
-	 * structured array. This array is designed to remove duplicate
980
-	 * addresses and to sort them by Domain.
981
-	 *
982
-	 * @param 	string 	$_type 			TO, CC, or BCC lists to add addrresses into
983
-	 * @param 	mixed 	$_addrList 		Array or COMMA delimited string of addresses
984
-	 * @return void
985
-	 *
986
-	 */
987
-	function _buildAddrList($_type, $_addrList)
988
-	{
989
-		// Pull existing list
990
-		$aryHost = $this->_msgRecipients;
991
-
992
-		// Only run this if we have something
993
-		if ( !empty ($_addrList ))
994
-		{
995
-			// $_addrList can be a STRING or an array
996
-			if ( is_string($_addrList) )
997
-			{
998
-				// This could be a COMMA delimited string
999
-				if ( strstr($_addrList, ',') )
1000
-				// "explode "list" into an array
1001
-				$_addrList = explode(',', $_addrList);
1002
-
1003
-				// Stick it in an array
1004
-				else
1005
-				$_addrList = array($_addrList);
1006
-			}
1007
-
1008
-			// take the array of addresses and split them further
1009
-			foreach ( $_addrList as $_strAddr )
1010
-			{
1011
-				// Strip off the end '>'
1012
-				$_strAddr = str_replace('>', '', $_strAddr);
1013
-
1014
-				// Seperate "Real Name" from eMail address
1015
-				$_tmpaddr = null;
1016
-				$_tmpaddr = explode('<', $_strAddr);
1017
-
1018
-				// We have a "Real Name" and eMail address
1019
-				if ( count($_tmpaddr) == 2 )
1020
-				{
1021
-					$_tmpHost = explode('@', $_tmpaddr[1]);
1022
-					$_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
1023
-					$aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = $_tmpaddr[0];
1024
-				}
1025
-				// We only have an eMail address
1026
-				else
1027
-				{
1028
-					// Strip off the beggining '<'
1029
-					$_strAddr = str_replace('<', '', $_strAddr);
1030
-
1031
-					$_tmpHost = explode('@', $_strAddr);
1032
-					$_tmpHost[0] = trim($_tmpHost[0]);
1033
-					$_tmpHost[1] = trim($_tmpHost[1]);
1034
-
1035
-					$aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = '';
1036
-				}
1037
-			}
1038
-		}
1039
-		// replace list
1040
-		$this->_msgRecipients = $aryHost;
1041
-	}
599
+                    $this->socket_send_str('RCPT TO: <' . $_address . '>', '250');
600
+                }
601
+
602
+                // Tell the server we are ready to start sending data
603
+                // with any custom headers...
604
+                // This is the last response code we look for until the end of the message.
605
+                $this->socket_send_str('DATA', '354');
606
+
607
+                // Now we are ready for the message...
608
+                // Ok, all the ingredients are mixed in let's cook this puppy...
609
+                $this->socket_send_str($this->getHeader().$this->getBodyContent() . "\r\n" . '.', '250');
610
+
611
+                // Now tell the server we are done and close the socket...
612
+                fputs($this->socket, 'QUIT');
613
+                fclose($this->socket);
614
+            }
615
+        }
616
+
617
+        return $_retVal;
618
+    }
619
+
620
+    // =============================================================
621
+    // ** Setter & Getter methods
622
+
623
+    // ** Basic System configuration
624
+
625
+    /**
626
+     * setConfig() is used to populate select class properties from either
627
+     * a user defined INI file or the systems 'php.ini' file
628
+     *
629
+     * If a user defined INI is to be used, the files complete path is passed
630
+     * as the method single parameter. The INI can define any class and/or
631
+     * user properties. Only properties defined within this file will be setter
632
+     * and/or orverwritten
633
+     *
634
+     * If the systems 'php.ini' file is to be used, the method is called without
635
+     * parameters. In this case, only HOST, PORT and FROM properties will be set
636
+     * as they are the only properties that are defined within the 'php.ini'.
637
+     *
638
+     * If secure SMTP is to be used, the user ID and Password can be defined with
639
+     * the user INI file, but the properties are not defined with the systems
640
+     * 'php.ini'file, they must be defined via their setter methods
641
+     *
642
+     * This method can be called twice, if desired. Once without a parameter to
643
+     * load the properties as defined within the systems 'php.ini' file, and a
644
+     * second time, with a path to a user INI file for other properties to be
645
+     * defined.
646
+     *
647
+     * @param mixed $_strConfigPath path to config file or VOID
648
+     * @return boolean
649
+     */
650
+    function setConfig($_strConfigPath = null)
651
+    {
652
+        /**
653
+         * Returns constructed SELECT Object string or boolean upon failure
654
+         * Default value is set at true
655
+         */
656
+        $_retVal = true;
657
+
658
+        // if we have a path...
659
+        if ( ! empty ($_strConfigPath) )
660
+        {
661
+            // If the path is not valid, this will NOT generate an error,
662
+            // it will simply return false.
663
+            if ( ! @include $_strConfigPath)
664
+            {
665
+                $this->_setErr(110, '"' . $_strConfigPath . '" is not a valid path.');
666
+                $_retVal = false;
667
+            }
668
+        }
669
+
670
+        // Read the Systems php.ini file
671
+        else
672
+        {
673
+            // Set these properties ONLY if they are set in the php.ini file.
674
+            // Otherwise the default values will be used.
675
+            if ( $_host = ini_get('SMTPs') )
676
+            $this->setHost($_host);
677
+
678
+            if ( $_port = ini_get('smtp_port') )
679
+            $this->setPort($_port);
680
+
681
+            if ( $_from = ini_get('sendmail_from') )
682
+            $this->setFrom($_from);
683
+        }
684
+
685
+        // Send back what we have
686
+        return $_retVal;
687
+    }
688
+
689
+    /**
690
+     * Determines the method inwhich the messages are to be sent.
691
+     * - 'sockets' [0] - conect via network to SMTP server
692
+     * - 'pipe     [1] - use UNIX path to EXE
693
+     * - 'phpmail  [2] - use the PHP built-in mail function
694
+     *
695
+     * @param int $_type  Interger value representing Mail Transport Type
696
+     * @return void
697
+     */
698
+    function setTransportType($_type = 0)
699
+    {
700
+        if ( ( is_numeric($_type) ) &&
701
+        ( ( $_type >= 0 ) && ( $_type <= 3 ) ) )
702
+        $this->_transportType = $_type;
703
+    }
704
+
705
+    /**
706
+     * Return the method inwhich the message is to be sent.
707
+     * - 'sockets' [0] - conect via network to SMTP server
708
+     * - 'pipe     [1] - use UNIX path to EXE
709
+     * - 'phpmail  [2] - use the PHP built-in mail function
710
+     *
711
+     * @return int $_strHost Host Name or IP of the Mail Server to use
712
+     */
713
+    function getTransportType()
714
+    {
715
+        return $this->_transportType;
716
+    }
717
+
718
+    /**
719
+     * Path to the sendmail execuable
720
+     *
721
+     * @param string $_path Path to the sendmail execuable
722
+     * @return boolean
723
+     *
724
+     */
725
+    function setMailPath($_path)
726
+    {
727
+        // This feature is not yet implemented
728
+        return true;
729
+
730
+        //if ( $_path ) $this->_mailPath = $_path;
731
+    }
732
+
733
+    /**
734
+     * Defines the Host Name or IP of the Mail Server to use.
735
+     * This is defaulted to 'localhost'
736
+     * This is  used only with 'socket' based mail transmission
737
+     *
738
+     * @param 	string 	$_strHost 		Host Name or IP of the Mail Server to use
739
+     * @return 	void
740
+     */
741
+    function setHost($_strHost)
742
+    {
743
+        if ( $_strHost )
744
+        $this->_smtpsHost = $_strHost;
745
+    }
746
+
747
+    /**
748
+     * Retrieves the Host Name or IP of the Mail Server to use
749
+     * This is  used only with 'socket' based mail transmission
750
+     *
751
+     * @return 	string 	$_strHost 		Host Name or IP of the Mail Server to use
752
+     */
753
+    function getHost()
754
+    {
755
+        return $this->_smtpsHost;
756
+    }
757
+
758
+    /**
759
+     * Defines the Port Number of the Mail Server to use
760
+     * This is defaulted to '25'
761
+     * This is  used only with 'socket' based mail transmission
762
+     *
763
+     * @param 	int 	$_intPort 		Port Number of the Mail Server to use
764
+     * @return 	void
765
+     */
766
+    function setPort($_intPort)
767
+    {
768
+        if ( ( is_numeric($_intPort) ) &&
769
+        ( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) )
770
+        $this->_smtpsPort = $_intPort;
771
+    }
772
+
773
+    /**
774
+     * Retrieves the Port Number of the Mail Server to use
775
+     * This is  used only with 'socket' based mail transmission
776
+     *
777
+     * @return 	string 		Port Number of the Mail Server to use
778
+     */
779
+    function getPort()
780
+    {
781
+        return $this->_smtpsPort;
782
+    }
783
+
784
+    /**
785
+     * User Name for authentication on Mail Server
786
+     *
787
+     * @param 	string 	$_strID 	User Name for authentication on Mail Server
788
+     * @return 	void
789
+     */
790
+    function setID($_strID)
791
+    {
792
+        $this->_smtpsID = $_strID;
793
+    }
794
+
795
+    /**
796
+     * Retrieves the User Name for authentication on Mail Server
797
+     *
798
+     * @return string 	User Name for authentication on Mail Server
799
+     */
800
+    function getID()
801
+    {
802
+        return $this->_smtpsID;
803
+    }
804
+
805
+    /**
806
+     * User Password for authentication on Mail Server
807
+     *
808
+     * @param 	string 	$_strPW 	User Password for authentication on Mail Server
809
+     * @return 	void
810
+     */
811
+    function setPW($_strPW)
812
+    {
813
+        $this->_smtpsPW = $_strPW;
814
+    }
815
+
816
+    /**
817
+     * Retrieves the User Password for authentication on Mail Server
818
+     *
819
+     * @return 	string 		User Password for authentication on Mail Server
820
+     */
821
+    function getPW()
822
+    {
823
+        return $this->_smtpsPW;
824
+    }
825
+
826
+    /**
827
+     * Character set used for current message
828
+     * Character set is defaulted to 'iso-8859-1';
829
+     *
830
+     * @param string $_strCharSet Character set used for current message
831
+     * @return void
832
+     */
833
+    function setCharSet($_strCharSet)
834
+    {
835
+        if ( $_strCharSet )
836
+        $this->_smtpsCharSet = $_strCharSet;
837
+    }
838
+
839
+    /**
840
+     * Retrieves the Character set used for current message
841
+     *
842
+     * @return string $_smtpsCharSet Character set used for current message
843
+     */
844
+    function getCharSet()
845
+    {
846
+        return $this->_smtpsCharSet;
847
+    }
848
+
849
+    /**
850
+     * Content-Transfer-Encoding, Defaulted to '7bit'
851
+     * This can be changed for 2byte characers sets
852
+     * Known Encode Types
853
+     *  - 7bit               Simple 7-bit ASCII
854
+     *  - 8bit               8-bit coding with line termination characters
855
+     *  - base64             3 octets encoded into 4 sextets with offset
856
+     *  - binary             Arbitrary binary stream
857
+     *  - mac-binhex40       Macintosh binary to hex encoding
858
+     *  - quoted-printable   Mostly 7-bit, with 8-bit characters encoded as "=HH"
859
+     *  - uuencode           UUENCODE encoding
860
+     *
861
+     * @param string $_strTransEncode Content-Transfer-Encoding
862
+     * @return void
863
+     */
864
+    function setTransEncode($_strTransEncode)
865
+    {
866
+        if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes))
867
+        $this->_smtpsTransEncode = $_strTransEncode;
868
+    }
869
+
870
+    /**
871
+     * Retrieves the Content-Transfer-Encoding
872
+     *
873
+     * @return string $_smtpsTransEncode Content-Transfer-Encoding
874
+     */
875
+    function getTransEncode()
876
+    {
877
+        return $this->_smtpsTransEncode;
878
+    }
879
+
880
+    /**
881
+     * Content-Transfer-Encoding, Defaulted to '0' [ZERO]
882
+     * This can be changed for 2byte characers sets
883
+     * Known Encode Types
884
+     *  - [0] 7bit               Simple 7-bit ASCII
885
+     *  - [1] 8bit               8-bit coding with line termination characters
886
+     *  - [2] base64             3 octets encoded into 4 sextets with offset
887
+     *  - [3] binary             Arbitrary binary stream
888
+     *  - [4] mac-binhex40       Macintosh binary to hex encoding
889
+     *  - [5] quoted-printable   Mostly 7-bit, with 8-bit characters encoded as "=HH"
890
+     *  - [6] uuencode           UUENCODE encoding
891
+     *
892
+     * @param string $_strTransEncodeType Content-Transfer-Encoding
893
+     * @return void
894
+     *
895
+     */
896
+    function setTransEncodeType($_strTransEncodeType)
897
+    {
898
+        if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes))
899
+        $this->_smtpsTransEncodeType = $_strTransEncodeType;
900
+    }
901
+
902
+    /**
903
+     * Retrieves the Content-Transfer-Encoding
904
+     *
905
+     * @return 	string 		Content-Transfer-Encoding
906
+     */
907
+    function getTransEncodeType()
908
+    {
909
+        return $this->_smtpsTransEncodeTypes[$this->_smtpsTransEncodeType];
910
+    }
911
+
912
+
913
+    // ** Message Construction
914
+
915
+    /**
916
+     * FROM Address from which mail will be sent
917
+     *
918
+     * @param 	string 	$_strFrom 	Address from which mail will be sent
919
+     * @return 	void
920
+     */
921
+    function setFrom($_strFrom)
922
+    {
923
+        if ( $_strFrom )
924
+        $this->_msgFrom = $this->_strip_email($_strFrom);
925
+    }
926
+
927
+    /**
928
+     * Retrieves the Address from which mail will be sent
929
+     *
930
+     * @param  	boolean $_part		To "strip" 'Real name' from address
931
+     * @return 	string 				Address from which mail will be sent
932
+     */
933
+    function getFrom($_part = true)
934
+    {
935
+        $_retValue = '';
936
+
937
+        if ( $_part === true )
938
+        $_retValue = $this->_msgFrom;
939
+        else
940
+        $_retValue = $this->_msgFrom[$_part];
941
+
942
+        return $_retValue;
943
+    }
944
+
945
+    /**
946
+     * Reply-To Address from which mail will be the reply-to
947
+     *
948
+     * @param 	string 	$_strReplyTo 	Address from which mail will be the reply-to
949
+     * @return 	void
950
+     */
951
+    function setReplyTo($_strReplyTo)
952
+    {
953
+        if ( $_strReplyTo )
954
+            $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
955
+    }
956
+
957
+    /**
958
+     * Retrieves the Address from which mail will be the reply-to
959
+     *
960
+     * @param  	boolean $_part		To "strip" 'Real name' from address
961
+     * @return 	string 				Address from which mail will be the reply-to
962
+     */
963
+    function getReplyTo($_part = true)
964
+    {
965
+        $_retValue = '';
966
+
967
+        if ( $_part === true )
968
+            $_retValue = $this->_msgReplyTo;
969
+        else
970
+            $_retValue = $this->_msgReplyTo[$_part];
971
+
972
+        return $_retValue;
973
+    }
974
+
975
+    /**
976
+     * Inserts given addresses into structured format.
977
+     * This method takes a list of given addresses, via an array
978
+     * or a COMMA delimted string, and inserts them into a highly
979
+     * structured array. This array is designed to remove duplicate
980
+     * addresses and to sort them by Domain.
981
+     *
982
+     * @param 	string 	$_type 			TO, CC, or BCC lists to add addrresses into
983
+     * @param 	mixed 	$_addrList 		Array or COMMA delimited string of addresses
984
+     * @return void
985
+     *
986
+     */
987
+    function _buildAddrList($_type, $_addrList)
988
+    {
989
+        // Pull existing list
990
+        $aryHost = $this->_msgRecipients;
991
+
992
+        // Only run this if we have something
993
+        if ( !empty ($_addrList ))
994
+        {
995
+            // $_addrList can be a STRING or an array
996
+            if ( is_string($_addrList) )
997
+            {
998
+                // This could be a COMMA delimited string
999
+                if ( strstr($_addrList, ',') )
1000
+                // "explode "list" into an array
1001
+                $_addrList = explode(',', $_addrList);
1002
+
1003
+                // Stick it in an array
1004
+                else
1005
+                $_addrList = array($_addrList);
1006
+            }
1007
+
1008
+            // take the array of addresses and split them further
1009
+            foreach ( $_addrList as $_strAddr )
1010
+            {
1011
+                // Strip off the end '>'
1012
+                $_strAddr = str_replace('>', '', $_strAddr);
1013
+
1014
+                // Seperate "Real Name" from eMail address
1015
+                $_tmpaddr = null;
1016
+                $_tmpaddr = explode('<', $_strAddr);
1017
+
1018
+                // We have a "Real Name" and eMail address
1019
+                if ( count($_tmpaddr) == 2 )
1020
+                {
1021
+                    $_tmpHost = explode('@', $_tmpaddr[1]);
1022
+                    $_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
1023
+                    $aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = $_tmpaddr[0];
1024
+                }
1025
+                // We only have an eMail address
1026
+                else
1027
+                {
1028
+                    // Strip off the beggining '<'
1029
+                    $_strAddr = str_replace('<', '', $_strAddr);
1030
+
1031
+                    $_tmpHost = explode('@', $_strAddr);
1032
+                    $_tmpHost[0] = trim($_tmpHost[0]);
1033
+                    $_tmpHost[1] = trim($_tmpHost[1]);
1034
+
1035
+                    $aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = '';
1036
+                }
1037
+            }
1038
+        }
1039
+        // replace list
1040
+        $this->_msgRecipients = $aryHost;
1041
+    }
1042 1042
 
1043 1043
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1044
-	/**
1045
-	 * Returns an array of the various parts of an email address
1046
-	 * This assumes a well formed address:
1047
-	 * - "Real name" <[email protected]>
1048
-	 * - "Real Name" is optional
1049
-	 * - if "Real Name" does not exist, the angle brackets are optional
1050
-	 * This will split an email address into 4 or 5 parts.
1051
-	 * - $_aryEmail[org]  = orignal string
1052
-	 * - $_aryEmail[real] = "real name" - if there is one
1053
-	 * - $_aryEmail[addr] = address part "[email protected]"
1054
-	 * - $_aryEmail[host] = "domain.tld"
1055
-	 * - $_aryEmail[user] = "userName"
1056
-	 *
1057
-	 *	@param		string		$_strAddr		Email address
1058
-	 * 	@return 	array	 					An array of the various parts of an email address
1059
-	 */
1060
-	function _strip_email($_strAddr)
1061
-	{
1044
+    /**
1045
+     * Returns an array of the various parts of an email address
1046
+     * This assumes a well formed address:
1047
+     * - "Real name" <[email protected]>
1048
+     * - "Real Name" is optional
1049
+     * - if "Real Name" does not exist, the angle brackets are optional
1050
+     * This will split an email address into 4 or 5 parts.
1051
+     * - $_aryEmail[org]  = orignal string
1052
+     * - $_aryEmail[real] = "real name" - if there is one
1053
+     * - $_aryEmail[addr] = address part "[email protected]"
1054
+     * - $_aryEmail[host] = "domain.tld"
1055
+     * - $_aryEmail[user] = "userName"
1056
+     *
1057
+     *	@param		string		$_strAddr		Email address
1058
+     * 	@return 	array	 					An array of the various parts of an email address
1059
+     */
1060
+    function _strip_email($_strAddr)
1061
+    {
1062 1062
         // phpcs:enable
1063
-		// Keep the orginal
1064
-		$_aryEmail['org'] = $_strAddr;
1063
+        // Keep the orginal
1064
+        $_aryEmail['org'] = $_strAddr;
1065 1065
 
1066
-		// Set entire string to Lower Case
1067
-		$_strAddr = strtolower($_strAddr);
1066
+        // Set entire string to Lower Case
1067
+        $_strAddr = strtolower($_strAddr);
1068 1068
 
1069
-		// Drop "stuff' off the end
1070
-		$_strAddr = trim($_strAddr, ' ">');
1069
+        // Drop "stuff' off the end
1070
+        $_strAddr = trim($_strAddr, ' ">');
1071 1071
 
1072
-		// Seperate "Real Name" from eMail address, if we have one
1073
-		$_tmpAry = explode('<', $_strAddr);
1072
+        // Seperate "Real Name" from eMail address, if we have one
1073
+        $_tmpAry = explode('<', $_strAddr);
1074 1074
 
1075
-		// Do we have a "Real name"
1076
-		if ( count($_tmpAry) == 2 )
1077
-		{
1078
-			// We may not really have a "Real Name"
1079
-			if ( $_tmpAry[0])
1080
-			$_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1075
+        // Do we have a "Real name"
1076
+        if ( count($_tmpAry) == 2 )
1077
+        {
1078
+            // We may not really have a "Real Name"
1079
+            if ( $_tmpAry[0])
1080
+            $_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1081 1081
 
1082
-			$_aryEmail['addr'] = $_tmpAry[1];
1083
-		}
1084
-		else
1085
-		$_aryEmail['addr'] = $_tmpAry[0];
1082
+            $_aryEmail['addr'] = $_tmpAry[1];
1083
+        }
1084
+        else
1085
+        $_aryEmail['addr'] = $_tmpAry[0];
1086 1086
 
1087
-		// Pull User Name and Host.tld apart
1088
-		list($_aryEmail['user'], $_aryEmail['host'] ) = explode('@', $_aryEmail['addr']);
1087
+        // Pull User Name and Host.tld apart
1088
+        list($_aryEmail['user'], $_aryEmail['host'] ) = explode('@', $_aryEmail['addr']);
1089 1089
 
1090
-		// Put the brackets back around the address
1091
-		$_aryEmail['addr'] = '<' . $_aryEmail['addr'] . '>';
1090
+        // Put the brackets back around the address
1091
+        $_aryEmail['addr'] = '<' . $_aryEmail['addr'] . '>';
1092 1092
 
1093
-		return $_aryEmail;
1094
-	}
1093
+        return $_aryEmail;
1094
+    }
1095 1095
 
1096 1096
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1097
-	/**
1098
-	 * Returns an array of bares addresses for use with 'RCPT TO:'
1099
-	 * This is a "build as you go" method. Each time this method is called
1100
-	 * the underlaying array is destroyed and reconstructed.
1101
-	 *
1102
-	 * @return 		array		Returns an array of bares addresses
1103
-	 */
1104
-	function get_RCPT_list()
1105
-	{
1097
+    /**
1098
+     * Returns an array of bares addresses for use with 'RCPT TO:'
1099
+     * This is a "build as you go" method. Each time this method is called
1100
+     * the underlaying array is destroyed and reconstructed.
1101
+     *
1102
+     * @return 		array		Returns an array of bares addresses
1103
+     */
1104
+    function get_RCPT_list()
1105
+    {
1106 1106
         // phpcs:enable
1107
-		/**
1108
-		 * An array of bares addresses for use with 'RCPT TO:'
1109
-		 */
1110
-		$_RCPT_list=array();
1111
-
1112
-		// walk down Recipients array and pull just email addresses
1113
-		foreach ( $this->_msgRecipients as $_host => $_list )
1114
-		{
1115
-			foreach ( $_list as $_subList )
1116
-			{
1117
-				foreach ( $_subList as $_name => $_addr )
1118
-				{
1119
-					// build RCPT list
1120
-					$_RCPT_list[] = $_name . '@' . $_host;
1121
-				}
1122
-			}
1123
-		}
1124
-
1125
-		return $_RCPT_list;
1126
-	}
1107
+        /**
1108
+         * An array of bares addresses for use with 'RCPT TO:'
1109
+         */
1110
+        $_RCPT_list=array();
1111
+
1112
+        // walk down Recipients array and pull just email addresses
1113
+        foreach ( $this->_msgRecipients as $_host => $_list )
1114
+        {
1115
+            foreach ( $_list as $_subList )
1116
+            {
1117
+                foreach ( $_subList as $_name => $_addr )
1118
+                {
1119
+                    // build RCPT list
1120
+                    $_RCPT_list[] = $_name . '@' . $_host;
1121
+                }
1122
+            }
1123
+        }
1124
+
1125
+        return $_RCPT_list;
1126
+    }
1127 1127
 
1128 1128
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1129
-	/**
1130
-	 * Returns an array of addresses for a specific type; TO, CC or BCC
1131
-	 *
1132
-	 * @param 		string 	       $_which 	    Which collection of addresses to return ('to', 'cc', 'bcc')
1133
-	 * @return 		string|false 				Array of emaill address
1134
-	 */
1135
-	function get_email_list($_which = null)
1136
-	{
1129
+    /**
1130
+     * Returns an array of addresses for a specific type; TO, CC or BCC
1131
+     *
1132
+     * @param 		string 	       $_which 	    Which collection of addresses to return ('to', 'cc', 'bcc')
1133
+     * @return 		string|false 				Array of emaill address
1134
+     */
1135
+    function get_email_list($_which = null)
1136
+    {
1137 1137
         // phpcs:enable
1138
-		// We need to know which address segment to pull
1139
-		if ( $_which )
1140
-		{
1141
-			// Make sure we have addresses to process
1142
-			if ( $this->_msgRecipients )
1143
-			{
1144
-				$_RCPT_list=array();
1145
-				// walk down Recipients array and pull just email addresses
1146
-				foreach ( $this->_msgRecipients as $_host => $_list )
1147
-				{
1148
-					if ( $this->_msgRecipients[$_host][$_which] )
1149
-					{
1150
-						foreach ( $this->_msgRecipients[$_host][$_which] as $_addr => $_realName )
1151
-						{
1152
-							if ( $_realName )	// @CHANGE LDR
1153
-							{
1154
-								$_realName = '"' . $_realName . '"';
1155
-								$_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>';
1156
-							}
1157
-							else
1158
-							{
1159
-								$_RCPT_list[] = $_addr . '@' . $_host;
1160
-							}
1161
-						}
1162
-					}
1163
-				}
1164
-
1165
-				return implode(', ', $_RCPT_list);
1166
-			}
1167
-			else
1168
-			{
1169
-				$this->_setErr(101, 'No eMail Address for message to be sent to.');
1170
-				return false;
1171
-			}
1172
-		}
1173
-		else
1174
-		{
1175
-			$this->_setErr(102, 'eMail type not defined.');
1176
-			return false;
1177
-		}
1178
-	}
1179
-
1180
-	/**
1181
-	 * TO Address[es] inwhich to send mail to
1182
-	 *
1183
-	 * @param 	string 	$_addrTo 	TO Address[es] inwhich to send mail to
1184
-	 * @return 	void
1185
-	 */
1186
-	function setTO($_addrTo)
1187
-	{
1188
-		if ( $_addrTo )
1189
-		$this->_buildAddrList('to', $_addrTo);
1190
-	}
1191
-
1192
-	/**
1193
-	 * Retrieves the TO Address[es] inwhich to send mail to
1194
-	 *
1195
-	 * @return 	string 	TO Address[es] inwhich to send mail to
1196
-	 */
1197
-	function getTo()
1198
-	{
1199
-		return $this->get_email_list('to');
1200
-	}
1201
-
1202
-	/**
1203
-	 * CC Address[es] inwhich to send mail to
1204
-	 *
1205
-	 * @param 	string	$_strCC		CC Address[es] inwhich to send mail to
1206
-	 * @return 	void
1207
-	 */
1208
-	function setCC($_strCC)
1209
-	{
1210
-		if ( $_strCC )
1211
-		$this->_buildAddrList('cc', $_strCC);
1212
-	}
1213
-
1214
-	/**
1215
-	 * Retrieves the CC Address[es] inwhich to send mail to
1216
-	 *
1217
-	 * @return 	string 		CC Address[es] inwhich to send mail to
1218
-	 */
1219
-	function getCC()
1220
-	{
1221
-		return $this->get_email_list('cc');
1222
-	}
1223
-
1224
-	/**
1225
-	 * BCC Address[es] inwhich to send mail to
1226
-	 *
1227
-	 * @param 	string		$_strBCC	Recipients BCC Address[es] inwhich to send mail to
1228
-	 * @return 	void
1229
-	 */
1230
-	function setBCC($_strBCC)
1231
-	{
1232
-		if ( $_strBCC )
1233
-		$this->_buildAddrList('bcc', $_strBCC);
1234
-	}
1235
-
1236
-	/**
1237
-	 * Retrieves the BCC Address[es] inwhich to send mail to
1238
-	 *
1239
-	 * @return 	string		BCC Address[es] inwhich to send mail to
1240
-	 */
1241
-	function getBCC()
1242
-	{
1243
-		return $this->get_email_list('bcc');
1244
-	}
1245
-
1246
-	/**
1247
-	 * Message Subject
1248
-	 *
1249
-	 * @param 	string 	$_strSubject	Message Subject
1250
-	 * @return 	void
1251
-	 */
1252
-	function setSubject($_strSubject = '')
1253
-	{
1254
-		if ( $_strSubject )
1255
-		$this->_msgSubject = $_strSubject;
1256
-	}
1257
-
1258
-	/**
1259
-	 * Retrieves the Message Subject
1260
-	 *
1261
-	 * @return 	string 		Message Subject
1262
-	 */
1263
-	function getSubject()
1264
-	{
1265
-		return $this->_msgSubject;
1266
-	}
1267
-
1268
-	/**
1269
-	 * Constructes and returns message header
1270
-	 *
1271
-	 * @return string Complete message header
1272
-	 */
1273
-	function getHeader()
1274
-	{
1275
-		global $conf;
1276
-
1277
-		$_header = 'From: '       . $this->getFrom('org') . "\r\n"
1278
-		. 'To: '         . $this->getTO()          . "\r\n";
1279
-
1280
-		if ( $this->getCC() )
1281
-		$_header .= 'Cc: ' . $this->getCC()  . "\r\n";
1282
-
1283
-		/* Note:
1138
+        // We need to know which address segment to pull
1139
+        if ( $_which )
1140
+        {
1141
+            // Make sure we have addresses to process
1142
+            if ( $this->_msgRecipients )
1143
+            {
1144
+                $_RCPT_list=array();
1145
+                // walk down Recipients array and pull just email addresses
1146
+                foreach ( $this->_msgRecipients as $_host => $_list )
1147
+                {
1148
+                    if ( $this->_msgRecipients[$_host][$_which] )
1149
+                    {
1150
+                        foreach ( $this->_msgRecipients[$_host][$_which] as $_addr => $_realName )
1151
+                        {
1152
+                            if ( $_realName )	// @CHANGE LDR
1153
+                            {
1154
+                                $_realName = '"' . $_realName . '"';
1155
+                                $_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>';
1156
+                            }
1157
+                            else
1158
+                            {
1159
+                                $_RCPT_list[] = $_addr . '@' . $_host;
1160
+                            }
1161
+                        }
1162
+                    }
1163
+                }
1164
+
1165
+                return implode(', ', $_RCPT_list);
1166
+            }
1167
+            else
1168
+            {
1169
+                $this->_setErr(101, 'No eMail Address for message to be sent to.');
1170
+                return false;
1171
+            }
1172
+        }
1173
+        else
1174
+        {
1175
+            $this->_setErr(102, 'eMail type not defined.');
1176
+            return false;
1177
+        }
1178
+    }
1179
+
1180
+    /**
1181
+     * TO Address[es] inwhich to send mail to
1182
+     *
1183
+     * @param 	string 	$_addrTo 	TO Address[es] inwhich to send mail to
1184
+     * @return 	void
1185
+     */
1186
+    function setTO($_addrTo)
1187
+    {
1188
+        if ( $_addrTo )
1189
+        $this->_buildAddrList('to', $_addrTo);
1190
+    }
1191
+
1192
+    /**
1193
+     * Retrieves the TO Address[es] inwhich to send mail to
1194
+     *
1195
+     * @return 	string 	TO Address[es] inwhich to send mail to
1196
+     */
1197
+    function getTo()
1198
+    {
1199
+        return $this->get_email_list('to');
1200
+    }
1201
+
1202
+    /**
1203
+     * CC Address[es] inwhich to send mail to
1204
+     *
1205
+     * @param 	string	$_strCC		CC Address[es] inwhich to send mail to
1206
+     * @return 	void
1207
+     */
1208
+    function setCC($_strCC)
1209
+    {
1210
+        if ( $_strCC )
1211
+        $this->_buildAddrList('cc', $_strCC);
1212
+    }
1213
+
1214
+    /**
1215
+     * Retrieves the CC Address[es] inwhich to send mail to
1216
+     *
1217
+     * @return 	string 		CC Address[es] inwhich to send mail to
1218
+     */
1219
+    function getCC()
1220
+    {
1221
+        return $this->get_email_list('cc');
1222
+    }
1223
+
1224
+    /**
1225
+     * BCC Address[es] inwhich to send mail to
1226
+     *
1227
+     * @param 	string		$_strBCC	Recipients BCC Address[es] inwhich to send mail to
1228
+     * @return 	void
1229
+     */
1230
+    function setBCC($_strBCC)
1231
+    {
1232
+        if ( $_strBCC )
1233
+        $this->_buildAddrList('bcc', $_strBCC);
1234
+    }
1235
+
1236
+    /**
1237
+     * Retrieves the BCC Address[es] inwhich to send mail to
1238
+     *
1239
+     * @return 	string		BCC Address[es] inwhich to send mail to
1240
+     */
1241
+    function getBCC()
1242
+    {
1243
+        return $this->get_email_list('bcc');
1244
+    }
1245
+
1246
+    /**
1247
+     * Message Subject
1248
+     *
1249
+     * @param 	string 	$_strSubject	Message Subject
1250
+     * @return 	void
1251
+     */
1252
+    function setSubject($_strSubject = '')
1253
+    {
1254
+        if ( $_strSubject )
1255
+        $this->_msgSubject = $_strSubject;
1256
+    }
1257
+
1258
+    /**
1259
+     * Retrieves the Message Subject
1260
+     *
1261
+     * @return 	string 		Message Subject
1262
+     */
1263
+    function getSubject()
1264
+    {
1265
+        return $this->_msgSubject;
1266
+    }
1267
+
1268
+    /**
1269
+     * Constructes and returns message header
1270
+     *
1271
+     * @return string Complete message header
1272
+     */
1273
+    function getHeader()
1274
+    {
1275
+        global $conf;
1276
+
1277
+        $_header = 'From: '       . $this->getFrom('org') . "\r\n"
1278
+        . 'To: '         . $this->getTO()          . "\r\n";
1279
+
1280
+        if ( $this->getCC() )
1281
+        $_header .= 'Cc: ' . $this->getCC()  . "\r\n";
1282
+
1283
+        /* Note:
1284 1284
 		 * BCC email addresses must be listed in the RCPT TO command list,
1285 1285
 		 * but the BCC header should not be printed under the DATA command.
1286 1286
 		 * So it is included into the function sendMsg() but not here.
1287 1287
 		 * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
1288 1288
 		 */
1289
-		/*
1289
+        /*
1290 1290
 		if ( $this->getBCC() )
1291 1291
 		$_header .= 'Bcc: ' . $this->getBCC()  . "\r\n";
1292 1292
         */
1293 1293
 
1294
-		$host=$this->getHost();
1295
-		$usetls = preg_match('@tls://@i',$host);
1296
-
1297
-		$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
1298
-		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
1299
-		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
1300
-
1301
-		$host=dol_getprefix('email');
1302
-
1303
-		//NOTE: Message-ID should probably contain the username of the user who sent the msg
1304
-		$_header .= 'Subject: '    . $this->getSubject()     . "\r\n";
1305
-		$_header .= 'Date: '       . date("r")               . "\r\n";
1306
-
1307
-		$trackid = $this->getTrackId();
1308
-		if ($trackid)
1309
-		{
1310
-			// References is kept in response and Message-ID is returned into In-Reply-To:
1311
-			$_header .= 'Message-ID: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1312
-			$_header .= 'References: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1313
-			$_header .= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host . "\r\n";
1314
-		}
1315
-		else
1316
-		{
1317
-			$_header .= 'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n";
1318
-		}
1319
-		if (! empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n";
1320
-		if ( $this->getMoreInHeader() )
1321
-		    $_header .= $this->getMoreInHeader();     // Value must include the "\r\n";
1322
-
1323
-		//$_header .=
1324
-		//                 'Read-Receipt-To: '   . $this->getFrom( 'org' ) . "\r\n"
1325
-		//                 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
1326
-
1327
-		if ( $this->getSensitivity() )
1328
-		$_header .= 'Sensitivity: ' . $this->getSensitivity()  . "\r\n";
1329
-
1330
-		if ( $this->_msgPriority != 3 )
1331
-		$_header .= $this->getPriority();
1332
-
1333
-
1334
-		// @CHANGE LDR
1335
-		if ( $this->getDeliveryReceipt() )
1336
-		    $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n";
1337
-		if ( $this->getErrorsTo() )
1338
-		    $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n";
1339
-		if ( $this->getReplyTo() )
1340
-		    $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n";
1341
-
1342
-		$_header .= 'X-Mailer: Dolibarr version ' . DOL_VERSION .' (using SMTPs Mailer)' . "\r\n";
1343
-		$_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART?'MAIN_MAIL_USE_MULTI_PART':'No MAIN_MAIL_USE_MULTI_PART') . "\r\n";
1344
-		$_header .= 'Mime-Version: 1.0' . "\r\n";
1345
-
1346
-
1347
-		return $_header;
1348
-	}
1349
-
1350
-	/**
1351
-	 * Message Content
1352
-	 *
1353
-	 * @param 	string 	$strContent		Message Content
1354
-	 * @param	string	$strType		Type
1355
-	 * @return 	void
1356
-	 */
1357
-	function setBodyContent($strContent, $strType = 'plain')
1358
-	{
1359
-		//if ( $strContent )
1360
-		//{
1361
-		if ( $strType == 'html' )
1362
-		$strMimeType = 'text/html';
1363
-		else
1364
-		$strMimeType = 'text/plain';
1365
-
1366
-		// Make RFC821 Compliant, replace bare linefeeds
1367
-		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent);
1368
-
1369
-		$strContentAltText = '';
1370
-		if ($strType == 'html')
1371
-		{
1372
-			// Similar code to forge a text from html is also in CMailFile.class.php
1373
-			$strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1374
-			$strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1375
-			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n"));
1376
-		}
1377
-
1378
-		// Make RFC2045 Compliant
1379
-		//$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1380
-		$strContent = rtrim(wordwrap($strContent, 75, "\r\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1381
-
1382
-		$this->_msgContent[$strType] = array();
1383
-
1384
-		$this->_msgContent[$strType]['mimeType'] = $strMimeType;
1385
-		$this->_msgContent[$strType]['data']     = $strContent;
1386
-		$this->_msgContent[$strType]['dataText'] = $strContentAltText;
1387
-
1388
-		if ( $this->getMD5flag() )
1389
-		$this->_msgContent[$strType]['md5']      = dol_hash($strContent, 3);
1390
-		//}
1391
-	}
1392
-
1393
-	/**
1394
-	 * Retrieves the Message Content
1395
-	 *
1396
-	 * @return 	string			Message Content
1397
-	 */
1398
-	function getBodyContent()
1399
-	{
1400
-	    global $conf;
1401
-
1402
-		// Generate a new Boundary string
1403
-		$this->_setBoundary();
1404
-
1405
-		// What type[s] of content do we have
1406
-		$_types = array_keys($this->_msgContent);
1407
-
1408
-		// How many content types do we have
1409
-		$keyCount = count($_types);
1410
-
1411
-		// If we have ZERO, we have a problem
1412
-		if( $keyCount === 0 )
1413
-		die ("Sorry, no content");
1414
-
1415
-		// If we have ONE, we can use the simple format
1416
-		else if( $keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1417
-		{
1418
-			$_msgData = $this->_msgContent;
1419
-			$_msgData = $_msgData[$_types[0]];
1420
-
1421
-			$content = 'Content-Type: ' . $_msgData['mimeType'] . '; charset="' . $this->getCharSet() . '"' . "\r\n"
1422
-			. 'Content-Transfer-Encoding: ' . $this->getTransEncodeType() . "\r\n"
1423
-			. 'Content-Disposition: inline'  . "\r\n"
1424
-			. 'Content-Description: Message' . "\r\n";
1425
-
1426
-			if ( $this->getMD5flag() )
1427
-			$content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
1428
-
1429
-			$content .= "\r\n"
1430
-			.  $_msgData['data'] . "\r\n";
1431
-		}
1432
-
1433
-		// If we have more than ONE, we use the multi-part format
1434
-		else if( $keyCount >= 1 || ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1435
-		{
1436
-			// Since this is an actual multi-part message
1437
-			// We need to define a content message Boundary
1438
-			// NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
1439
-
1440
-			//$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"'   . "\r\n";
1441
-			$content = 'Content-Type: multipart/mixed; boundary="' . $this->_getBoundary('mixed') . '"'   . "\r\n";
1442
-
1443
-			//                     . "\r\n"
1444
-			//                     . 'This is a multi-part message in MIME format.' . "\r\n";
1445
-			$content .= "Content-Transfer-Encoding: 8bit\r\n";
1446
-			$content .= "\r\n";
1447
-
1448
-			$content .= "--" . $this->_getBoundary('mixed') . "\r\n";
1449
-
1450
-			if (key_exists('image', $this->_msgContent))     // If inline image found
1451
-			{
1452
-				$content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1453
-				$content .= "\r\n";
1454
-				$content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1455
-			}
1456
-
1457
-
1458
-			// $this->_msgContent must be sorted with key 'text' or 'html' first then 'image' then 'attachment'
1459
-
1460
-
1461
-			// Loop through message content array
1462
-			foreach ($this->_msgContent as $type => $_content )
1463
-			{
1464
-				if ( $type == 'attachment' )
1465
-				{
1466
-					// loop through all attachments
1467
-					foreach ( $_content as $_file => $_data )
1468
-					{
1469
-						$content .= "--" . $this->_getBoundary('mixed') . "\r\n"
1470
-						.  'Content-Disposition: attachment; filename="' . $_data['fileName'] . '"' . "\r\n"
1471
-						.  'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['fileName'] . '"' . "\r\n"
1472
-						.  'Content-Transfer-Encoding: base64' . "\r\n"
1473
-						.  'Content-Description: ' . $_data['fileName'] ."\r\n";
1474
-
1475
-						if ( $this->getMD5flag() )
1476
-						$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1477
-
1478
-						$content .= "\r\n" .  $_data['data'] . "\r\n\r\n";
1479
-					}
1480
-				}
1481
-				// @CHANGE LDR
1482
-				else if ( $type == 'image' )
1483
-				{
1484
-					// loop through all images
1485
-					foreach ( $_content as $_image => $_data )
1486
-					{
1487
-						$content .= "--" . $this->_getBoundary('related') . "\r\n";  // always related for an inline image
1488
-
1489
-						$content .= 'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['imageName'] . '"' . "\r\n"
1490
-						.  'Content-Transfer-Encoding: base64' . "\r\n"
1491
-						.  'Content-Disposition: inline; filename="' . $_data['imageName'] . '"' . "\r\n"
1492
-						.  'Content-ID: <' . $_data['cid'] . '> ' . "\r\n";
1493
-
1494
-						if ( $this->getMD5flag() )
1495
-						$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1496
-
1497
-						$content .= "\r\n"
1498
-						. $_data['data'] . "\r\n";
1499
-					}
1500
-
1501
-					// always end related and end alternative after inline images
1502
-					$content.= "--" . $this->_getBoundary('related') . "--" . "\r\n";
1503
-					$content.= "\r\n" . "--" . $this->_getBoundary('alternative') . "--" . "\r\n";
1504
-					$content.= "\r\n";
1505
-				}
1506
-				else
1507
-				{
1508
-					if (key_exists('image', $this->_msgContent))
1509
-					{
1510
-						$content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
1511
-						$content.= "\r\n" . ($_content['dataText']?$_content['dataText']:strip_tags($_content['data'])) . "\r\n"; // Add plain text message
1512
-						$content.= "--" . $this->_getBoundary('alternative') . "\r\n";
1513
-						$content.= 'Content-Type: multipart/related; boundary="' . $this->_getBoundary('related') . '"' . "\r\n";
1514
-						$content.= "\r\n";
1515
-						$content.= "--" . $this->_getBoundary('related') . "\r\n";
1516
-					}
1517
-
1518
-					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
1519
-					{
1520
-					    $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1521
-    					$content .= "\r\n";
1522
-	       				$content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1523
-
1524
-	       				$content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
1525
-	       				$content.= "\r\n". $_content['dataText'] . "\r\n";
1526
-	       				$content.= "--" . $this->_getBoundary('alternative') . "\r\n";
1527
-					}
1528
-
1529
-					$content .= 'Content-Type: ' . $_content['mimeType'] . '; '
1530
-					//                             . 'charset="' . $this->getCharSet() . '"';
1531
-					. 'charset=' . $this->getCharSet() . '';
1532
-
1533
-					//                    $content .= ( $type == 'html') ? '; name="HTML Part"' : '';
1534
-					$content .=  "\r\n";
1535
-					//                    $content .= 'Content-Transfer-Encoding: ';
1536
-					//                    $content .= ($type == 'html') ? 'quoted-printable' : $this->getTransEncodeType();
1537
-					//                    $content .=  "\r\n"
1538
-					//                             . 'Content-Disposition: inline'  . "\r\n"
1539
-					//                             . 'Content-Description: ' . $type . ' message' . "\r\n";
1540
-
1541
-					if ( $this->getMD5flag() )
1542
-					$content .= 'Content-MD5: ' . $_content['md5'] . "\r\n";
1543
-
1544
-					$content .= "\r\n"	. $_content['data'] . "\r\n";
1545
-
1546
-					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
1547
-					{
1548
-					    $content.= "--" . $this->_getBoundary('alternative') . "--". "\r\n";
1549
-					}
1550
-
1551
-					$content .= "\r\n";
1552
-				}
1553
-			}
1554
-
1555
-			// Close message boundries
1556
-			//            $content .= "\r\n--" . $this->_getBoundary() . '--' . "\r\n" ;
1557
-			$content .= "--" . $this->_getBoundary('mixed') . '--' . "\r\n" ;
1558
-		}
1559
-
1560
-		return $content;
1561
-	}
1562
-
1563
-	/**
1564
-	 * File attachments are added to the content array as sub-arrays,
1565
-	 * allowing for multiple attachments for each outbound email
1566
-	 *
1567
-	 * @param string $strContent  File data to attach to message
1568
-	 * @param string $strFileName File Name to give to attachment
1569
-	 * @param string $strMimeType File Mime Type of attachment
1570
-	 * @return void
1571
-	 */
1572
-	function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown')
1573
-	{
1574
-		if ( $strContent )
1575
-		{
1576
-			$strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n"));    // 76 max is defined into http://tools.ietf.org/html/rfc2047
1577
-
1578
-			$this->_msgContent['attachment'][$strFileName]['mimeType'] = $strMimeType;
1579
-			$this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName;
1580
-			$this->_msgContent['attachment'][$strFileName]['data']     = $strContent;
1581
-
1582
-			if ( $this->getMD5flag() )
1583
-			$this->_msgContent['attachment'][$strFileName]['md5']      = dol_hash($strContent, 3);
1584
-		}
1585
-	}
1586
-
1587
-
1588
-	// @CHANGE LDR
1589
-
1590
-	/**
1591
-	 * Image attachments are added to the content array as sub-arrays,
1592
-	 * allowing for multiple images for each outbound email
1593
-	 *
1594
-	 * @param 	string $strContent  	Image data to attach to message
1595
-	 * @param 	string $strImageName 	Image Name to give to attachment
1596
-	 * @param 	string $strMimeType 	Image Mime Type of attachment
1597
-	 * @param 	string $strImageCid		CID
1598
-	 * @return 	void
1599
-	 */
1600
-	function setImageInline($strContent, $strImageName = 'unknown', $strMimeType = 'unknown', $strImageCid = 'unknown')
1601
-	{
1602
-		if ($strContent)
1603
-		{
1604
-			$this->_msgContent['image'][$strImageName]['mimeType'] = $strMimeType;
1605
-			$this->_msgContent['image'][$strImageName]['imageName'] = $strImageName;
1606
-			$this->_msgContent['image'][$strImageName]['cid']      = $strImageCid;
1607
-			$this->_msgContent['image'][$strImageName]['data']     = $strContent;
1608
-
1609
-			if ( $this->getMD5flag() )
1610
-			$this->_msgContent['image'][$strImageName]['md5']      = dol_hash($strContent, 3);
1611
-		}
1612
-	}
1613
-	// END @CHANGE LDR
1614
-
1615
-
1616
-	/**
1617
-	 * Message Content Sensitivity
1618
-	 * Message Sensitivity values:
1619
-	 *   - [0] None - default
1620
-	 *   - [1] Personal
1621
-	 *   - [2] Private
1622
-	 *   - [3] Company Confidential
1623
-	 *
1624
-	 * @param 	integer	$_value		Message Sensitivity
1625
-	 * @return 	void
1626
-	 */
1627
-	function setSensitivity($_value = 0)
1628
-	{
1629
-		if ( ( is_numeric($_value) ) &&
1630
-		( ( $_value >= 0 ) && ( $_value <= 3 ) ) )
1631
-		$this->_msgSensitivity = $_value;
1632
-	}
1633
-
1634
-	/**
1635
-	 * Returns Message Content Sensitivity string
1636
-	 * Message Sensitivity values:
1637
-	 *   - [0] None - default
1638
-	 *   - [1] Personal
1639
-	 *   - [2] Private
1640
-	 *   - [3] Company Confidential
1641
-	 *
1642
-	 * @return 	void
1643
-	 */
1644
-	function getSensitivity()
1645
-	{
1646
-		return $this->_arySensitivity[$this->_msgSensitivity];
1647
-	}
1648
-
1649
-	/**
1650
-	 * Message Content Priority
1651
-	 * Message Priority values:
1652
-	 *  - [0] 'Bulk'
1653
-	 *  - [1] 'Highest'
1654
-	 *  - [2] 'High'
1655
-	 *  - [3] 'Normal' - default
1656
-	 *  - [4] 'Low'
1657
-	 *  - [5] 'Lowest'
1658
-	 *
1659
-	 * @param 	integer 	$_value 	Message Priority
1660
-	 * @return 	void
1661
-	 */
1662
-	function setPriority( $_value = 3 )
1663
-	{
1664
-		if ( ( is_numeric($_value) ) &&
1665
-		( ( $_value >= 0 ) && ( $_value <= 5 ) ) )
1666
-		$this->_msgPriority = $_value;
1667
-	}
1668
-
1669
-	/**
1670
-	 * Message Content Priority
1671
-	 * Message Priority values:
1672
-	 *  - [0] 'Bulk'
1673
-	 *  - [1] 'Highest'
1674
-	 *  - [2] 'High'
1675
-	 *  - [3] 'Normal' - default
1676
-	 *  - [4] 'Low'
1677
-	 *  - [5] 'Lowest'
1678
-	 *
1679
-	 * @return string
1680
-	 */
1681
-	function getPriority()
1682
-	{
1683
-		return 'Importance: ' . $this->_aryPriority[$this->_msgPriority] . "\r\n"
1684
-		. 'Priority: '   . $this->_aryPriority[$this->_msgPriority] . "\r\n"
1685
-		. 'X-Priority: ' . $this->_msgPriority . ' (' . $this->_aryPriority[$this->_msgPriority] . ')' . "\r\n";
1686
-	}
1687
-
1688
-	/**
1689
-	 * Set flag which determines whether to calculate message MD5 checksum.
1690
-	 *
1691
-	 * @param 	string 	$_flag		Message Priority
1692
-	 * @return 	void
1693
-	 */
1694
-	function setMD5flag($_flag = false)
1695
-	{
1696
-		$this->_smtpMD5 = $_flag;
1697
-	}
1698
-
1699
-	/**
1700
-	 * Gets flag which determines whether to calculate message MD5 checksum.
1701
-	 *
1702
-	 * @return 	boolean 				Message Priority
1703
-	 */
1704
-	function getMD5flag()
1705
-	{
1706
-		return $this->_smtpMD5;
1707
-	}
1708
-
1709
-	/**
1710
-	 * Message X-Header Content
1711
-	 * This is a simple "insert". Whatever is given will be placed
1712
-	 * "as is" into the Xheader array.
1713
-	 *
1714
-	 * @param string $strXdata Message X-Header Content
1715
-	 * @return void
1716
-	 */
1717
-	function setXheader($strXdata)
1718
-	{
1719
-		if ( $strXdata )
1720
-		$this->_msgXheader[] = $strXdata;
1721
-	}
1722
-
1723
-	/**
1724
-	 * Retrieves the Message X-Header Content
1725
-	 *
1726
-	 * @return string[] $_msgContent Message X-Header Content
1727
-	 */
1728
-	function getXheader()
1729
-	{
1730
-		return $this->_msgXheader;
1731
-	}
1732
-
1733
-	/**
1734
-	 * Generates Random string for MIME message Boundary
1735
-	 *
1736
-	 * @return void
1737
-	 */
1738
-	function _setBoundary()
1739
-	{
1740
-		$this->_smtpsBoundary = "multipart_x." . time() . ".x_boundary";
1741
-		$this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);
1742
-		$this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);
1743
-	}
1744
-
1745
-	/**
1746
-	 * Retrieves the MIME message Boundary
1747
-	 *
1748
-	 * @param  string $type				Type of boundary
1749
-	 * @return string $_smtpsBoundary 	MIME message Boundary
1750
-	 */
1751
-	function _getBoundary($type='mixed')
1752
-	{
1753
-		if ($type == 'mixed') return $this->_smtpsBoundary;
1754
-		else if ($type == 'related') return $this->_smtpsRelatedBoundary;
1755
-		else if ($type == 'alternative') return $this->_smtpsAlternativeBoundary;
1756
-	}
1294
+        $host=$this->getHost();
1295
+        $usetls = preg_match('@tls://@i',$host);
1296
+
1297
+        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
1298
+        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
1299
+        $host=preg_replace('@tls://@i','',$host);	// Remove prefix
1300
+
1301
+        $host=dol_getprefix('email');
1302
+
1303
+        //NOTE: Message-ID should probably contain the username of the user who sent the msg
1304
+        $_header .= 'Subject: '    . $this->getSubject()     . "\r\n";
1305
+        $_header .= 'Date: '       . date("r")               . "\r\n";
1306
+
1307
+        $trackid = $this->getTrackId();
1308
+        if ($trackid)
1309
+        {
1310
+            // References is kept in response and Message-ID is returned into In-Reply-To:
1311
+            $_header .= 'Message-ID: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1312
+            $_header .= 'References: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1313
+            $_header .= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host . "\r\n";
1314
+        }
1315
+        else
1316
+        {
1317
+            $_header .= 'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n";
1318
+        }
1319
+        if (! empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n";
1320
+        if ( $this->getMoreInHeader() )
1321
+            $_header .= $this->getMoreInHeader();     // Value must include the "\r\n";
1322
+
1323
+        //$_header .=
1324
+        //                 'Read-Receipt-To: '   . $this->getFrom( 'org' ) . "\r\n"
1325
+        //                 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
1326
+
1327
+        if ( $this->getSensitivity() )
1328
+        $_header .= 'Sensitivity: ' . $this->getSensitivity()  . "\r\n";
1329
+
1330
+        if ( $this->_msgPriority != 3 )
1331
+        $_header .= $this->getPriority();
1332
+
1333
+
1334
+        // @CHANGE LDR
1335
+        if ( $this->getDeliveryReceipt() )
1336
+            $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n";
1337
+        if ( $this->getErrorsTo() )
1338
+            $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n";
1339
+        if ( $this->getReplyTo() )
1340
+            $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n";
1341
+
1342
+        $_header .= 'X-Mailer: Dolibarr version ' . DOL_VERSION .' (using SMTPs Mailer)' . "\r\n";
1343
+        $_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART?'MAIN_MAIL_USE_MULTI_PART':'No MAIN_MAIL_USE_MULTI_PART') . "\r\n";
1344
+        $_header .= 'Mime-Version: 1.0' . "\r\n";
1345
+
1346
+
1347
+        return $_header;
1348
+    }
1349
+
1350
+    /**
1351
+     * Message Content
1352
+     *
1353
+     * @param 	string 	$strContent		Message Content
1354
+     * @param	string	$strType		Type
1355
+     * @return 	void
1356
+     */
1357
+    function setBodyContent($strContent, $strType = 'plain')
1358
+    {
1359
+        //if ( $strContent )
1360
+        //{
1361
+        if ( $strType == 'html' )
1362
+        $strMimeType = 'text/html';
1363
+        else
1364
+        $strMimeType = 'text/plain';
1365
+
1366
+        // Make RFC821 Compliant, replace bare linefeeds
1367
+        $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent);
1368
+
1369
+        $strContentAltText = '';
1370
+        if ($strType == 'html')
1371
+        {
1372
+            // Similar code to forge a text from html is also in CMailFile.class.php
1373
+            $strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1374
+            $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1375
+            $strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n"));
1376
+        }
1377
+
1378
+        // Make RFC2045 Compliant
1379
+        //$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1380
+        $strContent = rtrim(wordwrap($strContent, 75, "\r\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1381
+
1382
+        $this->_msgContent[$strType] = array();
1383
+
1384
+        $this->_msgContent[$strType]['mimeType'] = $strMimeType;
1385
+        $this->_msgContent[$strType]['data']     = $strContent;
1386
+        $this->_msgContent[$strType]['dataText'] = $strContentAltText;
1387
+
1388
+        if ( $this->getMD5flag() )
1389
+        $this->_msgContent[$strType]['md5']      = dol_hash($strContent, 3);
1390
+        //}
1391
+    }
1392
+
1393
+    /**
1394
+     * Retrieves the Message Content
1395
+     *
1396
+     * @return 	string			Message Content
1397
+     */
1398
+    function getBodyContent()
1399
+    {
1400
+        global $conf;
1401
+
1402
+        // Generate a new Boundary string
1403
+        $this->_setBoundary();
1404
+
1405
+        // What type[s] of content do we have
1406
+        $_types = array_keys($this->_msgContent);
1407
+
1408
+        // How many content types do we have
1409
+        $keyCount = count($_types);
1410
+
1411
+        // If we have ZERO, we have a problem
1412
+        if( $keyCount === 0 )
1413
+        die ("Sorry, no content");
1414
+
1415
+        // If we have ONE, we can use the simple format
1416
+        else if( $keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1417
+        {
1418
+            $_msgData = $this->_msgContent;
1419
+            $_msgData = $_msgData[$_types[0]];
1420
+
1421
+            $content = 'Content-Type: ' . $_msgData['mimeType'] . '; charset="' . $this->getCharSet() . '"' . "\r\n"
1422
+            . 'Content-Transfer-Encoding: ' . $this->getTransEncodeType() . "\r\n"
1423
+            . 'Content-Disposition: inline'  . "\r\n"
1424
+            . 'Content-Description: Message' . "\r\n";
1425
+
1426
+            if ( $this->getMD5flag() )
1427
+            $content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
1428
+
1429
+            $content .= "\r\n"
1430
+            .  $_msgData['data'] . "\r\n";
1431
+        }
1432
+
1433
+        // If we have more than ONE, we use the multi-part format
1434
+        else if( $keyCount >= 1 || ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1435
+        {
1436
+            // Since this is an actual multi-part message
1437
+            // We need to define a content message Boundary
1438
+            // NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
1439
+
1440
+            //$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"'   . "\r\n";
1441
+            $content = 'Content-Type: multipart/mixed; boundary="' . $this->_getBoundary('mixed') . '"'   . "\r\n";
1442
+
1443
+            //                     . "\r\n"
1444
+            //                     . 'This is a multi-part message in MIME format.' . "\r\n";
1445
+            $content .= "Content-Transfer-Encoding: 8bit\r\n";
1446
+            $content .= "\r\n";
1447
+
1448
+            $content .= "--" . $this->_getBoundary('mixed') . "\r\n";
1449
+
1450
+            if (key_exists('image', $this->_msgContent))     // If inline image found
1451
+            {
1452
+                $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1453
+                $content .= "\r\n";
1454
+                $content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1455
+            }
1456
+
1457
+
1458
+            // $this->_msgContent must be sorted with key 'text' or 'html' first then 'image' then 'attachment'
1459
+
1460
+
1461
+            // Loop through message content array
1462
+            foreach ($this->_msgContent as $type => $_content )
1463
+            {
1464
+                if ( $type == 'attachment' )
1465
+                {
1466
+                    // loop through all attachments
1467
+                    foreach ( $_content as $_file => $_data )
1468
+                    {
1469
+                        $content .= "--" . $this->_getBoundary('mixed') . "\r\n"
1470
+                        .  'Content-Disposition: attachment; filename="' . $_data['fileName'] . '"' . "\r\n"
1471
+                        .  'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['fileName'] . '"' . "\r\n"
1472
+                        .  'Content-Transfer-Encoding: base64' . "\r\n"
1473
+                        .  'Content-Description: ' . $_data['fileName'] ."\r\n";
1474
+
1475
+                        if ( $this->getMD5flag() )
1476
+                        $content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1477
+
1478
+                        $content .= "\r\n" .  $_data['data'] . "\r\n\r\n";
1479
+                    }
1480
+                }
1481
+                // @CHANGE LDR
1482
+                else if ( $type == 'image' )
1483
+                {
1484
+                    // loop through all images
1485
+                    foreach ( $_content as $_image => $_data )
1486
+                    {
1487
+                        $content .= "--" . $this->_getBoundary('related') . "\r\n";  // always related for an inline image
1488
+
1489
+                        $content .= 'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['imageName'] . '"' . "\r\n"
1490
+                        .  'Content-Transfer-Encoding: base64' . "\r\n"
1491
+                        .  'Content-Disposition: inline; filename="' . $_data['imageName'] . '"' . "\r\n"
1492
+                        .  'Content-ID: <' . $_data['cid'] . '> ' . "\r\n";
1493
+
1494
+                        if ( $this->getMD5flag() )
1495
+                        $content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1496
+
1497
+                        $content .= "\r\n"
1498
+                        . $_data['data'] . "\r\n";
1499
+                    }
1500
+
1501
+                    // always end related and end alternative after inline images
1502
+                    $content.= "--" . $this->_getBoundary('related') . "--" . "\r\n";
1503
+                    $content.= "\r\n" . "--" . $this->_getBoundary('alternative') . "--" . "\r\n";
1504
+                    $content.= "\r\n";
1505
+                }
1506
+                else
1507
+                {
1508
+                    if (key_exists('image', $this->_msgContent))
1509
+                    {
1510
+                        $content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
1511
+                        $content.= "\r\n" . ($_content['dataText']?$_content['dataText']:strip_tags($_content['data'])) . "\r\n"; // Add plain text message
1512
+                        $content.= "--" . $this->_getBoundary('alternative') . "\r\n";
1513
+                        $content.= 'Content-Type: multipart/related; boundary="' . $this->_getBoundary('related') . '"' . "\r\n";
1514
+                        $content.= "\r\n";
1515
+                        $content.= "--" . $this->_getBoundary('related') . "\r\n";
1516
+                    }
1517
+
1518
+                    if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
1519
+                    {
1520
+                        $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1521
+                        $content .= "\r\n";
1522
+                            $content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1523
+
1524
+                            $content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
1525
+                            $content.= "\r\n". $_content['dataText'] . "\r\n";
1526
+                            $content.= "--" . $this->_getBoundary('alternative') . "\r\n";
1527
+                    }
1528
+
1529
+                    $content .= 'Content-Type: ' . $_content['mimeType'] . '; '
1530
+                    //                             . 'charset="' . $this->getCharSet() . '"';
1531
+                    . 'charset=' . $this->getCharSet() . '';
1532
+
1533
+                    //                    $content .= ( $type == 'html') ? '; name="HTML Part"' : '';
1534
+                    $content .=  "\r\n";
1535
+                    //                    $content .= 'Content-Transfer-Encoding: ';
1536
+                    //                    $content .= ($type == 'html') ? 'quoted-printable' : $this->getTransEncodeType();
1537
+                    //                    $content .=  "\r\n"
1538
+                    //                             . 'Content-Disposition: inline'  . "\r\n"
1539
+                    //                             . 'Content-Description: ' . $type . ' message' . "\r\n";
1540
+
1541
+                    if ( $this->getMD5flag() )
1542
+                    $content .= 'Content-MD5: ' . $_content['md5'] . "\r\n";
1543
+
1544
+                    $content .= "\r\n"	. $_content['data'] . "\r\n";
1545
+
1546
+                    if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
1547
+                    {
1548
+                        $content.= "--" . $this->_getBoundary('alternative') . "--". "\r\n";
1549
+                    }
1550
+
1551
+                    $content .= "\r\n";
1552
+                }
1553
+            }
1554
+
1555
+            // Close message boundries
1556
+            //            $content .= "\r\n--" . $this->_getBoundary() . '--' . "\r\n" ;
1557
+            $content .= "--" . $this->_getBoundary('mixed') . '--' . "\r\n" ;
1558
+        }
1559
+
1560
+        return $content;
1561
+    }
1562
+
1563
+    /**
1564
+     * File attachments are added to the content array as sub-arrays,
1565
+     * allowing for multiple attachments for each outbound email
1566
+     *
1567
+     * @param string $strContent  File data to attach to message
1568
+     * @param string $strFileName File Name to give to attachment
1569
+     * @param string $strMimeType File Mime Type of attachment
1570
+     * @return void
1571
+     */
1572
+    function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown')
1573
+    {
1574
+        if ( $strContent )
1575
+        {
1576
+            $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n"));    // 76 max is defined into http://tools.ietf.org/html/rfc2047
1577
+
1578
+            $this->_msgContent['attachment'][$strFileName]['mimeType'] = $strMimeType;
1579
+            $this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName;
1580
+            $this->_msgContent['attachment'][$strFileName]['data']     = $strContent;
1581
+
1582
+            if ( $this->getMD5flag() )
1583
+            $this->_msgContent['attachment'][$strFileName]['md5']      = dol_hash($strContent, 3);
1584
+        }
1585
+    }
1586
+
1587
+
1588
+    // @CHANGE LDR
1589
+
1590
+    /**
1591
+     * Image attachments are added to the content array as sub-arrays,
1592
+     * allowing for multiple images for each outbound email
1593
+     *
1594
+     * @param 	string $strContent  	Image data to attach to message
1595
+     * @param 	string $strImageName 	Image Name to give to attachment
1596
+     * @param 	string $strMimeType 	Image Mime Type of attachment
1597
+     * @param 	string $strImageCid		CID
1598
+     * @return 	void
1599
+     */
1600
+    function setImageInline($strContent, $strImageName = 'unknown', $strMimeType = 'unknown', $strImageCid = 'unknown')
1601
+    {
1602
+        if ($strContent)
1603
+        {
1604
+            $this->_msgContent['image'][$strImageName]['mimeType'] = $strMimeType;
1605
+            $this->_msgContent['image'][$strImageName]['imageName'] = $strImageName;
1606
+            $this->_msgContent['image'][$strImageName]['cid']      = $strImageCid;
1607
+            $this->_msgContent['image'][$strImageName]['data']     = $strContent;
1608
+
1609
+            if ( $this->getMD5flag() )
1610
+            $this->_msgContent['image'][$strImageName]['md5']      = dol_hash($strContent, 3);
1611
+        }
1612
+    }
1613
+    // END @CHANGE LDR
1614
+
1615
+
1616
+    /**
1617
+     * Message Content Sensitivity
1618
+     * Message Sensitivity values:
1619
+     *   - [0] None - default
1620
+     *   - [1] Personal
1621
+     *   - [2] Private
1622
+     *   - [3] Company Confidential
1623
+     *
1624
+     * @param 	integer	$_value		Message Sensitivity
1625
+     * @return 	void
1626
+     */
1627
+    function setSensitivity($_value = 0)
1628
+    {
1629
+        if ( ( is_numeric($_value) ) &&
1630
+        ( ( $_value >= 0 ) && ( $_value <= 3 ) ) )
1631
+        $this->_msgSensitivity = $_value;
1632
+    }
1633
+
1634
+    /**
1635
+     * Returns Message Content Sensitivity string
1636
+     * Message Sensitivity values:
1637
+     *   - [0] None - default
1638
+     *   - [1] Personal
1639
+     *   - [2] Private
1640
+     *   - [3] Company Confidential
1641
+     *
1642
+     * @return 	void
1643
+     */
1644
+    function getSensitivity()
1645
+    {
1646
+        return $this->_arySensitivity[$this->_msgSensitivity];
1647
+    }
1648
+
1649
+    /**
1650
+     * Message Content Priority
1651
+     * Message Priority values:
1652
+     *  - [0] 'Bulk'
1653
+     *  - [1] 'Highest'
1654
+     *  - [2] 'High'
1655
+     *  - [3] 'Normal' - default
1656
+     *  - [4] 'Low'
1657
+     *  - [5] 'Lowest'
1658
+     *
1659
+     * @param 	integer 	$_value 	Message Priority
1660
+     * @return 	void
1661
+     */
1662
+    function setPriority( $_value = 3 )
1663
+    {
1664
+        if ( ( is_numeric($_value) ) &&
1665
+        ( ( $_value >= 0 ) && ( $_value <= 5 ) ) )
1666
+        $this->_msgPriority = $_value;
1667
+    }
1668
+
1669
+    /**
1670
+     * Message Content Priority
1671
+     * Message Priority values:
1672
+     *  - [0] 'Bulk'
1673
+     *  - [1] 'Highest'
1674
+     *  - [2] 'High'
1675
+     *  - [3] 'Normal' - default
1676
+     *  - [4] 'Low'
1677
+     *  - [5] 'Lowest'
1678
+     *
1679
+     * @return string
1680
+     */
1681
+    function getPriority()
1682
+    {
1683
+        return 'Importance: ' . $this->_aryPriority[$this->_msgPriority] . "\r\n"
1684
+        . 'Priority: '   . $this->_aryPriority[$this->_msgPriority] . "\r\n"
1685
+        . 'X-Priority: ' . $this->_msgPriority . ' (' . $this->_aryPriority[$this->_msgPriority] . ')' . "\r\n";
1686
+    }
1687
+
1688
+    /**
1689
+     * Set flag which determines whether to calculate message MD5 checksum.
1690
+     *
1691
+     * @param 	string 	$_flag		Message Priority
1692
+     * @return 	void
1693
+     */
1694
+    function setMD5flag($_flag = false)
1695
+    {
1696
+        $this->_smtpMD5 = $_flag;
1697
+    }
1698
+
1699
+    /**
1700
+     * Gets flag which determines whether to calculate message MD5 checksum.
1701
+     *
1702
+     * @return 	boolean 				Message Priority
1703
+     */
1704
+    function getMD5flag()
1705
+    {
1706
+        return $this->_smtpMD5;
1707
+    }
1708
+
1709
+    /**
1710
+     * Message X-Header Content
1711
+     * This is a simple "insert". Whatever is given will be placed
1712
+     * "as is" into the Xheader array.
1713
+     *
1714
+     * @param string $strXdata Message X-Header Content
1715
+     * @return void
1716
+     */
1717
+    function setXheader($strXdata)
1718
+    {
1719
+        if ( $strXdata )
1720
+        $this->_msgXheader[] = $strXdata;
1721
+    }
1722
+
1723
+    /**
1724
+     * Retrieves the Message X-Header Content
1725
+     *
1726
+     * @return string[] $_msgContent Message X-Header Content
1727
+     */
1728
+    function getXheader()
1729
+    {
1730
+        return $this->_msgXheader;
1731
+    }
1732
+
1733
+    /**
1734
+     * Generates Random string for MIME message Boundary
1735
+     *
1736
+     * @return void
1737
+     */
1738
+    function _setBoundary()
1739
+    {
1740
+        $this->_smtpsBoundary = "multipart_x." . time() . ".x_boundary";
1741
+        $this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);
1742
+        $this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);
1743
+    }
1744
+
1745
+    /**
1746
+     * Retrieves the MIME message Boundary
1747
+     *
1748
+     * @param  string $type				Type of boundary
1749
+     * @return string $_smtpsBoundary 	MIME message Boundary
1750
+     */
1751
+    function _getBoundary($type='mixed')
1752
+    {
1753
+        if ($type == 'mixed') return $this->_smtpsBoundary;
1754
+        else if ($type == 'related') return $this->_smtpsRelatedBoundary;
1755
+        else if ($type == 'alternative') return $this->_smtpsAlternativeBoundary;
1756
+    }
1757 1757
 
1758 1758
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1759
-	/**
1760
-	 * This function has been modified as provided by SirSir to allow multiline responses when
1761
-	 * using SMTP Extensions
1762
-	 *
1763
-	 * @param	Handler		$socket			Socket handler
1764
-	 * @param	string		$response		Response. Example: "550 5.7.1  https://support.google.com/a/answer/6140680#invalidcred j21sm814390wre.3"
1765
-	 * @return	boolean						True or false
1766
-	 */
1767
-	function server_parse($socket, $response)
1768
-	{
1759
+    /**
1760
+     * This function has been modified as provided by SirSir to allow multiline responses when
1761
+     * using SMTP Extensions
1762
+     *
1763
+     * @param	Handler		$socket			Socket handler
1764
+     * @param	string		$response		Response. Example: "550 5.7.1  https://support.google.com/a/answer/6140680#invalidcred j21sm814390wre.3"
1765
+     * @return	boolean						True or false
1766
+     */
1767
+    function server_parse($socket, $response)
1768
+    {
1769 1769
         // phpcs:enable
1770
-		/**
1771
-		 * Returns constructed SELECT Object string or boolean upon failure
1772
-		 * Default value is set at true
1773
-		 */
1774
-		$_retVal = true;
1770
+        /**
1771
+         * Returns constructed SELECT Object string or boolean upon failure
1772
+         * Default value is set at true
1773
+         */
1774
+        $_retVal = true;
1775 1775
 
1776
-		$server_response = '';
1776
+        $server_response = '';
1777 1777
 
1778 1778
         // avoid infinite loop
1779 1779
         $limit=0;
1780 1780
 
1781
-		while (substr($server_response,3,1) != ' ' && $limit<100)
1782
-		{
1783
-			if (! ($server_response = fgets($socket, 256)))
1784
-			{
1785
-				$this->_setErr(121, "Couldn't get mail server response codes");
1786
-				$_retVal = false;
1787
-				break;
1788
-			}
1781
+        while (substr($server_response,3,1) != ' ' && $limit<100)
1782
+        {
1783
+            if (! ($server_response = fgets($socket, 256)))
1784
+            {
1785
+                $this->_setErr(121, "Couldn't get mail server response codes");
1786
+                $_retVal = false;
1787
+                break;
1788
+            }
1789 1789
             $limit++;
1790
-		}
1790
+        }
1791 1791
 
1792
-		if (! (substr($server_response, 0, 3) == $response))
1793
-		{
1794
-			$this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: $server_response");
1795
-			$_retVal = false;
1796
-		}
1792
+        if (! (substr($server_response, 0, 3) == $response))
1793
+        {
1794
+            $this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: $server_response");
1795
+            $_retVal = false;
1796
+        }
1797 1797
 
1798
-		return $_retVal;
1799
-	}
1798
+        return $_retVal;
1799
+    }
1800 1800
 
1801 1801
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1802
-	/**
1803
-	 * Send str
1804
-	 *
1805
-	 * @param	string		$_strSend		String to send
1806
-	 * @param 	string		$_returnCode	Return code
1807
-	 * @param 	string		$CRLF			CRLF
1808
-	 * @return 	boolean|null						True or false
1809
-	 */
1810
-	function socket_send_str( $_strSend, $_returnCode = null, $CRLF = "\r\n" )
1811
-	{
1802
+    /**
1803
+     * Send str
1804
+     *
1805
+     * @param	string		$_strSend		String to send
1806
+     * @param 	string		$_returnCode	Return code
1807
+     * @param 	string		$CRLF			CRLF
1808
+     * @return 	boolean|null						True or false
1809
+     */
1810
+    function socket_send_str( $_strSend, $_returnCode = null, $CRLF = "\r\n" )
1811
+    {
1812 1812
         // phpcs:enable
1813
-		if ($this->_debug) $this->log.=$_strSend;	// @CHANGE LDR for log
1814
-		fputs($this->socket, $_strSend . $CRLF);
1815
-		if ($this->_debug) $this->log.=' ('.$_returnCode.')' . $CRLF;
1813
+        if ($this->_debug) $this->log.=$_strSend;	// @CHANGE LDR for log
1814
+        fputs($this->socket, $_strSend . $CRLF);
1815
+        if ($this->_debug) $this->log.=' ('.$_returnCode.')' . $CRLF;
1816 1816
 
1817
-		if ( $_returnCode )
1818
-		return $this->server_parse($this->socket, $_returnCode);
1819
-	}
1817
+        if ( $_returnCode )
1818
+        return $this->server_parse($this->socket, $_returnCode);
1819
+    }
1820 1820
 
1821
-	// =============================================================
1822
-	// ** Error handling methods
1821
+    // =============================================================
1822
+    // ** Error handling methods
1823 1823
 
1824
-	/**
1825
-	 * Defines errors codes and messages for Class
1826
-	 *
1827
-	 * @param  int    $_errNum  Error Code Number
1828
-	 * @param  string $_errMsg  Error Message
1829
-	 * @return void
1824
+    /**
1825
+     * Defines errors codes and messages for Class
1826
+     *
1827
+     * @param  int    $_errNum  Error Code Number
1828
+     * @param  string $_errMsg  Error Message
1829
+     * @return void
1830 1830
      */
1831 1831
     function _setErr( $_errNum, $_errMsg )
1832 1832
     {
@@ -1836,25 +1836,25 @@  discard block
 block discarded – undo
1836 1836
         );
1837 1837
     }
1838 1838
 
1839
-	/**
1840
-	 * Returns errors codes and messages for Class
1841
-	 *
1842
-	 * @return string $_errMsg  Error Message
1843
-	 */
1844
-	function getErrors()
1845
-	{
1846
-		$_errMsg = array();
1847
-
1848
-		if (is_array($this->_smtpsErrors))
1849
-		{
1850
-			foreach ( $this->_smtpsErrors as $_err => $_info )
1851
-			{
1852
-				$_errMsg[] = 'Error [' . $_info['num'] .']: '. $_info['msg'];
1853
-			}
1854
-		}
1855
-
1856
-		return implode("\n", $_errMsg);
1857
-	}
1839
+    /**
1840
+     * Returns errors codes and messages for Class
1841
+     *
1842
+     * @return string $_errMsg  Error Message
1843
+     */
1844
+    function getErrors()
1845
+    {
1846
+        $_errMsg = array();
1847
+
1848
+        if (is_array($this->_smtpsErrors))
1849
+        {
1850
+            foreach ( $this->_smtpsErrors as $_err => $_info )
1851
+            {
1852
+                $_errMsg[] = 'Error [' . $_info['num'] .']: '. $_info['msg'];
1853
+            }
1854
+        }
1855
+
1856
+        return implode("\n", $_errMsg);
1857
+    }
1858 1858
 }
1859 1859
 
1860 1860
 
Please login to merge, or discard this patch.
Spacing   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -117,10 +117,10 @@  discard block
 block discarded – undo
117 117
 	/**
118 118
 	 * Message Sensitivity
119 119
 	 */
120
-	var $_arySensitivity = array ( false,
120
+	var $_arySensitivity = array(false,
121 121
                                   'Personal',
122 122
                                   'Private',
123
-                                  'Company Confidential' );
123
+                                  'Company Confidential');
124 124
 
125 125
 	/**
126 126
 	 * Message Sensitivity
@@ -131,12 +131,12 @@  discard block
 block discarded – undo
131 131
 	/**
132 132
 	 * Message Priority
133 133
 	 */
134
-	var $_aryPriority = array ( 'Bulk',
134
+	var $_aryPriority = array('Bulk',
135 135
                                 'Highest',
136 136
                                 'High',
137 137
                                 'Normal',
138 138
                                 'Low',
139
-                                'Lowest' );
139
+                                'Lowest');
140 140
 
141 141
 	/**
142 142
 	 * Content-Transfer-Encoding
@@ -147,13 +147,13 @@  discard block
 block discarded – undo
147 147
 	/**
148 148
 	 * Content-Transfer-Encoding
149 149
 	 */
150
-	var $_smtpsTransEncodeTypes = array( '7bit',               // Simple 7-bit ASCII
151
-                                         '8bit',               // 8-bit coding with line termination characters
152
-                                         'base64',             // 3 octets encoded into 4 sextets with offset
153
-                                         'binary',             // Arbitrary binary stream
154
-                                         'mac-binhex40',       // Macintosh binary to hex encoding
155
-                                         'quoted-printable',   // Mostly 7-bit, with 8-bit characters encoded as "=HH"
156
-                                         'uuencode' );         // UUENCODE encoding
150
+	var $_smtpsTransEncodeTypes = array('7bit', // Simple 7-bit ASCII
151
+                                         '8bit', // 8-bit coding with line termination characters
152
+                                         'base64', // 3 octets encoded into 4 sextets with offset
153
+                                         'binary', // Arbitrary binary stream
154
+                                         'mac-binhex40', // Macintosh binary to hex encoding
155
+                                         'quoted-printable', // Mostly 7-bit, with 8-bit characters encoded as "=HH"
156
+                                         'uuencode'); // UUENCODE encoding
157 157
 
158 158
 	/**
159 159
 	 * Content-Transfer-Encoding
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
      */
301 301
 	function setErrorsTo($_strErrorsTo)
302 302
 	{
303
-		if ( $_strErrorsTo )
303
+		if ($_strErrorsTo)
304 304
 		$this->_errorsTo = $this->_strip_email($_strErrorsTo);
305 305
 	}
306 306
 
@@ -310,11 +310,11 @@  discard block
 block discarded – undo
310 310
      * @param	boolean		$_part		Variant
311 311
      * @return	string					Errors to
312 312
      */
313
-	function getErrorsTo($_part = true )
313
+	function getErrorsTo($_part = true)
314 314
 	{
315 315
 		$_retValue = '';
316 316
 
317
-		if ( $_part === true )
317
+		if ($_part === true)
318 318
 		$_retValue = $this->_errorsTo;
319 319
 		else
320 320
 		$_retValue = $this->_errorsTo[$_part];
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 	 * @param	boolean		$_vDebug		Value for debug
329 329
 	 * @return 	void
330 330
 	 */
331
-	function setDebug($_vDebug = false )
331
+	function setDebug($_vDebug = false)
332 332
 	{
333 333
 		$this->_debug = $_vDebug;
334 334
 	}
@@ -359,29 +359,29 @@  discard block
 block discarded – undo
359 359
 		// We have to make sure the HOST given is valid
360 360
 		// This is done here because '@fsockopen' will not give me this
361 361
 		// information if it failes to connect because it can't find the HOST
362
-		$host=$this->getHost();
363
-		$usetls = preg_match('@tls://@i',$host);
362
+		$host = $this->getHost();
363
+		$usetls = preg_match('@tls://@i', $host);
364 364
 
365
-		$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
366
-		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
367
-		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
365
+		$host = preg_replace('@tcp://@i', '', $host); // Remove prefix
366
+		$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
367
+		$host = preg_replace('@tls://@i', '', $host); // Remove prefix
368 368
 
369 369
 		// @CHANGE LDR
370 370
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
371 371
 
372
-		if ( (! is_ip($host)) && ((gethostbyname($host)) == $host))
372
+		if ((!is_ip($host)) && ((gethostbyname($host)) == $host))
373 373
 		{
374
-			$this->_setErr(99, $host . ' is either offline or is an invalid host name.');
374
+			$this->_setErr(99, $host.' is either offline or is an invalid host name.');
375 375
 			$_retVal = false;
376 376
 		}
377 377
 		else
378 378
 		{
379 379
 			//See if we can connect to the SMTP server
380 380
 			if ($this->socket = @fsockopen(
381
-    			preg_replace('@tls://@i','',$this->getHost()),       // Host to 'hit', IP or domain
382
-    			$this->getPort(),       // which Port number to use
383
-    			$this->errno,           // actual system level error
384
-    			$this->errstr,          // and any text that goes with the error
381
+    			preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain
382
+    			$this->getPort(), // which Port number to use
383
+    			$this->errno, // actual system level error
384
+    			$this->errstr, // and any text that goes with the error
385 385
     			$this->_smtpTimeout
386 386
 			))  // timeout for reading/writing data over the socket
387 387
 			{
@@ -392,14 +392,14 @@  discard block
 block discarded – undo
392 392
 				if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
393 393
 
394 394
 				// Check response from Server
395
-				if ( $_retVal = $this->server_parse($this->socket, "220") )
395
+				if ($_retVal = $this->server_parse($this->socket, "220"))
396 396
 				$_retVal = $this->socket;
397 397
 			}
398 398
 			// This connection attempt failed.
399 399
 			else
400 400
 			{
401 401
 				// @CHANGE LDR
402
-				if (empty($this->errstr)) $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
402
+				if (empty($this->errstr)) $this->errstr = 'Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
403 403
 				$this->_setErr($this->errno, $this->errstr);
404 404
 				$_retVal = false;
405 405
 			}
@@ -422,18 +422,18 @@  discard block
 block discarded – undo
422 422
 		// Send the RFC2554 specified EHLO.
423 423
 		// This improvment as provided by 'SirSir' to
424 424
 		// accomodate both SMTP AND ESMTP capable servers
425
-		$host=$this->getHost();
426
-		$usetls = preg_match('@tls://@i',$host);
425
+		$host = $this->getHost();
426
+		$usetls = preg_match('@tls://@i', $host);
427 427
 
428
-		$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
429
-		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
430
-		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
428
+		$host = preg_replace('@tcp://@i', '', $host); // Remove prefix
429
+		$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
430
+		$host = preg_replace('@tls://@i', '', $host); // Remove prefix
431 431
 
432
-		if ($usetls) $host='tls://'.$host;
432
+		if ($usetls) $host = 'tls://'.$host;
433 433
 
434 434
 		$hosth = $host;
435 435
 
436
-		if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
436
+		if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
437 437
 		{
438 438
 			// If the from to is 'aaa <[email protected]>', we will keep 'ccc.com'
439 439
 			$hosth = $this->getFrom('addr');
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 			$hosth = preg_replace('/.*@/', '', $hosth);
443 443
 		}
444 444
 
445
-		if ( $_retVal = $this->socket_send_str('EHLO ' . $hosth, '250') )
445
+		if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250'))
446 446
 		{
447 447
 			if ($usetls)
448 448
 			{
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 				// the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
494 494
 				if (!$_retVal = $this->socket_send_str('EHLO '.$host, '250'))
495 495
 				{
496
-					$this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
496
+					$this->_setErr(126, '"'.$host.'" does not support authenticated connections.');
497 497
 					return $_retVal;
498 498
 				}
499 499
 			}
@@ -506,12 +506,12 @@  discard block
 block discarded – undo
506 506
 
507 507
 			// The error here just means the ID/password combo doesn't work.
508 508
 			// There is not a method to determine which is the problem, ID or password
509
-			if ( ! $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235') )
509
+			if (!$_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235'))
510 510
 			$this->_setErr(130, 'Invalid Authentication Credentials.');
511 511
 		}
512 512
 		else
513 513
 		{
514
-			$this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
514
+			$this->_setErr(126, '"'.$host.'" does not support authenticated connections.');
515 515
 		}
516 516
 
517 517
 		return $_retVal;
@@ -535,10 +535,10 @@  discard block
 block discarded – undo
535 535
 		$_retVal = false;
536 536
 
537 537
 		// Connect to Server
538
-		if ( $this->socket = $this->_server_connect() )
538
+		if ($this->socket = $this->_server_connect())
539 539
 		{
540 540
 			// If a User ID *and* a password is given, assume Authentication is desired
541
-			if( !empty($this->_smtpsID) && !empty($this->_smtpsPW) )
541
+			if (!empty($this->_smtpsID) && !empty($this->_smtpsPW))
542 542
 			{
543 543
 				// Send the RFC2554 specified EHLO.
544 544
 				$_retVal = $this->_server_authenticate();
@@ -548,16 +548,16 @@  discard block
 block discarded – undo
548 548
 			else
549 549
 			{
550 550
 				// Send the RFC821 specified HELO.
551
-				$host=$this->getHost();
552
-				$usetls = preg_match('@tls://@i',$host);
551
+				$host = $this->getHost();
552
+				$usetls = preg_match('@tls://@i', $host);
553 553
 
554
-				$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
555
-				$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
556
-				$host=preg_replace('@tls://@i','',$host);	// Remove prefix
554
+				$host = preg_replace('@tcp://@i', '', $host); // Remove prefix
555
+				$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
556
+				$host = preg_replace('@tls://@i', '', $host); // Remove prefix
557 557
 
558 558
 				$hosth = $host;
559 559
 
560
-				if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
560
+				if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
561 561
 				{
562 562
 					// If the from to is 'aaa <[email protected]>', we will keep 'ccc.com'
563 563
 					$hosth = $this->getFrom('addr');
@@ -566,21 +566,21 @@  discard block
 block discarded – undo
566 566
 					$hosth = preg_replace('/.*@/', '', $hosth);
567 567
 				}
568 568
 
569
-				$_retVal = $this->socket_send_str('HELO ' . $hosth, '250');
569
+				$_retVal = $this->socket_send_str('HELO '.$hosth, '250');
570 570
 			}
571 571
 
572 572
 			// Well, did we get to the server?
573
-			if ( $_retVal )
573
+			if ($_retVal)
574 574
 			{
575 575
 				// From this point onward most server response codes should be 250
576 576
 				// Specify who the mail is from....
577 577
 				// This has to be the raw email address, strip the "name" off
578
-				$this->socket_send_str('MAIL FROM: ' . $this->getFrom('addr'), '250');
578
+				$this->socket_send_str('MAIL FROM: '.$this->getFrom('addr'), '250');
579 579
 
580 580
 				// 'RCPT TO:' must be given a single address, so this has to loop
581 581
 				// through the list of addresses, regardless of TO, CC or BCC
582 582
 				// and send it out "single file"
583
-				foreach ( $this->get_RCPT_list() as $_address )
583
+				foreach ($this->get_RCPT_list() as $_address)
584 584
 				{
585 585
 				    /* Note:
586 586
 				     * BCC email addresses must be listed in the RCPT TO command list,
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
 					 * mark the last address as "bad" and start the address loop over again.
597 597
 					 * If any address fails, the entire message fails.
598 598
 					 */
599
-					$this->socket_send_str('RCPT TO: <' . $_address . '>', '250');
599
+					$this->socket_send_str('RCPT TO: <'.$_address.'>', '250');
600 600
 				}
601 601
 
602 602
 				// Tell the server we are ready to start sending data
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 
607 607
 				// Now we are ready for the message...
608 608
 				// Ok, all the ingredients are mixed in let's cook this puppy...
609
-				$this->socket_send_str($this->getHeader().$this->getBodyContent() . "\r\n" . '.', '250');
609
+				$this->socket_send_str($this->getHeader().$this->getBodyContent()."\r\n".'.', '250');
610 610
 
611 611
 				// Now tell the server we are done and close the socket...
612 612
 				fputs($this->socket, 'QUIT');
@@ -656,13 +656,13 @@  discard block
 block discarded – undo
656 656
 		$_retVal = true;
657 657
 
658 658
 		// if we have a path...
659
-		if ( ! empty ($_strConfigPath) )
659
+		if (!empty ($_strConfigPath))
660 660
 		{
661 661
 			// If the path is not valid, this will NOT generate an error,
662 662
 			// it will simply return false.
663
-			if ( ! @include $_strConfigPath)
663
+			if (!@include $_strConfigPath)
664 664
 			{
665
-				$this->_setErr(110, '"' . $_strConfigPath . '" is not a valid path.');
665
+				$this->_setErr(110, '"'.$_strConfigPath.'" is not a valid path.');
666 666
 				$_retVal = false;
667 667
 			}
668 668
 		}
@@ -672,13 +672,13 @@  discard block
 block discarded – undo
672 672
 		{
673 673
 			// Set these properties ONLY if they are set in the php.ini file.
674 674
 			// Otherwise the default values will be used.
675
-			if ( $_host = ini_get('SMTPs') )
675
+			if ($_host = ini_get('SMTPs'))
676 676
 			$this->setHost($_host);
677 677
 
678
-			if ( $_port = ini_get('smtp_port') )
678
+			if ($_port = ini_get('smtp_port'))
679 679
 			$this->setPort($_port);
680 680
 
681
-			if ( $_from = ini_get('sendmail_from') )
681
+			if ($_from = ini_get('sendmail_from'))
682 682
 			$this->setFrom($_from);
683 683
 		}
684 684
 
@@ -697,8 +697,8 @@  discard block
 block discarded – undo
697 697
 	 */
698 698
 	function setTransportType($_type = 0)
699 699
 	{
700
-		if ( ( is_numeric($_type) ) &&
701
-		( ( $_type >= 0 ) && ( $_type <= 3 ) ) )
700
+		if ((is_numeric($_type)) &&
701
+		(($_type >= 0) && ($_type <= 3)))
702 702
 		$this->_transportType = $_type;
703 703
 	}
704 704
 
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
 	 */
741 741
 	function setHost($_strHost)
742 742
 	{
743
-		if ( $_strHost )
743
+		if ($_strHost)
744 744
 		$this->_smtpsHost = $_strHost;
745 745
 	}
746 746
 
@@ -765,8 +765,8 @@  discard block
 block discarded – undo
765 765
 	 */
766 766
 	function setPort($_intPort)
767 767
 	{
768
-		if ( ( is_numeric($_intPort) ) &&
769
-		( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) )
768
+		if ((is_numeric($_intPort)) &&
769
+		(($_intPort >= 1) && ($_intPort <= 65536)))
770 770
 		$this->_smtpsPort = $_intPort;
771 771
 	}
772 772
 
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
 	 */
833 833
 	function setCharSet($_strCharSet)
834 834
 	{
835
-		if ( $_strCharSet )
835
+		if ($_strCharSet)
836 836
 		$this->_smtpsCharSet = $_strCharSet;
837 837
 	}
838 838
 
@@ -920,7 +920,7 @@  discard block
 block discarded – undo
920 920
 	 */
921 921
 	function setFrom($_strFrom)
922 922
 	{
923
-		if ( $_strFrom )
923
+		if ($_strFrom)
924 924
 		$this->_msgFrom = $this->_strip_email($_strFrom);
925 925
 	}
926 926
 
@@ -934,7 +934,7 @@  discard block
 block discarded – undo
934 934
 	{
935 935
 		$_retValue = '';
936 936
 
937
-		if ( $_part === true )
937
+		if ($_part === true)
938 938
 		$_retValue = $this->_msgFrom;
939 939
 		else
940 940
 		$_retValue = $this->_msgFrom[$_part];
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 	 */
951 951
 	function setReplyTo($_strReplyTo)
952 952
 	{
953
-	    if ( $_strReplyTo )
953
+	    if ($_strReplyTo)
954 954
 	        $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
955 955
 	}
956 956
 
@@ -964,7 +964,7 @@  discard block
 block discarded – undo
964 964
 	{
965 965
 	    $_retValue = '';
966 966
 
967
-	    if ( $_part === true )
967
+	    if ($_part === true)
968 968
 	        $_retValue = $this->_msgReplyTo;
969 969
 	    else
970 970
 	        $_retValue = $this->_msgReplyTo[$_part];
@@ -990,13 +990,13 @@  discard block
 block discarded – undo
990 990
 		$aryHost = $this->_msgRecipients;
991 991
 
992 992
 		// Only run this if we have something
993
-		if ( !empty ($_addrList ))
993
+		if (!empty ($_addrList))
994 994
 		{
995 995
 			// $_addrList can be a STRING or an array
996
-			if ( is_string($_addrList) )
996
+			if (is_string($_addrList))
997 997
 			{
998 998
 				// This could be a COMMA delimited string
999
-				if ( strstr($_addrList, ',') )
999
+				if (strstr($_addrList, ','))
1000 1000
 				// "explode "list" into an array
1001 1001
 				$_addrList = explode(',', $_addrList);
1002 1002
 
@@ -1006,7 +1006,7 @@  discard block
 block discarded – undo
1006 1006
 			}
1007 1007
 
1008 1008
 			// take the array of addresses and split them further
1009
-			foreach ( $_addrList as $_strAddr )
1009
+			foreach ($_addrList as $_strAddr)
1010 1010
 			{
1011 1011
 				// Strip off the end '>'
1012 1012
 				$_strAddr = str_replace('>', '', $_strAddr);
@@ -1016,7 +1016,7 @@  discard block
 block discarded – undo
1016 1016
 				$_tmpaddr = explode('<', $_strAddr);
1017 1017
 
1018 1018
 				// We have a "Real Name" and eMail address
1019
-				if ( count($_tmpaddr) == 2 )
1019
+				if (count($_tmpaddr) == 2)
1020 1020
 				{
1021 1021
 					$_tmpHost = explode('@', $_tmpaddr[1]);
1022 1022
 					$_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
@@ -1073,10 +1073,10 @@  discard block
 block discarded – undo
1073 1073
 		$_tmpAry = explode('<', $_strAddr);
1074 1074
 
1075 1075
 		// Do we have a "Real name"
1076
-		if ( count($_tmpAry) == 2 )
1076
+		if (count($_tmpAry) == 2)
1077 1077
 		{
1078 1078
 			// We may not really have a "Real Name"
1079
-			if ( $_tmpAry[0])
1079
+			if ($_tmpAry[0])
1080 1080
 			$_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1081 1081
 
1082 1082
 			$_aryEmail['addr'] = $_tmpAry[1];
@@ -1085,10 +1085,10 @@  discard block
 block discarded – undo
1085 1085
 		$_aryEmail['addr'] = $_tmpAry[0];
1086 1086
 
1087 1087
 		// Pull User Name and Host.tld apart
1088
-		list($_aryEmail['user'], $_aryEmail['host'] ) = explode('@', $_aryEmail['addr']);
1088
+		list($_aryEmail['user'], $_aryEmail['host']) = explode('@', $_aryEmail['addr']);
1089 1089
 
1090 1090
 		// Put the brackets back around the address
1091
-		$_aryEmail['addr'] = '<' . $_aryEmail['addr'] . '>';
1091
+		$_aryEmail['addr'] = '<'.$_aryEmail['addr'].'>';
1092 1092
 
1093 1093
 		return $_aryEmail;
1094 1094
 	}
@@ -1107,17 +1107,17 @@  discard block
 block discarded – undo
1107 1107
 		/**
1108 1108
 		 * An array of bares addresses for use with 'RCPT TO:'
1109 1109
 		 */
1110
-		$_RCPT_list=array();
1110
+		$_RCPT_list = array();
1111 1111
 
1112 1112
 		// walk down Recipients array and pull just email addresses
1113
-		foreach ( $this->_msgRecipients as $_host => $_list )
1113
+		foreach ($this->_msgRecipients as $_host => $_list)
1114 1114
 		{
1115
-			foreach ( $_list as $_subList )
1115
+			foreach ($_list as $_subList)
1116 1116
 			{
1117
-				foreach ( $_subList as $_name => $_addr )
1117
+				foreach ($_subList as $_name => $_addr)
1118 1118
 				{
1119 1119
 					// build RCPT list
1120
-					$_RCPT_list[] = $_name . '@' . $_host;
1120
+					$_RCPT_list[] = $_name.'@'.$_host;
1121 1121
 				}
1122 1122
 			}
1123 1123
 		}
@@ -1136,27 +1136,27 @@  discard block
 block discarded – undo
1136 1136
 	{
1137 1137
         // phpcs:enable
1138 1138
 		// We need to know which address segment to pull
1139
-		if ( $_which )
1139
+		if ($_which)
1140 1140
 		{
1141 1141
 			// Make sure we have addresses to process
1142
-			if ( $this->_msgRecipients )
1142
+			if ($this->_msgRecipients)
1143 1143
 			{
1144
-				$_RCPT_list=array();
1144
+				$_RCPT_list = array();
1145 1145
 				// walk down Recipients array and pull just email addresses
1146
-				foreach ( $this->_msgRecipients as $_host => $_list )
1146
+				foreach ($this->_msgRecipients as $_host => $_list)
1147 1147
 				{
1148
-					if ( $this->_msgRecipients[$_host][$_which] )
1148
+					if ($this->_msgRecipients[$_host][$_which])
1149 1149
 					{
1150
-						foreach ( $this->_msgRecipients[$_host][$_which] as $_addr => $_realName )
1150
+						foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName)
1151 1151
 						{
1152
-							if ( $_realName )	// @CHANGE LDR
1152
+							if ($_realName)	// @CHANGE LDR
1153 1153
 							{
1154
-								$_realName = '"' . $_realName . '"';
1155
-								$_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>';
1154
+								$_realName = '"'.$_realName.'"';
1155
+								$_RCPT_list[] = $_realName.' <'.$_addr.'@'.$_host.'>';
1156 1156
 							}
1157 1157
 							else
1158 1158
 							{
1159
-								$_RCPT_list[] = $_addr . '@' . $_host;
1159
+								$_RCPT_list[] = $_addr.'@'.$_host;
1160 1160
 							}
1161 1161
 						}
1162 1162
 					}
@@ -1185,7 +1185,7 @@  discard block
 block discarded – undo
1185 1185
 	 */
1186 1186
 	function setTO($_addrTo)
1187 1187
 	{
1188
-		if ( $_addrTo )
1188
+		if ($_addrTo)
1189 1189
 		$this->_buildAddrList('to', $_addrTo);
1190 1190
 	}
1191 1191
 
@@ -1207,7 +1207,7 @@  discard block
 block discarded – undo
1207 1207
 	 */
1208 1208
 	function setCC($_strCC)
1209 1209
 	{
1210
-		if ( $_strCC )
1210
+		if ($_strCC)
1211 1211
 		$this->_buildAddrList('cc', $_strCC);
1212 1212
 	}
1213 1213
 
@@ -1229,7 +1229,7 @@  discard block
 block discarded – undo
1229 1229
 	 */
1230 1230
 	function setBCC($_strBCC)
1231 1231
 	{
1232
-		if ( $_strBCC )
1232
+		if ($_strBCC)
1233 1233
 		$this->_buildAddrList('bcc', $_strBCC);
1234 1234
 	}
1235 1235
 
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
 	 */
1252 1252
 	function setSubject($_strSubject = '')
1253 1253
 	{
1254
-		if ( $_strSubject )
1254
+		if ($_strSubject)
1255 1255
 		$this->_msgSubject = $_strSubject;
1256 1256
 	}
1257 1257
 
@@ -1274,11 +1274,11 @@  discard block
 block discarded – undo
1274 1274
 	{
1275 1275
 		global $conf;
1276 1276
 
1277
-		$_header = 'From: '       . $this->getFrom('org') . "\r\n"
1278
-		. 'To: '         . $this->getTO()          . "\r\n";
1277
+		$_header = 'From: '.$this->getFrom('org')."\r\n"
1278
+		. 'To: '.$this->getTO()."\r\n";
1279 1279
 
1280
-		if ( $this->getCC() )
1281
-		$_header .= 'Cc: ' . $this->getCC()  . "\r\n";
1280
+		if ($this->getCC())
1281
+		$_header .= 'Cc: '.$this->getCC()."\r\n";
1282 1282
 
1283 1283
 		/* Note:
1284 1284
 		 * BCC email addresses must be listed in the RCPT TO command list,
@@ -1291,57 +1291,57 @@  discard block
 block discarded – undo
1291 1291
 		$_header .= 'Bcc: ' . $this->getBCC()  . "\r\n";
1292 1292
         */
1293 1293
 
1294
-		$host=$this->getHost();
1295
-		$usetls = preg_match('@tls://@i',$host);
1294
+		$host = $this->getHost();
1295
+		$usetls = preg_match('@tls://@i', $host);
1296 1296
 
1297
-		$host=preg_replace('@tcp://@i','',$host);	// Remove prefix
1298
-		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
1299
-		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
1297
+		$host = preg_replace('@tcp://@i', '', $host); // Remove prefix
1298
+		$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
1299
+		$host = preg_replace('@tls://@i', '', $host); // Remove prefix
1300 1300
 
1301
-		$host=dol_getprefix('email');
1301
+		$host = dol_getprefix('email');
1302 1302
 
1303 1303
 		//NOTE: Message-ID should probably contain the username of the user who sent the msg
1304
-		$_header .= 'Subject: '    . $this->getSubject()     . "\r\n";
1305
-		$_header .= 'Date: '       . date("r")               . "\r\n";
1304
+		$_header .= 'Subject: '.$this->getSubject()."\r\n";
1305
+		$_header .= 'Date: '.date("r")."\r\n";
1306 1306
 
1307 1307
 		$trackid = $this->getTrackId();
1308 1308
 		if ($trackid)
1309 1309
 		{
1310 1310
 			// References is kept in response and Message-ID is returned into In-Reply-To:
1311
-			$_header .= 'Message-ID: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1312
-			$_header .= 'References: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1313
-			$_header .= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host . "\r\n";
1311
+			$_header .= 'Message-ID: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n";
1312
+			$_header .= 'References: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n";
1313
+			$_header .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host."\r\n";
1314 1314
 		}
1315 1315
 		else
1316 1316
 		{
1317
-			$_header .= 'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n";
1317
+			$_header .= 'Message-ID: <'.time().'.SMTPs@'.$host.">\r\n";
1318 1318
 		}
1319
-		if (! empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n";
1320
-		if ( $this->getMoreInHeader() )
1321
-		    $_header .= $this->getMoreInHeader();     // Value must include the "\r\n";
1319
+		if (!empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n";
1320
+		if ($this->getMoreInHeader())
1321
+		    $_header .= $this->getMoreInHeader(); // Value must include the "\r\n";
1322 1322
 
1323 1323
 		//$_header .=
1324 1324
 		//                 'Read-Receipt-To: '   . $this->getFrom( 'org' ) . "\r\n"
1325 1325
 		//                 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
1326 1326
 
1327
-		if ( $this->getSensitivity() )
1328
-		$_header .= 'Sensitivity: ' . $this->getSensitivity()  . "\r\n";
1327
+		if ($this->getSensitivity())
1328
+		$_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n";
1329 1329
 
1330
-		if ( $this->_msgPriority != 3 )
1330
+		if ($this->_msgPriority != 3)
1331 1331
 		$_header .= $this->getPriority();
1332 1332
 
1333 1333
 
1334 1334
 		// @CHANGE LDR
1335
-		if ( $this->getDeliveryReceipt() )
1336
-		    $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n";
1337
-		if ( $this->getErrorsTo() )
1338
-		    $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n";
1339
-		if ( $this->getReplyTo() )
1340
-		    $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n";
1335
+		if ($this->getDeliveryReceipt())
1336
+		    $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr')."\r\n";
1337
+		if ($this->getErrorsTo())
1338
+		    $_header .= 'Errors-To: '.$this->getErrorsTo('addr')."\r\n";
1339
+		if ($this->getReplyTo())
1340
+		    $_header .= "Reply-To: ".$this->getReplyTo('addr')."\r\n";
1341 1341
 
1342
-		$_header .= 'X-Mailer: Dolibarr version ' . DOL_VERSION .' (using SMTPs Mailer)' . "\r\n";
1343
-		$_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART?'MAIN_MAIL_USE_MULTI_PART':'No MAIN_MAIL_USE_MULTI_PART') . "\r\n";
1344
-		$_header .= 'Mime-Version: 1.0' . "\r\n";
1342
+		$_header .= 'X-Mailer: Dolibarr version '.DOL_VERSION.' (using SMTPs Mailer)'."\r\n";
1343
+		$_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART ? 'MAIN_MAIL_USE_MULTI_PART' : 'No MAIN_MAIL_USE_MULTI_PART')."\r\n";
1344
+		$_header .= 'Mime-Version: 1.0'."\r\n";
1345 1345
 
1346 1346
 
1347 1347
 		return $_header;
@@ -1358,7 +1358,7 @@  discard block
 block discarded – undo
1358 1358
 	{
1359 1359
 		//if ( $strContent )
1360 1360
 		//{
1361
-		if ( $strType == 'html' )
1361
+		if ($strType == 'html')
1362 1362
 		$strMimeType = 'text/html';
1363 1363
 		else
1364 1364
 		$strMimeType = 'text/plain';
@@ -1370,14 +1370,14 @@  discard block
 block discarded – undo
1370 1370
 		if ($strType == 'html')
1371 1371
 		{
1372 1372
 			// Similar code to forge a text from html is also in CMailFile.class.php
1373
-			$strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1373
+			$strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
1374 1374
 			$strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1375 1375
 			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n"));
1376 1376
 		}
1377 1377
 
1378 1378
 		// Make RFC2045 Compliant
1379 1379
 		//$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1380
-		$strContent = rtrim(wordwrap($strContent, 75, "\r\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1380
+		$strContent = rtrim(wordwrap($strContent, 75, "\r\n")); // TODO Using this method creates unexpected line break on text/plain content.
1381 1381
 
1382 1382
 		$this->_msgContent[$strType] = array();
1383 1383
 
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
 		$this->_msgContent[$strType]['data']     = $strContent;
1386 1386
 		$this->_msgContent[$strType]['dataText'] = $strContentAltText;
1387 1387
 
1388
-		if ( $this->getMD5flag() )
1388
+		if ($this->getMD5flag())
1389 1389
 		$this->_msgContent[$strType]['md5']      = dol_hash($strContent, 3);
1390 1390
 		//}
1391 1391
 	}
@@ -1409,49 +1409,49 @@  discard block
 block discarded – undo
1409 1409
 		$keyCount = count($_types);
1410 1410
 
1411 1411
 		// If we have ZERO, we have a problem
1412
-		if( $keyCount === 0 )
1412
+		if ($keyCount === 0)
1413 1413
 		die ("Sorry, no content");
1414 1414
 
1415 1415
 		// If we have ONE, we can use the simple format
1416
-		else if( $keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1416
+		else if ($keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1417 1417
 		{
1418 1418
 			$_msgData = $this->_msgContent;
1419 1419
 			$_msgData = $_msgData[$_types[0]];
1420 1420
 
1421
-			$content = 'Content-Type: ' . $_msgData['mimeType'] . '; charset="' . $this->getCharSet() . '"' . "\r\n"
1422
-			. 'Content-Transfer-Encoding: ' . $this->getTransEncodeType() . "\r\n"
1423
-			. 'Content-Disposition: inline'  . "\r\n"
1424
-			. 'Content-Description: Message' . "\r\n";
1421
+			$content = 'Content-Type: '.$_msgData['mimeType'].'; charset="'.$this->getCharSet().'"'."\r\n"
1422
+			. 'Content-Transfer-Encoding: '.$this->getTransEncodeType()."\r\n"
1423
+			. 'Content-Disposition: inline'."\r\n"
1424
+			. 'Content-Description: Message'."\r\n";
1425 1425
 
1426
-			if ( $this->getMD5flag() )
1427
-			$content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
1426
+			if ($this->getMD5flag())
1427
+			$content .= 'Content-MD5: '.$_msgData['md5']."\r\n";
1428 1428
 
1429 1429
 			$content .= "\r\n"
1430
-			.  $_msgData['data'] . "\r\n";
1430
+			.  $_msgData['data']."\r\n";
1431 1431
 		}
1432 1432
 
1433 1433
 		// If we have more than ONE, we use the multi-part format
1434
-		else if( $keyCount >= 1 || ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1434
+		else if ($keyCount >= 1 || !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
1435 1435
 		{
1436 1436
 			// Since this is an actual multi-part message
1437 1437
 			// We need to define a content message Boundary
1438 1438
 			// NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
1439 1439
 
1440 1440
 			//$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"'   . "\r\n";
1441
-			$content = 'Content-Type: multipart/mixed; boundary="' . $this->_getBoundary('mixed') . '"'   . "\r\n";
1441
+			$content = 'Content-Type: multipart/mixed; boundary="'.$this->_getBoundary('mixed').'"'."\r\n";
1442 1442
 
1443 1443
 			//                     . "\r\n"
1444 1444
 			//                     . 'This is a multi-part message in MIME format.' . "\r\n";
1445 1445
 			$content .= "Content-Transfer-Encoding: 8bit\r\n";
1446 1446
 			$content .= "\r\n";
1447 1447
 
1448
-			$content .= "--" . $this->_getBoundary('mixed') . "\r\n";
1448
+			$content .= "--".$this->_getBoundary('mixed')."\r\n";
1449 1449
 
1450 1450
 			if (key_exists('image', $this->_msgContent))     // If inline image found
1451 1451
 			{
1452
-				$content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1452
+				$content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
1453 1453
 				$content .= "\r\n";
1454
-				$content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1454
+				$content .= "--".$this->_getBoundary('alternative')."\r\n";
1455 1455
 			}
1456 1456
 
1457 1457
 
@@ -1459,93 +1459,93 @@  discard block
 block discarded – undo
1459 1459
 
1460 1460
 
1461 1461
 			// Loop through message content array
1462
-			foreach ($this->_msgContent as $type => $_content )
1462
+			foreach ($this->_msgContent as $type => $_content)
1463 1463
 			{
1464
-				if ( $type == 'attachment' )
1464
+				if ($type == 'attachment')
1465 1465
 				{
1466 1466
 					// loop through all attachments
1467
-					foreach ( $_content as $_file => $_data )
1467
+					foreach ($_content as $_file => $_data)
1468 1468
 					{
1469
-						$content .= "--" . $this->_getBoundary('mixed') . "\r\n"
1470
-						.  'Content-Disposition: attachment; filename="' . $_data['fileName'] . '"' . "\r\n"
1471
-						.  'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['fileName'] . '"' . "\r\n"
1472
-						.  'Content-Transfer-Encoding: base64' . "\r\n"
1473
-						.  'Content-Description: ' . $_data['fileName'] ."\r\n";
1469
+						$content .= "--".$this->_getBoundary('mixed')."\r\n"
1470
+						.  'Content-Disposition: attachment; filename="'.$_data['fileName'].'"'."\r\n"
1471
+						.  'Content-Type: '.$_data['mimeType'].'; name="'.$_data['fileName'].'"'."\r\n"
1472
+						.  'Content-Transfer-Encoding: base64'."\r\n"
1473
+						.  'Content-Description: '.$_data['fileName']."\r\n";
1474 1474
 
1475
-						if ( $this->getMD5flag() )
1476
-						$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1475
+						if ($this->getMD5flag())
1476
+						$content .= 'Content-MD5: '.$_data['md5']."\r\n";
1477 1477
 
1478
-						$content .= "\r\n" .  $_data['data'] . "\r\n\r\n";
1478
+						$content .= "\r\n".$_data['data']."\r\n\r\n";
1479 1479
 					}
1480 1480
 				}
1481 1481
 				// @CHANGE LDR
1482
-				else if ( $type == 'image' )
1482
+				else if ($type == 'image')
1483 1483
 				{
1484 1484
 					// loop through all images
1485
-					foreach ( $_content as $_image => $_data )
1485
+					foreach ($_content as $_image => $_data)
1486 1486
 					{
1487
-						$content .= "--" . $this->_getBoundary('related') . "\r\n";  // always related for an inline image
1487
+						$content .= "--".$this->_getBoundary('related')."\r\n"; // always related for an inline image
1488 1488
 
1489
-						$content .= 'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['imageName'] . '"' . "\r\n"
1490
-						.  'Content-Transfer-Encoding: base64' . "\r\n"
1491
-						.  'Content-Disposition: inline; filename="' . $_data['imageName'] . '"' . "\r\n"
1492
-						.  'Content-ID: <' . $_data['cid'] . '> ' . "\r\n";
1489
+						$content .= 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['imageName'].'"'."\r\n"
1490
+						.  'Content-Transfer-Encoding: base64'."\r\n"
1491
+						.  'Content-Disposition: inline; filename="'.$_data['imageName'].'"'."\r\n"
1492
+						.  'Content-ID: <'.$_data['cid'].'> '."\r\n";
1493 1493
 
1494
-						if ( $this->getMD5flag() )
1495
-						$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1494
+						if ($this->getMD5flag())
1495
+						$content .= 'Content-MD5: '.$_data['md5']."\r\n";
1496 1496
 
1497 1497
 						$content .= "\r\n"
1498
-						. $_data['data'] . "\r\n";
1498
+						. $_data['data']."\r\n";
1499 1499
 					}
1500 1500
 
1501 1501
 					// always end related and end alternative after inline images
1502
-					$content.= "--" . $this->_getBoundary('related') . "--" . "\r\n";
1503
-					$content.= "\r\n" . "--" . $this->_getBoundary('alternative') . "--" . "\r\n";
1504
-					$content.= "\r\n";
1502
+					$content .= "--".$this->_getBoundary('related')."--"."\r\n";
1503
+					$content .= "\r\n"."--".$this->_getBoundary('alternative')."--"."\r\n";
1504
+					$content .= "\r\n";
1505 1505
 				}
1506 1506
 				else
1507 1507
 				{
1508 1508
 					if (key_exists('image', $this->_msgContent))
1509 1509
 					{
1510
-						$content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
1511
-						$content.= "\r\n" . ($_content['dataText']?$_content['dataText']:strip_tags($_content['data'])) . "\r\n"; // Add plain text message
1512
-						$content.= "--" . $this->_getBoundary('alternative') . "\r\n";
1513
-						$content.= 'Content-Type: multipart/related; boundary="' . $this->_getBoundary('related') . '"' . "\r\n";
1514
-						$content.= "\r\n";
1515
-						$content.= "--" . $this->_getBoundary('related') . "\r\n";
1510
+						$content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
1511
+						$content .= "\r\n".($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n"; // Add plain text message
1512
+						$content .= "--".$this->_getBoundary('alternative')."\r\n";
1513
+						$content .= 'Content-Type: multipart/related; boundary="'.$this->_getBoundary('related').'"'."\r\n";
1514
+						$content .= "\r\n";
1515
+						$content .= "--".$this->_getBoundary('related')."\r\n";
1516 1516
 					}
1517 1517
 
1518
-					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
1518
+					if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
1519 1519
 					{
1520
-					    $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1520
+					    $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
1521 1521
     					$content .= "\r\n";
1522
-	       				$content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1522
+	       				$content .= "--".$this->_getBoundary('alternative')."\r\n";
1523 1523
 
1524
-	       				$content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
1525
-	       				$content.= "\r\n". $_content['dataText'] . "\r\n";
1526
-	       				$content.= "--" . $this->_getBoundary('alternative') . "\r\n";
1524
+	       				$content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
1525
+	       				$content .= "\r\n".$_content['dataText']."\r\n";
1526
+	       				$content .= "--".$this->_getBoundary('alternative')."\r\n";
1527 1527
 					}
1528 1528
 
1529
-					$content .= 'Content-Type: ' . $_content['mimeType'] . '; '
1529
+					$content .= 'Content-Type: '.$_content['mimeType'].'; '
1530 1530
 					//                             . 'charset="' . $this->getCharSet() . '"';
1531
-					. 'charset=' . $this->getCharSet() . '';
1531
+					. 'charset='.$this->getCharSet().'';
1532 1532
 
1533 1533
 					//                    $content .= ( $type == 'html') ? '; name="HTML Part"' : '';
1534
-					$content .=  "\r\n";
1534
+					$content .= "\r\n";
1535 1535
 					//                    $content .= 'Content-Transfer-Encoding: ';
1536 1536
 					//                    $content .= ($type == 'html') ? 'quoted-printable' : $this->getTransEncodeType();
1537 1537
 					//                    $content .=  "\r\n"
1538 1538
 					//                             . 'Content-Disposition: inline'  . "\r\n"
1539 1539
 					//                             . 'Content-Description: ' . $type . ' message' . "\r\n";
1540 1540
 
1541
-					if ( $this->getMD5flag() )
1542
-					$content .= 'Content-MD5: ' . $_content['md5'] . "\r\n";
1541
+					if ($this->getMD5flag())
1542
+					$content .= 'Content-MD5: '.$_content['md5']."\r\n";
1543 1543
 
1544
-					$content .= "\r\n"	. $_content['data'] . "\r\n";
1544
+					$content .= "\r\n".$_content['data']."\r\n";
1545 1545
 
1546
-					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
1546
+					if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
1547 1547
 					{
1548
-					    $content.= "--" . $this->_getBoundary('alternative') . "--". "\r\n";
1548
+					    $content .= "--".$this->_getBoundary('alternative')."--"."\r\n";
1549 1549
 					}
1550 1550
 
1551 1551
 					$content .= "\r\n";
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
 
1555 1555
 			// Close message boundries
1556 1556
 			//            $content .= "\r\n--" . $this->_getBoundary() . '--' . "\r\n" ;
1557
-			$content .= "--" . $this->_getBoundary('mixed') . '--' . "\r\n" ;
1557
+			$content .= "--".$this->_getBoundary('mixed').'--'."\r\n";
1558 1558
 		}
1559 1559
 
1560 1560
 		return $content;
@@ -1571,15 +1571,15 @@  discard block
 block discarded – undo
1571 1571
 	 */
1572 1572
 	function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown')
1573 1573
 	{
1574
-		if ( $strContent )
1574
+		if ($strContent)
1575 1575
 		{
1576
-			$strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n"));    // 76 max is defined into http://tools.ietf.org/html/rfc2047
1576
+			$strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047
1577 1577
 
1578 1578
 			$this->_msgContent['attachment'][$strFileName]['mimeType'] = $strMimeType;
1579 1579
 			$this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName;
1580 1580
 			$this->_msgContent['attachment'][$strFileName]['data']     = $strContent;
1581 1581
 
1582
-			if ( $this->getMD5flag() )
1582
+			if ($this->getMD5flag())
1583 1583
 			$this->_msgContent['attachment'][$strFileName]['md5']      = dol_hash($strContent, 3);
1584 1584
 		}
1585 1585
 	}
@@ -1606,7 +1606,7 @@  discard block
 block discarded – undo
1606 1606
 			$this->_msgContent['image'][$strImageName]['cid']      = $strImageCid;
1607 1607
 			$this->_msgContent['image'][$strImageName]['data']     = $strContent;
1608 1608
 
1609
-			if ( $this->getMD5flag() )
1609
+			if ($this->getMD5flag())
1610 1610
 			$this->_msgContent['image'][$strImageName]['md5']      = dol_hash($strContent, 3);
1611 1611
 		}
1612 1612
 	}
@@ -1626,8 +1626,8 @@  discard block
 block discarded – undo
1626 1626
 	 */
1627 1627
 	function setSensitivity($_value = 0)
1628 1628
 	{
1629
-		if ( ( is_numeric($_value) ) &&
1630
-		( ( $_value >= 0 ) && ( $_value <= 3 ) ) )
1629
+		if ((is_numeric($_value)) &&
1630
+		(($_value >= 0) && ($_value <= 3)))
1631 1631
 		$this->_msgSensitivity = $_value;
1632 1632
 	}
1633 1633
 
@@ -1659,10 +1659,10 @@  discard block
 block discarded – undo
1659 1659
 	 * @param 	integer 	$_value 	Message Priority
1660 1660
 	 * @return 	void
1661 1661
 	 */
1662
-	function setPriority( $_value = 3 )
1662
+	function setPriority($_value = 3)
1663 1663
 	{
1664
-		if ( ( is_numeric($_value) ) &&
1665
-		( ( $_value >= 0 ) && ( $_value <= 5 ) ) )
1664
+		if ((is_numeric($_value)) &&
1665
+		(($_value >= 0) && ($_value <= 5)))
1666 1666
 		$this->_msgPriority = $_value;
1667 1667
 	}
1668 1668
 
@@ -1680,9 +1680,9 @@  discard block
 block discarded – undo
1680 1680
 	 */
1681 1681
 	function getPriority()
1682 1682
 	{
1683
-		return 'Importance: ' . $this->_aryPriority[$this->_msgPriority] . "\r\n"
1684
-		. 'Priority: '   . $this->_aryPriority[$this->_msgPriority] . "\r\n"
1685
-		. 'X-Priority: ' . $this->_msgPriority . ' (' . $this->_aryPriority[$this->_msgPriority] . ')' . "\r\n";
1683
+		return 'Importance: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
1684
+		. 'Priority: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
1685
+		. 'X-Priority: '.$this->_msgPriority.' ('.$this->_aryPriority[$this->_msgPriority].')'."\r\n";
1686 1686
 	}
1687 1687
 
1688 1688
 	/**
@@ -1716,7 +1716,7 @@  discard block
 block discarded – undo
1716 1716
 	 */
1717 1717
 	function setXheader($strXdata)
1718 1718
 	{
1719
-		if ( $strXdata )
1719
+		if ($strXdata)
1720 1720
 		$this->_msgXheader[] = $strXdata;
1721 1721
 	}
1722 1722
 
@@ -1737,7 +1737,7 @@  discard block
 block discarded – undo
1737 1737
 	 */
1738 1738
 	function _setBoundary()
1739 1739
 	{
1740
-		$this->_smtpsBoundary = "multipart_x." . time() . ".x_boundary";
1740
+		$this->_smtpsBoundary = "multipart_x.".time().".x_boundary";
1741 1741
 		$this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);
1742 1742
 		$this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);
1743 1743
 	}
@@ -1748,7 +1748,7 @@  discard block
 block discarded – undo
1748 1748
 	 * @param  string $type				Type of boundary
1749 1749
 	 * @return string $_smtpsBoundary 	MIME message Boundary
1750 1750
 	 */
1751
-	function _getBoundary($type='mixed')
1751
+	function _getBoundary($type = 'mixed')
1752 1752
 	{
1753 1753
 		if ($type == 'mixed') return $this->_smtpsBoundary;
1754 1754
 		else if ($type == 'related') return $this->_smtpsRelatedBoundary;
@@ -1776,11 +1776,11 @@  discard block
 block discarded – undo
1776 1776
 		$server_response = '';
1777 1777
 
1778 1778
         // avoid infinite loop
1779
-        $limit=0;
1779
+        $limit = 0;
1780 1780
 
1781
-		while (substr($server_response,3,1) != ' ' && $limit<100)
1781
+		while (substr($server_response, 3, 1) != ' ' && $limit < 100)
1782 1782
 		{
1783
-			if (! ($server_response = fgets($socket, 256)))
1783
+			if (!($server_response = fgets($socket, 256)))
1784 1784
 			{
1785 1785
 				$this->_setErr(121, "Couldn't get mail server response codes");
1786 1786
 				$_retVal = false;
@@ -1789,7 +1789,7 @@  discard block
 block discarded – undo
1789 1789
             $limit++;
1790 1790
 		}
1791 1791
 
1792
-		if (! (substr($server_response, 0, 3) == $response))
1792
+		if (!(substr($server_response, 0, 3) == $response))
1793 1793
 		{
1794 1794
 			$this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: $server_response");
1795 1795
 			$_retVal = false;
@@ -1807,14 +1807,14 @@  discard block
 block discarded – undo
1807 1807
 	 * @param 	string		$CRLF			CRLF
1808 1808
 	 * @return 	boolean|null						True or false
1809 1809
 	 */
1810
-	function socket_send_str( $_strSend, $_returnCode = null, $CRLF = "\r\n" )
1810
+	function socket_send_str($_strSend, $_returnCode = null, $CRLF = "\r\n")
1811 1811
 	{
1812 1812
         // phpcs:enable
1813
-		if ($this->_debug) $this->log.=$_strSend;	// @CHANGE LDR for log
1814
-		fputs($this->socket, $_strSend . $CRLF);
1815
-		if ($this->_debug) $this->log.=' ('.$_returnCode.')' . $CRLF;
1813
+		if ($this->_debug) $this->log .= $_strSend; // @CHANGE LDR for log
1814
+		fputs($this->socket, $_strSend.$CRLF);
1815
+		if ($this->_debug) $this->log .= ' ('.$_returnCode.')'.$CRLF;
1816 1816
 
1817
-		if ( $_returnCode )
1817
+		if ($_returnCode)
1818 1818
 		return $this->server_parse($this->socket, $_returnCode);
1819 1819
 	}
1820 1820
 
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
 	 * @param  string $_errMsg  Error Message
1829 1829
 	 * @return void
1830 1830
      */
1831
-    function _setErr( $_errNum, $_errMsg )
1831
+    function _setErr($_errNum, $_errMsg)
1832 1832
     {
1833 1833
         $this->_smtpsErrors[] = array(
1834 1834
             'num' => $_errNum,
@@ -1847,9 +1847,9 @@  discard block
 block discarded – undo
1847 1847
 
1848 1848
 		if (is_array($this->_smtpsErrors))
1849 1849
 		{
1850
-			foreach ( $this->_smtpsErrors as $_err => $_info )
1850
+			foreach ($this->_smtpsErrors as $_err => $_info)
1851 1851
 			{
1852
-				$_errMsg[] = 'Error [' . $_info['num'] .']: '. $_info['msg'];
1852
+				$_errMsg[] = 'Error ['.$_info['num'].']: '.$_info['msg'];
1853 1853
 			}
1854 1854
 		}
1855 1855
 
Please login to merge, or discard this patch.
Braces   +188 added lines, -125 removed lines patch added patch discarded remove patch
@@ -300,8 +300,9 @@  discard block
 block discarded – undo
300 300
      */
301 301
 	function setErrorsTo($_strErrorsTo)
302 302
 	{
303
-		if ( $_strErrorsTo )
304
-		$this->_errorsTo = $this->_strip_email($_strErrorsTo);
303
+		if ( $_strErrorsTo ) {
304
+				$this->_errorsTo = $this->_strip_email($_strErrorsTo);
305
+		}
305 306
 	}
306 307
 
307 308
     /**
@@ -314,10 +315,11 @@  discard block
 block discarded – undo
314 315
 	{
315 316
 		$_retValue = '';
316 317
 
317
-		if ( $_part === true )
318
-		$_retValue = $this->_errorsTo;
319
-		else
320
-		$_retValue = $this->_errorsTo[$_part];
318
+		if ( $_part === true ) {
319
+				$_retValue = $this->_errorsTo;
320
+		} else {
321
+				$_retValue = $this->_errorsTo[$_part];
322
+		}
321 323
 
322 324
 		return $_retValue;
323 325
 	}
@@ -373,8 +375,7 @@  discard block
 block discarded – undo
373 375
 		{
374 376
 			$this->_setErr(99, $host . ' is either offline or is an invalid host name.');
375 377
 			$_retVal = false;
376
-		}
377
-		else
378
+		} else
378 379
 		{
379 380
 			//See if we can connect to the SMTP server
380 381
 			if ($this->socket = @fsockopen(
@@ -383,23 +384,28 @@  discard block
 block discarded – undo
383 384
     			$this->errno,           // actual system level error
384 385
     			$this->errstr,          // and any text that goes with the error
385 386
     			$this->_smtpTimeout
386
-			))  // timeout for reading/writing data over the socket
387
+			)) {
388
+			    // timeout for reading/writing data over the socket
387 389
 			{
388 390
 				// Fix from PHP SMTP class by 'Chris Ryan'
389 391
 				// Sometimes the SMTP server takes a little longer to respond
390 392
 				// so we will give it a longer timeout for the first read
391 393
 				// Windows still does not have support for this timeout function
392 394
 				if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
395
+			}
393 396
 
394 397
 				// Check response from Server
395
-				if ( $_retVal = $this->server_parse($this->socket, "220") )
396
-				$_retVal = $this->socket;
398
+				if ( $_retVal = $this->server_parse($this->socket, "220") ) {
399
+								$_retVal = $this->socket;
400
+				}
397 401
 			}
398 402
 			// This connection attempt failed.
399 403
 			else
400 404
 			{
401 405
 				// @CHANGE LDR
402
-				if (empty($this->errstr)) $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
406
+				if (empty($this->errstr)) {
407
+				    $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
408
+				}
403 409
 				$this->_setErr($this->errno, $this->errstr);
404 410
 				$_retVal = false;
405 411
 			}
@@ -429,7 +435,9 @@  discard block
 block discarded – undo
429 435
 		$host=preg_replace('@ssl://@i','',$host);	// Remove prefix
430 436
 		$host=preg_replace('@tls://@i','',$host);	// Remove prefix
431 437
 
432
-		if ($usetls) $host='tls://'.$host;
438
+		if ($usetls) {
439
+		    $host='tls://'.$host;
440
+		}
433 441
 
434 442
 		$hosth = $host;
435 443
 
@@ -506,10 +514,10 @@  discard block
 block discarded – undo
506 514
 
507 515
 			// The error here just means the ID/password combo doesn't work.
508 516
 			// There is not a method to determine which is the problem, ID or password
509
-			if ( ! $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235') )
510
-			$this->_setErr(130, 'Invalid Authentication Credentials.');
511
-		}
512
-		else
517
+			if ( ! $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235') ) {
518
+						$this->_setErr(130, 'Invalid Authentication Credentials.');
519
+			}
520
+		} else
513 521
 		{
514 522
 			$this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
515 523
 		}
@@ -672,14 +680,17 @@  discard block
 block discarded – undo
672 680
 		{
673 681
 			// Set these properties ONLY if they are set in the php.ini file.
674 682
 			// Otherwise the default values will be used.
675
-			if ( $_host = ini_get('SMTPs') )
676
-			$this->setHost($_host);
683
+			if ( $_host = ini_get('SMTPs') ) {
684
+						$this->setHost($_host);
685
+			}
677 686
 
678
-			if ( $_port = ini_get('smtp_port') )
679
-			$this->setPort($_port);
687
+			if ( $_port = ini_get('smtp_port') ) {
688
+						$this->setPort($_port);
689
+			}
680 690
 
681
-			if ( $_from = ini_get('sendmail_from') )
682
-			$this->setFrom($_from);
691
+			if ( $_from = ini_get('sendmail_from') ) {
692
+						$this->setFrom($_from);
693
+			}
683 694
 		}
684 695
 
685 696
 		// Send back what we have
@@ -698,8 +709,9 @@  discard block
 block discarded – undo
698 709
 	function setTransportType($_type = 0)
699 710
 	{
700 711
 		if ( ( is_numeric($_type) ) &&
701
-		( ( $_type >= 0 ) && ( $_type <= 3 ) ) )
702
-		$this->_transportType = $_type;
712
+		( ( $_type >= 0 ) && ( $_type <= 3 ) ) ) {
713
+				$this->_transportType = $_type;
714
+		}
703 715
 	}
704 716
 
705 717
 	/**
@@ -740,8 +752,9 @@  discard block
 block discarded – undo
740 752
 	 */
741 753
 	function setHost($_strHost)
742 754
 	{
743
-		if ( $_strHost )
744
-		$this->_smtpsHost = $_strHost;
755
+		if ( $_strHost ) {
756
+				$this->_smtpsHost = $_strHost;
757
+		}
745 758
 	}
746 759
 
747 760
 	/**
@@ -766,8 +779,9 @@  discard block
 block discarded – undo
766 779
 	function setPort($_intPort)
767 780
 	{
768 781
 		if ( ( is_numeric($_intPort) ) &&
769
-		( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) )
770
-		$this->_smtpsPort = $_intPort;
782
+		( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) ) {
783
+				$this->_smtpsPort = $_intPort;
784
+		}
771 785
 	}
772 786
 
773 787
 	/**
@@ -832,8 +846,9 @@  discard block
 block discarded – undo
832 846
 	 */
833 847
 	function setCharSet($_strCharSet)
834 848
 	{
835
-		if ( $_strCharSet )
836
-		$this->_smtpsCharSet = $_strCharSet;
849
+		if ( $_strCharSet ) {
850
+				$this->_smtpsCharSet = $_strCharSet;
851
+		}
837 852
 	}
838 853
 
839 854
 	/**
@@ -863,8 +878,9 @@  discard block
 block discarded – undo
863 878
 	 */
864 879
 	function setTransEncode($_strTransEncode)
865 880
 	{
866
-		if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes))
867
-		$this->_smtpsTransEncode = $_strTransEncode;
881
+		if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes)) {
882
+				$this->_smtpsTransEncode = $_strTransEncode;
883
+		}
868 884
 	}
869 885
 
870 886
 	/**
@@ -895,8 +911,9 @@  discard block
 block discarded – undo
895 911
 	 */
896 912
 	function setTransEncodeType($_strTransEncodeType)
897 913
 	{
898
-		if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes))
899
-		$this->_smtpsTransEncodeType = $_strTransEncodeType;
914
+		if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes)) {
915
+				$this->_smtpsTransEncodeType = $_strTransEncodeType;
916
+		}
900 917
 	}
901 918
 
902 919
 	/**
@@ -920,8 +937,9 @@  discard block
 block discarded – undo
920 937
 	 */
921 938
 	function setFrom($_strFrom)
922 939
 	{
923
-		if ( $_strFrom )
924
-		$this->_msgFrom = $this->_strip_email($_strFrom);
940
+		if ( $_strFrom ) {
941
+				$this->_msgFrom = $this->_strip_email($_strFrom);
942
+		}
925 943
 	}
926 944
 
927 945
 	/**
@@ -934,10 +952,11 @@  discard block
 block discarded – undo
934 952
 	{
935 953
 		$_retValue = '';
936 954
 
937
-		if ( $_part === true )
938
-		$_retValue = $this->_msgFrom;
939
-		else
940
-		$_retValue = $this->_msgFrom[$_part];
955
+		if ( $_part === true ) {
956
+				$_retValue = $this->_msgFrom;
957
+		} else {
958
+				$_retValue = $this->_msgFrom[$_part];
959
+		}
941 960
 
942 961
 		return $_retValue;
943 962
 	}
@@ -950,8 +969,9 @@  discard block
 block discarded – undo
950 969
 	 */
951 970
 	function setReplyTo($_strReplyTo)
952 971
 	{
953
-	    if ( $_strReplyTo )
954
-	        $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
972
+	    if ( $_strReplyTo ) {
973
+	    	        $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
974
+	    }
955 975
 	}
956 976
 
957 977
 	/**
@@ -964,10 +984,11 @@  discard block
 block discarded – undo
964 984
 	{
965 985
 	    $_retValue = '';
966 986
 
967
-	    if ( $_part === true )
968
-	        $_retValue = $this->_msgReplyTo;
969
-	    else
970
-	        $_retValue = $this->_msgReplyTo[$_part];
987
+	    if ( $_part === true ) {
988
+	    	        $_retValue = $this->_msgReplyTo;
989
+	    } else {
990
+	    	        $_retValue = $this->_msgReplyTo[$_part];
991
+	    }
971 992
 
972 993
 	    return $_retValue;
973 994
 	}
@@ -996,13 +1017,15 @@  discard block
 block discarded – undo
996 1017
 			if ( is_string($_addrList) )
997 1018
 			{
998 1019
 				// This could be a COMMA delimited string
999
-				if ( strstr($_addrList, ',') )
1000
-				// "explode "list" into an array
1020
+				if ( strstr($_addrList, ',') ) {
1021
+								// "explode "list" into an array
1001 1022
 				$_addrList = explode(',', $_addrList);
1023
+				}
1002 1024
 
1003 1025
 				// Stick it in an array
1004
-				else
1005
-				$_addrList = array($_addrList);
1026
+				else {
1027
+								$_addrList = array($_addrList);
1028
+				}
1006 1029
 			}
1007 1030
 
1008 1031
 			// take the array of addresses and split them further
@@ -1076,13 +1099,14 @@  discard block
 block discarded – undo
1076 1099
 		if ( count($_tmpAry) == 2 )
1077 1100
 		{
1078 1101
 			// We may not really have a "Real Name"
1079
-			if ( $_tmpAry[0])
1080
-			$_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1102
+			if ( $_tmpAry[0]) {
1103
+						$_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1104
+			}
1081 1105
 
1082 1106
 			$_aryEmail['addr'] = $_tmpAry[1];
1107
+		} else {
1108
+				$_aryEmail['addr'] = $_tmpAry[0];
1083 1109
 		}
1084
-		else
1085
-		$_aryEmail['addr'] = $_tmpAry[0];
1086 1110
 
1087 1111
 		// Pull User Name and Host.tld apart
1088 1112
 		list($_aryEmail['user'], $_aryEmail['host'] ) = explode('@', $_aryEmail['addr']);
@@ -1149,12 +1173,13 @@  discard block
 block discarded – undo
1149 1173
 					{
1150 1174
 						foreach ( $this->_msgRecipients[$_host][$_which] as $_addr => $_realName )
1151 1175
 						{
1152
-							if ( $_realName )	// @CHANGE LDR
1176
+							if ( $_realName ) {
1177
+							    // @CHANGE LDR
1153 1178
 							{
1154 1179
 								$_realName = '"' . $_realName . '"';
1155
-								$_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>';
1156 1180
 							}
1157
-							else
1181
+								$_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>';
1182
+							} else
1158 1183
 							{
1159 1184
 								$_RCPT_list[] = $_addr . '@' . $_host;
1160 1185
 							}
@@ -1163,14 +1188,12 @@  discard block
 block discarded – undo
1163 1188
 				}
1164 1189
 
1165 1190
 				return implode(', ', $_RCPT_list);
1166
-			}
1167
-			else
1191
+			} else
1168 1192
 			{
1169 1193
 				$this->_setErr(101, 'No eMail Address for message to be sent to.');
1170 1194
 				return false;
1171 1195
 			}
1172
-		}
1173
-		else
1196
+		} else
1174 1197
 		{
1175 1198
 			$this->_setErr(102, 'eMail type not defined.');
1176 1199
 			return false;
@@ -1185,8 +1208,9 @@  discard block
 block discarded – undo
1185 1208
 	 */
1186 1209
 	function setTO($_addrTo)
1187 1210
 	{
1188
-		if ( $_addrTo )
1189
-		$this->_buildAddrList('to', $_addrTo);
1211
+		if ( $_addrTo ) {
1212
+				$this->_buildAddrList('to', $_addrTo);
1213
+		}
1190 1214
 	}
1191 1215
 
1192 1216
 	/**
@@ -1207,8 +1231,9 @@  discard block
 block discarded – undo
1207 1231
 	 */
1208 1232
 	function setCC($_strCC)
1209 1233
 	{
1210
-		if ( $_strCC )
1211
-		$this->_buildAddrList('cc', $_strCC);
1234
+		if ( $_strCC ) {
1235
+				$this->_buildAddrList('cc', $_strCC);
1236
+		}
1212 1237
 	}
1213 1238
 
1214 1239
 	/**
@@ -1229,8 +1254,9 @@  discard block
 block discarded – undo
1229 1254
 	 */
1230 1255
 	function setBCC($_strBCC)
1231 1256
 	{
1232
-		if ( $_strBCC )
1233
-		$this->_buildAddrList('bcc', $_strBCC);
1257
+		if ( $_strBCC ) {
1258
+				$this->_buildAddrList('bcc', $_strBCC);
1259
+		}
1234 1260
 	}
1235 1261
 
1236 1262
 	/**
@@ -1251,8 +1277,9 @@  discard block
 block discarded – undo
1251 1277
 	 */
1252 1278
 	function setSubject($_strSubject = '')
1253 1279
 	{
1254
-		if ( $_strSubject )
1255
-		$this->_msgSubject = $_strSubject;
1280
+		if ( $_strSubject ) {
1281
+				$this->_msgSubject = $_strSubject;
1282
+		}
1256 1283
 	}
1257 1284
 
1258 1285
 	/**
@@ -1277,8 +1304,9 @@  discard block
 block discarded – undo
1277 1304
 		$_header = 'From: '       . $this->getFrom('org') . "\r\n"
1278 1305
 		. 'To: '         . $this->getTO()          . "\r\n";
1279 1306
 
1280
-		if ( $this->getCC() )
1281
-		$_header .= 'Cc: ' . $this->getCC()  . "\r\n";
1307
+		if ( $this->getCC() ) {
1308
+				$_header .= 'Cc: ' . $this->getCC()  . "\r\n";
1309
+		}
1282 1310
 
1283 1311
 		/* Note:
1284 1312
 		 * BCC email addresses must be listed in the RCPT TO command list,
@@ -1311,33 +1339,41 @@  discard block
 block discarded – undo
1311 1339
 			$_header .= 'Message-ID: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1312 1340
 			$_header .= 'References: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
1313 1341
 			$_header .= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host . "\r\n";
1314
-		}
1315
-		else
1342
+		} else
1316 1343
 		{
1317 1344
 			$_header .= 'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n";
1318 1345
 		}
1319
-		if (! empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n";
1320
-		if ( $this->getMoreInHeader() )
1321
-		    $_header .= $this->getMoreInHeader();     // Value must include the "\r\n";
1346
+		if (! empty($_SERVER['REMOTE_ADDR'])) {
1347
+		    $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n";
1348
+		}
1349
+		if ( $this->getMoreInHeader() ) {
1350
+				    $_header .= $this->getMoreInHeader();
1351
+		}
1352
+		// Value must include the "\r\n";
1322 1353
 
1323 1354
 		//$_header .=
1324 1355
 		//                 'Read-Receipt-To: '   . $this->getFrom( 'org' ) . "\r\n"
1325 1356
 		//                 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
1326 1357
 
1327
-		if ( $this->getSensitivity() )
1328
-		$_header .= 'Sensitivity: ' . $this->getSensitivity()  . "\r\n";
1358
+		if ( $this->getSensitivity() ) {
1359
+				$_header .= 'Sensitivity: ' . $this->getSensitivity()  . "\r\n";
1360
+		}
1329 1361
 
1330
-		if ( $this->_msgPriority != 3 )
1331
-		$_header .= $this->getPriority();
1362
+		if ( $this->_msgPriority != 3 ) {
1363
+				$_header .= $this->getPriority();
1364
+		}
1332 1365
 
1333 1366
 
1334 1367
 		// @CHANGE LDR
1335
-		if ( $this->getDeliveryReceipt() )
1336
-		    $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n";
1337
-		if ( $this->getErrorsTo() )
1338
-		    $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n";
1339
-		if ( $this->getReplyTo() )
1340
-		    $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n";
1368
+		if ( $this->getDeliveryReceipt() ) {
1369
+				    $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n";
1370
+		}
1371
+		if ( $this->getErrorsTo() ) {
1372
+				    $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n";
1373
+		}
1374
+		if ( $this->getReplyTo() ) {
1375
+				    $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n";
1376
+		}
1341 1377
 
1342 1378
 		$_header .= 'X-Mailer: Dolibarr version ' . DOL_VERSION .' (using SMTPs Mailer)' . "\r\n";
1343 1379
 		$_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART?'MAIN_MAIL_USE_MULTI_PART':'No MAIN_MAIL_USE_MULTI_PART') . "\r\n";
@@ -1358,10 +1394,11 @@  discard block
 block discarded – undo
1358 1394
 	{
1359 1395
 		//if ( $strContent )
1360 1396
 		//{
1361
-		if ( $strType == 'html' )
1362
-		$strMimeType = 'text/html';
1363
-		else
1364
-		$strMimeType = 'text/plain';
1397
+		if ( $strType == 'html' ) {
1398
+				$strMimeType = 'text/html';
1399
+		} else {
1400
+				$strMimeType = 'text/plain';
1401
+		}
1365 1402
 
1366 1403
 		// Make RFC821 Compliant, replace bare linefeeds
1367 1404
 		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent);
@@ -1385,8 +1422,9 @@  discard block
 block discarded – undo
1385 1422
 		$this->_msgContent[$strType]['data']     = $strContent;
1386 1423
 		$this->_msgContent[$strType]['dataText'] = $strContentAltText;
1387 1424
 
1388
-		if ( $this->getMD5flag() )
1389
-		$this->_msgContent[$strType]['md5']      = dol_hash($strContent, 3);
1425
+		if ( $this->getMD5flag() ) {
1426
+				$this->_msgContent[$strType]['md5']      = dol_hash($strContent, 3);
1427
+		}
1390 1428
 		//}
1391 1429
 	}
1392 1430
 
@@ -1409,8 +1447,9 @@  discard block
 block discarded – undo
1409 1447
 		$keyCount = count($_types);
1410 1448
 
1411 1449
 		// If we have ZERO, we have a problem
1412
-		if( $keyCount === 0 )
1413
-		die ("Sorry, no content");
1450
+		if( $keyCount === 0 ) {
1451
+				die ("Sorry, no content");
1452
+		}
1414 1453
 
1415 1454
 		// If we have ONE, we can use the simple format
1416 1455
 		else if( $keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
@@ -1423,8 +1462,9 @@  discard block
 block discarded – undo
1423 1462
 			. 'Content-Disposition: inline'  . "\r\n"
1424 1463
 			. 'Content-Description: Message' . "\r\n";
1425 1464
 
1426
-			if ( $this->getMD5flag() )
1427
-			$content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
1465
+			if ( $this->getMD5flag() ) {
1466
+						$content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
1467
+			}
1428 1468
 
1429 1469
 			$content .= "\r\n"
1430 1470
 			.  $_msgData['data'] . "\r\n";
@@ -1447,9 +1487,11 @@  discard block
 block discarded – undo
1447 1487
 
1448 1488
 			$content .= "--" . $this->_getBoundary('mixed') . "\r\n";
1449 1489
 
1450
-			if (key_exists('image', $this->_msgContent))     // If inline image found
1490
+			if (key_exists('image', $this->_msgContent)) {
1491
+			    // If inline image found
1451 1492
 			{
1452 1493
 				$content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1494
+			}
1453 1495
 				$content .= "\r\n";
1454 1496
 				$content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1455 1497
 			}
@@ -1472,8 +1514,9 @@  discard block
 block discarded – undo
1472 1514
 						.  'Content-Transfer-Encoding: base64' . "\r\n"
1473 1515
 						.  'Content-Description: ' . $_data['fileName'] ."\r\n";
1474 1516
 
1475
-						if ( $this->getMD5flag() )
1476
-						$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1517
+						if ( $this->getMD5flag() ) {
1518
+												$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1519
+						}
1477 1520
 
1478 1521
 						$content .= "\r\n" .  $_data['data'] . "\r\n\r\n";
1479 1522
 					}
@@ -1491,8 +1534,9 @@  discard block
 block discarded – undo
1491 1534
 						.  'Content-Disposition: inline; filename="' . $_data['imageName'] . '"' . "\r\n"
1492 1535
 						.  'Content-ID: <' . $_data['cid'] . '> ' . "\r\n";
1493 1536
 
1494
-						if ( $this->getMD5flag() )
1495
-						$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1537
+						if ( $this->getMD5flag() ) {
1538
+												$content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
1539
+						}
1496 1540
 
1497 1541
 						$content .= "\r\n"
1498 1542
 						. $_data['data'] . "\r\n";
@@ -1502,8 +1546,7 @@  discard block
 block discarded – undo
1502 1546
 					$content.= "--" . $this->_getBoundary('related') . "--" . "\r\n";
1503 1547
 					$content.= "\r\n" . "--" . $this->_getBoundary('alternative') . "--" . "\r\n";
1504 1548
 					$content.= "\r\n";
1505
-				}
1506
-				else
1549
+				} else
1507 1550
 				{
1508 1551
 					if (key_exists('image', $this->_msgContent))
1509 1552
 					{
@@ -1515,9 +1558,11 @@  discard block
 block discarded – undo
1515 1558
 						$content.= "--" . $this->_getBoundary('related') . "\r\n";
1516 1559
 					}
1517 1560
 
1518
-					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
1561
+					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1562
+					    // Add plain text message part before html part
1519 1563
 					{
1520 1564
 					    $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
1565
+					}
1521 1566
     					$content .= "\r\n";
1522 1567
 	       				$content .= "--" . $this->_getBoundary('alternative') . "\r\n";
1523 1568
 
@@ -1538,15 +1583,18 @@  discard block
 block discarded – undo
1538 1583
 					//                             . 'Content-Disposition: inline'  . "\r\n"
1539 1584
 					//                             . 'Content-Description: ' . $type . ' message' . "\r\n";
1540 1585
 
1541
-					if ( $this->getMD5flag() )
1542
-					$content .= 'Content-MD5: ' . $_content['md5'] . "\r\n";
1586
+					if ( $this->getMD5flag() ) {
1587
+										$content .= 'Content-MD5: ' . $_content['md5'] . "\r\n";
1588
+					}
1543 1589
 
1544 1590
 					$content .= "\r\n"	. $_content['data'] . "\r\n";
1545 1591
 
1546
-					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
1592
+					if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1593
+					    // Add plain text message part after html part
1547 1594
 					{
1548 1595
 					    $content.= "--" . $this->_getBoundary('alternative') . "--". "\r\n";
1549 1596
 					}
1597
+					}
1550 1598
 
1551 1599
 					$content .= "\r\n";
1552 1600
 				}
@@ -1579,8 +1627,9 @@  discard block
 block discarded – undo
1579 1627
 			$this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName;
1580 1628
 			$this->_msgContent['attachment'][$strFileName]['data']     = $strContent;
1581 1629
 
1582
-			if ( $this->getMD5flag() )
1583
-			$this->_msgContent['attachment'][$strFileName]['md5']      = dol_hash($strContent, 3);
1630
+			if ( $this->getMD5flag() ) {
1631
+						$this->_msgContent['attachment'][$strFileName]['md5']      = dol_hash($strContent, 3);
1632
+			}
1584 1633
 		}
1585 1634
 	}
1586 1635
 
@@ -1606,8 +1655,9 @@  discard block
 block discarded – undo
1606 1655
 			$this->_msgContent['image'][$strImageName]['cid']      = $strImageCid;
1607 1656
 			$this->_msgContent['image'][$strImageName]['data']     = $strContent;
1608 1657
 
1609
-			if ( $this->getMD5flag() )
1610
-			$this->_msgContent['image'][$strImageName]['md5']      = dol_hash($strContent, 3);
1658
+			if ( $this->getMD5flag() ) {
1659
+						$this->_msgContent['image'][$strImageName]['md5']      = dol_hash($strContent, 3);
1660
+			}
1611 1661
 		}
1612 1662
 	}
1613 1663
 	// END @CHANGE LDR
@@ -1627,8 +1677,9 @@  discard block
 block discarded – undo
1627 1677
 	function setSensitivity($_value = 0)
1628 1678
 	{
1629 1679
 		if ( ( is_numeric($_value) ) &&
1630
-		( ( $_value >= 0 ) && ( $_value <= 3 ) ) )
1631
-		$this->_msgSensitivity = $_value;
1680
+		( ( $_value >= 0 ) && ( $_value <= 3 ) ) ) {
1681
+				$this->_msgSensitivity = $_value;
1682
+		}
1632 1683
 	}
1633 1684
 
1634 1685
 	/**
@@ -1662,8 +1713,9 @@  discard block
 block discarded – undo
1662 1713
 	function setPriority( $_value = 3 )
1663 1714
 	{
1664 1715
 		if ( ( is_numeric($_value) ) &&
1665
-		( ( $_value >= 0 ) && ( $_value <= 5 ) ) )
1666
-		$this->_msgPriority = $_value;
1716
+		( ( $_value >= 0 ) && ( $_value <= 5 ) ) ) {
1717
+				$this->_msgPriority = $_value;
1718
+		}
1667 1719
 	}
1668 1720
 
1669 1721
 	/**
@@ -1716,8 +1768,9 @@  discard block
 block discarded – undo
1716 1768
 	 */
1717 1769
 	function setXheader($strXdata)
1718 1770
 	{
1719
-		if ( $strXdata )
1720
-		$this->_msgXheader[] = $strXdata;
1771
+		if ( $strXdata ) {
1772
+				$this->_msgXheader[] = $strXdata;
1773
+		}
1721 1774
 	}
1722 1775
 
1723 1776
 	/**
@@ -1750,9 +1803,13 @@  discard block
 block discarded – undo
1750 1803
 	 */
1751 1804
 	function _getBoundary($type='mixed')
1752 1805
 	{
1753
-		if ($type == 'mixed') return $this->_smtpsBoundary;
1754
-		else if ($type == 'related') return $this->_smtpsRelatedBoundary;
1755
-		else if ($type == 'alternative') return $this->_smtpsAlternativeBoundary;
1806
+		if ($type == 'mixed') {
1807
+		    return $this->_smtpsBoundary;
1808
+		} else if ($type == 'related') {
1809
+		    return $this->_smtpsRelatedBoundary;
1810
+		} else if ($type == 'alternative') {
1811
+		    return $this->_smtpsAlternativeBoundary;
1812
+		}
1756 1813
 	}
1757 1814
 
1758 1815
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1810,12 +1867,18 @@  discard block
 block discarded – undo
1810 1867
 	function socket_send_str( $_strSend, $_returnCode = null, $CRLF = "\r\n" )
1811 1868
 	{
1812 1869
         // phpcs:enable
1813
-		if ($this->_debug) $this->log.=$_strSend;	// @CHANGE LDR for log
1870
+		if ($this->_debug) {
1871
+		    $this->log.=$_strSend;
1872
+		}
1873
+		// @CHANGE LDR for log
1814 1874
 		fputs($this->socket, $_strSend . $CRLF);
1815
-		if ($this->_debug) $this->log.=' ('.$_returnCode.')' . $CRLF;
1875
+		if ($this->_debug) {
1876
+		    $this->log.=' ('.$_returnCode.')' . $CRLF;
1877
+		}
1816 1878
 
1817
-		if ( $_returnCode )
1818
-		return $this->server_parse($this->socket, $_returnCode);
1879
+		if ( $_returnCode ) {
1880
+				return $this->server_parse($this->socket, $_returnCode);
1881
+		}
1819 1882
 	}
1820 1883
 
1821 1884
 	// =============================================================
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/commonobjectline.class.php 3 patches
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -29,25 +29,25 @@  discard block
 block discarded – undo
29 29
  */
30 30
 abstract class CommonObjectLine extends CommonObject
31 31
 {
32
-	/**
33
-	 * Id of the line
34
-	 * @var int
35
-	 */
36
-	public $id;
32
+    /**
33
+     * Id of the line
34
+     * @var int
35
+     */
36
+    public $id;
37 37
 
38
-	/**
39
-	 * Id of the line
40
-	 * @var int
41
-	 * @deprecated Try to use id property as possible (even if field into database is still rowid)
42
-	 * @see id
43
-	 */
44
-	public $rowid;
38
+    /**
39
+     * Id of the line
40
+     * @var int
41
+     * @deprecated Try to use id property as possible (even if field into database is still rowid)
42
+     * @see id
43
+     */
44
+    public $rowid;
45 45
 
46
-	/**
47
-	 * Product/service unit code ('km', 'm', 'p', ...)
48
-	 * @var string
49
-	 */
50
-	public $fk_unit;
46
+    /**
47
+     * Product/service unit code ('km', 'm', 'p', ...)
48
+     * @var string
49
+     */
50
+    public $fk_unit;
51 51
 
52 52
 
53 53
     /**
@@ -57,40 +57,40 @@  discard block
 block discarded – undo
57 57
      * 	@param	string $type Label type (long or short)
58 58
      *	@return	string|int <0 if ko, label if ok
59 59
      */
60
-	public function getLabelOfUnit($type='long')
61
-	{
62
-		global $langs;
60
+    public function getLabelOfUnit($type='long')
61
+    {
62
+        global $langs;
63 63
 
64
-		if (!$this->fk_unit) {
65
-			return '';
66
-		}
64
+        if (!$this->fk_unit) {
65
+            return '';
66
+        }
67 67
 
68
-		$langs->load('products');
68
+        $langs->load('products');
69 69
 
70
-		$label_type = 'label';
70
+        $label_type = 'label';
71 71
 
72
-		if ($type == 'short')
73
-		{
74
-			$label_type = 'short_label';
75
-		}
72
+        if ($type == 'short')
73
+        {
74
+            $label_type = 'short_label';
75
+        }
76 76
 
77
-		$sql = 'select '.$label_type.' from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit;
78
-		$resql = $this->db->query($sql);
79
-		if($resql && $this->db->num_rows($resql) > 0)
80
-		{
81
-			$res = $this->db->fetch_array($resql);
82
-			$label = $res[$label_type];
83
-			$this->db->free($resql);
84
-			return $label;
85
-		}
86
-		else
87
-		{
88
-			$this->error=$this->db->error().' sql='.$sql;
89
-			dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
90
-			return -1;
91
-		}
92
-	}
93
-	// Currently we need function at end of file CommonObject for all object lines. Should find a way to avoid duplicate code.
77
+        $sql = 'select '.$label_type.' from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit;
78
+        $resql = $this->db->query($sql);
79
+        if($resql && $this->db->num_rows($resql) > 0)
80
+        {
81
+            $res = $this->db->fetch_array($resql);
82
+            $label = $res[$label_type];
83
+            $this->db->free($resql);
84
+            return $label;
85
+        }
86
+        else
87
+        {
88
+            $this->error=$this->db->error().' sql='.$sql;
89
+            dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
90
+            return -1;
91
+        }
92
+    }
93
+    // Currently we need function at end of file CommonObject for all object lines. Should find a way to avoid duplicate code.
94 94
 
95
-	// For the moment we use the extends on CommonObject until PHP min is 5.4 so use Traits.
95
+    // For the moment we use the extends on CommonObject until PHP min is 5.4 so use Traits.
96 96
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
      * 	@param	string $type Label type (long or short)
58 58
      *	@return	string|int <0 if ko, label if ok
59 59
      */
60
-	public function getLabelOfUnit($type='long')
60
+	public function getLabelOfUnit($type = 'long')
61 61
 	{
62 62
 		global $langs;
63 63
 
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 
77 77
 		$sql = 'select '.$label_type.' from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit;
78 78
 		$resql = $this->db->query($sql);
79
-		if($resql && $this->db->num_rows($resql) > 0)
79
+		if ($resql && $this->db->num_rows($resql) > 0)
80 80
 		{
81 81
 			$res = $this->db->fetch_array($resql);
82 82
 			$label = $res[$label_type];
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 		}
86 86
 		else
87 87
 		{
88
-			$this->error=$this->db->error().' sql='.$sql;
88
+			$this->error = $this->db->error().' sql='.$sql;
89 89
 			dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
90 90
 			return -1;
91 91
 		}
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -82,8 +82,7 @@
 block discarded – undo
82 82
 			$label = $res[$label_type];
83 83
 			$this->db->free($resql);
84 84
 			return $label;
85
-		}
86
-		else
85
+		} else
87 86
 		{
88 87
 			$this->error=$this->db->error().' sql='.$sql;
89 88
 			dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/fiscalyear.class.php 3 patches
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -28,384 +28,384 @@
 block discarded – undo
28 28
  */
29 29
 class Fiscalyear extends CommonObject
30 30
 {
31
-	/**
32
-	 * @var string ID to identify managed object
33
-	 */
34
-	public $element='fiscalyear';
35
-
36
-	/**
37
-	 * @var string Name of table without prefix where object is stored
38
-	 */
39
-	public $table_element='accounting_fiscalyear';
40
-
41
-	/**
42
-	 * @var int    Name of subtable line
43
-	 */
44
-	public $table_element_line = '';
45
-
46
-	/**
47
-	 * @var int Field with ID of parent key if this field has a parent
48
-	 */
49
-	public $fk_element = '';
50
-
51
-	/**
52
-	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
53
-	 * @var int
54
-	 */
55
-	public $ismultientitymanaged = 1;
56
-
57
-	/**
58
-	 * @var int ID
59
-	 */
60
-	public $rowid;
61
-
62
-	/**
63
-	 * @var string fiscal year label
64
-	 */
65
-	public $label;
66
-
67
-	public $date_start;
68
-	public $date_end;
69
-	public $datec;
70
-	public $statut;		// 0=open, 1=closed
71
-
72
-	/**
73
-	 * @var int Entity
74
-	 */
75
-	public $entity;
76
-
77
-	public $statuts=array();
78
-	public $statuts_short=array();
79
-
80
-	/**
81
-	 * Constructor
82
-	 *
83
-	 * @param	DoliDB		$db		Database handler
84
-	 */
85
-	function __construct(DoliDB $db)
86
-	{
87
-		global $langs;
88
-
89
-		$this->db = $db;
90
-
91
-		$this->statuts_short = array(0 => 'Opened', 1 => 'Closed');
92
-		$this->statuts = array(0 => 'Opened', 1 => 'Closed');
93
-	}
94
-
95
-	/**
96
-	 *	Create object in database
97
-	 *
98
-	 *	@param		User	$user   User making creation
99
-	 *	@return 	int				<0 if KO, >0 if OK
100
-	 */
101
-	function create($user)
102
-	{
103
-		global $conf;
104
-
105
-		$error = 0;
106
-
107
-		$now=dol_now();
108
-
109
-		$this->db->begin();
110
-
111
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_fiscalyear (";
112
-		$sql.= "label";
113
-		$sql.= ", date_start";
114
-		$sql.= ", date_end";
115
-		$sql.= ", statut";
116
-		$sql.= ", entity";
117
-		$sql.= ", datec";
118
-		$sql.= ", fk_user_author";
119
-		$sql.= ") VALUES (";
120
-		$sql.= " '".$this->db->escape($this->label)."'";
121
-		$sql.= ", '".$this->db->idate($this->date_start)."'";
122
-		$sql.= ", ".($this->date_end ? "'".$this->db->idate($this->date_end)."'":"null");
123
-		$sql.= ", 0";
124
-		$sql.= ", ".$conf->entity;
125
-		$sql.= ", '".$this->db->idate($now)."'";
126
-		$sql.= ", ". $user->id;
127
-		$sql.= ")";
128
-
129
-		dol_syslog(get_class($this)."::create", LOG_DEBUG);
130
-		$result = $this->db->query($sql);
131
-		if ($result)
132
-		{
133
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."accounting_fiscalyear");
134
-
135
-			$result=$this->update($user);
136
-			if ($result > 0)
137
-			{
138
-				$this->db->commit();
139
-				return $this->id;
140
-			}
141
-			else
142
-			{
143
-				$this->error=$this->db->lasterror();
144
-				$this->db->rollback();
145
-				return $result;
146
-			}
147
-		}
148
-		else
149
-		{
150
-			$this->error=$this->db->lasterror()." sql=".$sql;
151
-			$this->db->rollback();
152
-			return -1;
153
-		}
154
-	}
155
-
156
-	/**
157
-	 *	Update record
158
-	 *
159
-	 *	@param	User	$user		User making update
160
-	 *	@return	int					<0 if KO, >0 if OK
161
-	 */
162
-	function update($user)
163
-	{
164
-		global $langs;
165
-
166
-		// Check parameters
167
-		if (empty($this->date_start) && empty($this->date_end))
168
-		{
169
-			$this->error='ErrorBadParameter';
170
-			return -1;
171
-		}
172
-
173
-		$this->db->begin();
174
-
175
-		$sql = "UPDATE ".MAIN_DB_PREFIX."accounting_fiscalyear";
176
-		$sql .= " SET label = '".$this->db->escape($this->label)."'";
177
-		$sql .= ", date_start = '".$this->db->idate($this->date_start)."'";
178
-		$sql .= ", date_end = ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null");
179
-		$sql .= ", statut = '".$this->db->escape($this->statut?$this->statut:0)."'";
180
-		$sql .= ", datec = " . ($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null');
181
-		$sql .= ", fk_user_modif = " . $user->id;
182
-		$sql .= " WHERE rowid = ".$this->id;
183
-
184
-		dol_syslog(get_class($this)."::update", LOG_DEBUG);
185
-		$result = $this->db->query($sql);
186
-		if ($result)
187
-		{
188
-			$this->db->commit();
189
-			return 1;
190
-		}
191
-		else
192
-		{
193
-			$this->error=$this->db->lasterror();
194
-			dol_syslog($this->error, LOG_ERR);
195
-			$this->db->rollback();
196
-			return -1;
197
-		}
198
-	}
199
-
200
-	/**
201
-	* Load an object from database
202
-	*
203
-	* @param	int		$id		Id of record to load
204
-	* @return	int				<0 if KO, >0 if OK
205
-	*/
206
-	function fetch($id)
207
-	{
208
-		$sql = "SELECT rowid, label, date_start, date_end, statut";
209
-		$sql.= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear";
210
-		$sql.= " WHERE rowid = ".$id;
211
-
212
-		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
213
-		$result = $this->db->query($sql);
214
-		if ( $result )
215
-		{
216
-			$obj = $this->db->fetch_object($result);
217
-
218
-			$this->id			= $obj->rowid;
219
-			$this->ref			= $obj->rowid;
220
-			$this->date_start	= $this->db->jdate($obj->date_start);
221
-			$this->date_end		= $this->db->jdate($obj->date_end);
222
-			$this->label		= $obj->label;
223
-			$this->statut	    = $obj->statut;
224
-
225
-			return 1;
226
-		}
227
-		else
228
-		{
229
-			$this->error=$this->db->lasterror();
230
-			return -1;
231
-		}
232
-	}
233
-
234
-   /**
235
-	*	Delete record
236
-	*
237
-	*	@param	int		$id		Id of record to delete
238
-	*	@return	int				<0 if KO, >0 if OK
239
-	*/
240
-	function delete($id)
241
-	{
242
-		$this->db->begin();
243
-
244
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE rowid = ".$id;
245
-
246
-		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
247
-		$result = $this->db->query($sql);
248
-		if ($result)
249
-		{
250
-			$this->db->commit();
251
-			return 1;
252
-		}
253
-		else
254
-		{
255
-			$this->error=$this->db->lasterror();
256
-			$this->db->rollback();
257
-			return -1;
258
-		}
259
-	}
260
-
261
-	/**
262
-	 * Give a label from a status
263
-	 *
264
-	 * @param	int		$mode   	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
265
-	 * @return  string   		   	Label
266
-	 */
267
-	function getLibStatut($mode=0)
268
-	{
269
-		return $this->LibStatut($this->statut,$mode);
270
-	}
271
-
272
-	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
273
-	/**
274
-	 *  Give a label from a status
275
-	 *
276
-	 *  @param	int		$statut     Id status
277
-	 *  @param  int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
278
-	 *  @return string      		Label
279
-	 */
280
-	function LibStatut($statut,$mode=0)
281
-	{
282
-		// phpcs:enable
283
-		global $langs;
284
-
285
-		if ($mode == 0)
286
-		{
287
-			return $langs->trans($this->statuts[$statut]);
288
-		}
289
-		elseif ($mode == 1)
290
-		{
291
-			return $langs->trans($this->statuts_short[$statut]);
292
-		}
293
-		elseif ($mode == 2)
294
-		{
295
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
296
-			elseif ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts_short[$statut]);
297
-		}
298
-		elseif ($mode == 3)
299
-		{
300
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
301
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8');
302
-		}
303
-		elseif ($mode == 4)
304
-		{
305
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
306
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]);
307
-		}
308
-		elseif ($mode == 5)
309
-		{
310
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
311
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
312
-		}
313
-	}
314
-
315
-	/**
316
-	 * Information on record
317
-	 *
318
-	 * @param	int		$id      Id of record
319
-	 * @return	void
320
-	 */
321
-	function info($id)
322
-	{
323
-		$sql = 'SELECT fy.rowid, fy.datec, fy.fk_user_author, fy.fk_user_modif,';
324
-		$sql.= ' fy.tms';
325
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'accounting_fiscalyear as fy';
326
-		$sql.= ' WHERE fy.rowid = '.$id;
327
-
328
-		dol_syslog(get_class($this)."::fetch info", LOG_DEBUG);
329
-		$result = $this->db->query($sql);
330
-
331
-		if ($result)
332
-		{
333
-			if ($this->db->num_rows($result))
334
-			{
335
-				$obj = $this->db->fetch_object($result);
336
-				$this->id = $obj->rowid;
337
-				if ($obj->fk_user_author)
338
-				{
339
-					$cuser = new User($this->db);
340
-					$cuser->fetch($obj->fk_user_author);
341
-					$this->user_creation = $cuser;
342
-				}
343
-				if ($obj->fk_user_modif)
344
-				{
345
-					$muser = new User($this->db);
346
-					$muser->fetch($obj->fk_user_modif);
347
-					$this->user_modification = $muser;
348
-				}
349
-				$this->date_creation     = $this->db->jdate($obj->datec);
350
-				$this->date_modification = $this->db->jdate($obj->tms);
351
-			}
352
-			$this->db->free($result);
353
-		}
354
-		else
355
-		{
356
-			dol_print_error($this->db);
357
-		}
358
-	}
359
-
360
-	/**
361
-	 *  Return the number of entries by fiscal year
362
-	 *
363
-	 *	@param	int		$datestart	Date start to scan
364
-	 *	@param	int		$dateend	Date end to scan
365
-	 *	@return	string				Number of entries
366
-	 */
367
-	function getAccountancyEntriesByFiscalYear($datestart, $dateend)
368
-	{
369
-		global $conf;
370
-
371
-		$sql = "SELECT count(DISTINCT piece_num) as nb";
372
-		$sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
373
-		$sql.= " WHERE doc_date >= '".$datestart."' and doc_date <= '".$dateend."'";
374
-
375
-		$resql=$this->db->query($sql);
376
-		if ($resql)
377
-		{
378
-			$obj = $this->db->fetch_object($resql);
379
-			$nb = $obj->nb;
380
-		}
381
-		else dol_print_error($this->db);
382
-
383
-		return $nb;
384
-	}
385
-
386
-	/**
387
-	 *  Return the number of movements by fiscal year
388
-	 *
389
-	 *	@param	int		$datestart	Date start to scan
390
-	 *	@param	int		$dateend	Date end to scan
391
-	 *	@return	string				Number of movements
392
-	 */
393
-	function getAccountancyMovementsByFiscalYear($datestart, $dateend)
394
-	{
395
-		global $conf;
396
-
397
-		$sql = "SELECT count(rowid) as nb";
398
-		$sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
399
-		$sql.= " WHERE doc_date >= '".$datestart."' AND doc_date <= '".$dateend."'";
400
-
401
-		$resql=$this->db->query($sql);
402
-		if ($resql)
403
-		{
404
-			$obj = $this->db->fetch_object($resql);
405
-			$nb = $obj->nb;
406
-		}
407
-		else dol_print_error($this->db);
408
-
409
-		return $nb;
410
-	}
31
+    /**
32
+     * @var string ID to identify managed object
33
+     */
34
+    public $element='fiscalyear';
35
+
36
+    /**
37
+     * @var string Name of table without prefix where object is stored
38
+     */
39
+    public $table_element='accounting_fiscalyear';
40
+
41
+    /**
42
+     * @var int    Name of subtable line
43
+     */
44
+    public $table_element_line = '';
45
+
46
+    /**
47
+     * @var int Field with ID of parent key if this field has a parent
48
+     */
49
+    public $fk_element = '';
50
+
51
+    /**
52
+     * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
53
+     * @var int
54
+     */
55
+    public $ismultientitymanaged = 1;
56
+
57
+    /**
58
+     * @var int ID
59
+     */
60
+    public $rowid;
61
+
62
+    /**
63
+     * @var string fiscal year label
64
+     */
65
+    public $label;
66
+
67
+    public $date_start;
68
+    public $date_end;
69
+    public $datec;
70
+    public $statut;		// 0=open, 1=closed
71
+
72
+    /**
73
+     * @var int Entity
74
+     */
75
+    public $entity;
76
+
77
+    public $statuts=array();
78
+    public $statuts_short=array();
79
+
80
+    /**
81
+     * Constructor
82
+     *
83
+     * @param	DoliDB		$db		Database handler
84
+     */
85
+    function __construct(DoliDB $db)
86
+    {
87
+        global $langs;
88
+
89
+        $this->db = $db;
90
+
91
+        $this->statuts_short = array(0 => 'Opened', 1 => 'Closed');
92
+        $this->statuts = array(0 => 'Opened', 1 => 'Closed');
93
+    }
94
+
95
+    /**
96
+     *	Create object in database
97
+     *
98
+     *	@param		User	$user   User making creation
99
+     *	@return 	int				<0 if KO, >0 if OK
100
+     */
101
+    function create($user)
102
+    {
103
+        global $conf;
104
+
105
+        $error = 0;
106
+
107
+        $now=dol_now();
108
+
109
+        $this->db->begin();
110
+
111
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_fiscalyear (";
112
+        $sql.= "label";
113
+        $sql.= ", date_start";
114
+        $sql.= ", date_end";
115
+        $sql.= ", statut";
116
+        $sql.= ", entity";
117
+        $sql.= ", datec";
118
+        $sql.= ", fk_user_author";
119
+        $sql.= ") VALUES (";
120
+        $sql.= " '".$this->db->escape($this->label)."'";
121
+        $sql.= ", '".$this->db->idate($this->date_start)."'";
122
+        $sql.= ", ".($this->date_end ? "'".$this->db->idate($this->date_end)."'":"null");
123
+        $sql.= ", 0";
124
+        $sql.= ", ".$conf->entity;
125
+        $sql.= ", '".$this->db->idate($now)."'";
126
+        $sql.= ", ". $user->id;
127
+        $sql.= ")";
128
+
129
+        dol_syslog(get_class($this)."::create", LOG_DEBUG);
130
+        $result = $this->db->query($sql);
131
+        if ($result)
132
+        {
133
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."accounting_fiscalyear");
134
+
135
+            $result=$this->update($user);
136
+            if ($result > 0)
137
+            {
138
+                $this->db->commit();
139
+                return $this->id;
140
+            }
141
+            else
142
+            {
143
+                $this->error=$this->db->lasterror();
144
+                $this->db->rollback();
145
+                return $result;
146
+            }
147
+        }
148
+        else
149
+        {
150
+            $this->error=$this->db->lasterror()." sql=".$sql;
151
+            $this->db->rollback();
152
+            return -1;
153
+        }
154
+    }
155
+
156
+    /**
157
+     *	Update record
158
+     *
159
+     *	@param	User	$user		User making update
160
+     *	@return	int					<0 if KO, >0 if OK
161
+     */
162
+    function update($user)
163
+    {
164
+        global $langs;
165
+
166
+        // Check parameters
167
+        if (empty($this->date_start) && empty($this->date_end))
168
+        {
169
+            $this->error='ErrorBadParameter';
170
+            return -1;
171
+        }
172
+
173
+        $this->db->begin();
174
+
175
+        $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_fiscalyear";
176
+        $sql .= " SET label = '".$this->db->escape($this->label)."'";
177
+        $sql .= ", date_start = '".$this->db->idate($this->date_start)."'";
178
+        $sql .= ", date_end = ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null");
179
+        $sql .= ", statut = '".$this->db->escape($this->statut?$this->statut:0)."'";
180
+        $sql .= ", datec = " . ($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null');
181
+        $sql .= ", fk_user_modif = " . $user->id;
182
+        $sql .= " WHERE rowid = ".$this->id;
183
+
184
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
185
+        $result = $this->db->query($sql);
186
+        if ($result)
187
+        {
188
+            $this->db->commit();
189
+            return 1;
190
+        }
191
+        else
192
+        {
193
+            $this->error=$this->db->lasterror();
194
+            dol_syslog($this->error, LOG_ERR);
195
+            $this->db->rollback();
196
+            return -1;
197
+        }
198
+    }
199
+
200
+    /**
201
+     * Load an object from database
202
+     *
203
+     * @param	int		$id		Id of record to load
204
+     * @return	int				<0 if KO, >0 if OK
205
+     */
206
+    function fetch($id)
207
+    {
208
+        $sql = "SELECT rowid, label, date_start, date_end, statut";
209
+        $sql.= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear";
210
+        $sql.= " WHERE rowid = ".$id;
211
+
212
+        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
213
+        $result = $this->db->query($sql);
214
+        if ( $result )
215
+        {
216
+            $obj = $this->db->fetch_object($result);
217
+
218
+            $this->id			= $obj->rowid;
219
+            $this->ref			= $obj->rowid;
220
+            $this->date_start	= $this->db->jdate($obj->date_start);
221
+            $this->date_end		= $this->db->jdate($obj->date_end);
222
+            $this->label		= $obj->label;
223
+            $this->statut	    = $obj->statut;
224
+
225
+            return 1;
226
+        }
227
+        else
228
+        {
229
+            $this->error=$this->db->lasterror();
230
+            return -1;
231
+        }
232
+    }
233
+
234
+    /**
235
+     *	Delete record
236
+     *
237
+     *	@param	int		$id		Id of record to delete
238
+     *	@return	int				<0 if KO, >0 if OK
239
+     */
240
+    function delete($id)
241
+    {
242
+        $this->db->begin();
243
+
244
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE rowid = ".$id;
245
+
246
+        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
247
+        $result = $this->db->query($sql);
248
+        if ($result)
249
+        {
250
+            $this->db->commit();
251
+            return 1;
252
+        }
253
+        else
254
+        {
255
+            $this->error=$this->db->lasterror();
256
+            $this->db->rollback();
257
+            return -1;
258
+        }
259
+    }
260
+
261
+    /**
262
+     * Give a label from a status
263
+     *
264
+     * @param	int		$mode   	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
265
+     * @return  string   		   	Label
266
+     */
267
+    function getLibStatut($mode=0)
268
+    {
269
+        return $this->LibStatut($this->statut,$mode);
270
+    }
271
+
272
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
273
+    /**
274
+     *  Give a label from a status
275
+     *
276
+     *  @param	int		$statut     Id status
277
+     *  @param  int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
278
+     *  @return string      		Label
279
+     */
280
+    function LibStatut($statut,$mode=0)
281
+    {
282
+        // phpcs:enable
283
+        global $langs;
284
+
285
+        if ($mode == 0)
286
+        {
287
+            return $langs->trans($this->statuts[$statut]);
288
+        }
289
+        elseif ($mode == 1)
290
+        {
291
+            return $langs->trans($this->statuts_short[$statut]);
292
+        }
293
+        elseif ($mode == 2)
294
+        {
295
+            if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
296
+            elseif ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts_short[$statut]);
297
+        }
298
+        elseif ($mode == 3)
299
+        {
300
+            if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
301
+            elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8');
302
+        }
303
+        elseif ($mode == 4)
304
+        {
305
+            if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
306
+            elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]);
307
+        }
308
+        elseif ($mode == 5)
309
+        {
310
+            if ($statut==0 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
311
+            elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
312
+        }
313
+    }
314
+
315
+    /**
316
+     * Information on record
317
+     *
318
+     * @param	int		$id      Id of record
319
+     * @return	void
320
+     */
321
+    function info($id)
322
+    {
323
+        $sql = 'SELECT fy.rowid, fy.datec, fy.fk_user_author, fy.fk_user_modif,';
324
+        $sql.= ' fy.tms';
325
+        $sql.= ' FROM '.MAIN_DB_PREFIX.'accounting_fiscalyear as fy';
326
+        $sql.= ' WHERE fy.rowid = '.$id;
327
+
328
+        dol_syslog(get_class($this)."::fetch info", LOG_DEBUG);
329
+        $result = $this->db->query($sql);
330
+
331
+        if ($result)
332
+        {
333
+            if ($this->db->num_rows($result))
334
+            {
335
+                $obj = $this->db->fetch_object($result);
336
+                $this->id = $obj->rowid;
337
+                if ($obj->fk_user_author)
338
+                {
339
+                    $cuser = new User($this->db);
340
+                    $cuser->fetch($obj->fk_user_author);
341
+                    $this->user_creation = $cuser;
342
+                }
343
+                if ($obj->fk_user_modif)
344
+                {
345
+                    $muser = new User($this->db);
346
+                    $muser->fetch($obj->fk_user_modif);
347
+                    $this->user_modification = $muser;
348
+                }
349
+                $this->date_creation     = $this->db->jdate($obj->datec);
350
+                $this->date_modification = $this->db->jdate($obj->tms);
351
+            }
352
+            $this->db->free($result);
353
+        }
354
+        else
355
+        {
356
+            dol_print_error($this->db);
357
+        }
358
+    }
359
+
360
+    /**
361
+     *  Return the number of entries by fiscal year
362
+     *
363
+     *	@param	int		$datestart	Date start to scan
364
+     *	@param	int		$dateend	Date end to scan
365
+     *	@return	string				Number of entries
366
+     */
367
+    function getAccountancyEntriesByFiscalYear($datestart, $dateend)
368
+    {
369
+        global $conf;
370
+
371
+        $sql = "SELECT count(DISTINCT piece_num) as nb";
372
+        $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
373
+        $sql.= " WHERE doc_date >= '".$datestart."' and doc_date <= '".$dateend."'";
374
+
375
+        $resql=$this->db->query($sql);
376
+        if ($resql)
377
+        {
378
+            $obj = $this->db->fetch_object($resql);
379
+            $nb = $obj->nb;
380
+        }
381
+        else dol_print_error($this->db);
382
+
383
+        return $nb;
384
+    }
385
+
386
+    /**
387
+     *  Return the number of movements by fiscal year
388
+     *
389
+     *	@param	int		$datestart	Date start to scan
390
+     *	@param	int		$dateend	Date end to scan
391
+     *	@return	string				Number of movements
392
+     */
393
+    function getAccountancyMovementsByFiscalYear($datestart, $dateend)
394
+    {
395
+        global $conf;
396
+
397
+        $sql = "SELECT count(rowid) as nb";
398
+        $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
399
+        $sql.= " WHERE doc_date >= '".$datestart."' AND doc_date <= '".$dateend."'";
400
+
401
+        $resql=$this->db->query($sql);
402
+        if ($resql)
403
+        {
404
+            $obj = $this->db->fetch_object($resql);
405
+            $nb = $obj->nb;
406
+        }
407
+        else dol_print_error($this->db);
408
+
409
+        return $nb;
410
+    }
411 411
 }
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
  *		\brief      File of class to manage fiscal years
22 22
  */
23 23
 
24
-require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
24
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
25 25
 
26 26
 /**
27 27
  * Class to manage fiscal year
@@ -31,12 +31,12 @@  discard block
 block discarded – undo
31 31
 	/**
32 32
 	 * @var string ID to identify managed object
33 33
 	 */
34
-	public $element='fiscalyear';
34
+	public $element = 'fiscalyear';
35 35
 
36 36
 	/**
37 37
 	 * @var string Name of table without prefix where object is stored
38 38
 	 */
39
-	public $table_element='accounting_fiscalyear';
39
+	public $table_element = 'accounting_fiscalyear';
40 40
 
41 41
 	/**
42 42
 	 * @var int    Name of subtable line
@@ -67,15 +67,15 @@  discard block
 block discarded – undo
67 67
 	public $date_start;
68 68
 	public $date_end;
69 69
 	public $datec;
70
-	public $statut;		// 0=open, 1=closed
70
+	public $statut; // 0=open, 1=closed
71 71
 
72 72
 	/**
73 73
 	 * @var int Entity
74 74
 	 */
75 75
 	public $entity;
76 76
 
77
-	public $statuts=array();
78
-	public $statuts_short=array();
77
+	public $statuts = array();
78
+	public $statuts_short = array();
79 79
 
80 80
 	/**
81 81
 	 * Constructor
@@ -104,27 +104,27 @@  discard block
 block discarded – undo
104 104
 
105 105
 		$error = 0;
106 106
 
107
-		$now=dol_now();
107
+		$now = dol_now();
108 108
 
109 109
 		$this->db->begin();
110 110
 
111 111
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_fiscalyear (";
112
-		$sql.= "label";
113
-		$sql.= ", date_start";
114
-		$sql.= ", date_end";
115
-		$sql.= ", statut";
116
-		$sql.= ", entity";
117
-		$sql.= ", datec";
118
-		$sql.= ", fk_user_author";
119
-		$sql.= ") VALUES (";
120
-		$sql.= " '".$this->db->escape($this->label)."'";
121
-		$sql.= ", '".$this->db->idate($this->date_start)."'";
122
-		$sql.= ", ".($this->date_end ? "'".$this->db->idate($this->date_end)."'":"null");
123
-		$sql.= ", 0";
124
-		$sql.= ", ".$conf->entity;
125
-		$sql.= ", '".$this->db->idate($now)."'";
126
-		$sql.= ", ". $user->id;
127
-		$sql.= ")";
112
+		$sql .= "label";
113
+		$sql .= ", date_start";
114
+		$sql .= ", date_end";
115
+		$sql .= ", statut";
116
+		$sql .= ", entity";
117
+		$sql .= ", datec";
118
+		$sql .= ", fk_user_author";
119
+		$sql .= ") VALUES (";
120
+		$sql .= " '".$this->db->escape($this->label)."'";
121
+		$sql .= ", '".$this->db->idate($this->date_start)."'";
122
+		$sql .= ", ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null");
123
+		$sql .= ", 0";
124
+		$sql .= ", ".$conf->entity;
125
+		$sql .= ", '".$this->db->idate($now)."'";
126
+		$sql .= ", ".$user->id;
127
+		$sql .= ")";
128 128
 
129 129
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
130 130
 		$result = $this->db->query($sql);
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		{
133 133
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."accounting_fiscalyear");
134 134
 
135
-			$result=$this->update($user);
135
+			$result = $this->update($user);
136 136
 			if ($result > 0)
137 137
 			{
138 138
 				$this->db->commit();
@@ -140,14 +140,14 @@  discard block
 block discarded – undo
140 140
 			}
141 141
 			else
142 142
 			{
143
-				$this->error=$this->db->lasterror();
143
+				$this->error = $this->db->lasterror();
144 144
 				$this->db->rollback();
145 145
 				return $result;
146 146
 			}
147 147
 		}
148 148
 		else
149 149
 		{
150
-			$this->error=$this->db->lasterror()." sql=".$sql;
150
+			$this->error = $this->db->lasterror()." sql=".$sql;
151 151
 			$this->db->rollback();
152 152
 			return -1;
153 153
 		}
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 		// Check parameters
167 167
 		if (empty($this->date_start) && empty($this->date_end))
168 168
 		{
169
-			$this->error='ErrorBadParameter';
169
+			$this->error = 'ErrorBadParameter';
170 170
 			return -1;
171 171
 		}
172 172
 
@@ -176,9 +176,9 @@  discard block
 block discarded – undo
176 176
 		$sql .= " SET label = '".$this->db->escape($this->label)."'";
177 177
 		$sql .= ", date_start = '".$this->db->idate($this->date_start)."'";
178 178
 		$sql .= ", date_end = ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null");
179
-		$sql .= ", statut = '".$this->db->escape($this->statut?$this->statut:0)."'";
180
-		$sql .= ", datec = " . ($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null');
181
-		$sql .= ", fk_user_modif = " . $user->id;
179
+		$sql .= ", statut = '".$this->db->escape($this->statut ? $this->statut : 0)."'";
180
+		$sql .= ", datec = ".($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null');
181
+		$sql .= ", fk_user_modif = ".$user->id;
182 182
 		$sql .= " WHERE rowid = ".$this->id;
183 183
 
184 184
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 		}
191 191
 		else
192 192
 		{
193
-			$this->error=$this->db->lasterror();
193
+			$this->error = $this->db->lasterror();
194 194
 			dol_syslog($this->error, LOG_ERR);
195 195
 			$this->db->rollback();
196 196
 			return -1;
@@ -206,27 +206,27 @@  discard block
 block discarded – undo
206 206
 	function fetch($id)
207 207
 	{
208 208
 		$sql = "SELECT rowid, label, date_start, date_end, statut";
209
-		$sql.= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear";
210
-		$sql.= " WHERE rowid = ".$id;
209
+		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear";
210
+		$sql .= " WHERE rowid = ".$id;
211 211
 
212 212
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
213 213
 		$result = $this->db->query($sql);
214
-		if ( $result )
214
+		if ($result)
215 215
 		{
216 216
 			$obj = $this->db->fetch_object($result);
217 217
 
218
-			$this->id			= $obj->rowid;
219
-			$this->ref			= $obj->rowid;
218
+			$this->id = $obj->rowid;
219
+			$this->ref = $obj->rowid;
220 220
 			$this->date_start	= $this->db->jdate($obj->date_start);
221
-			$this->date_end		= $this->db->jdate($obj->date_end);
222
-			$this->label		= $obj->label;
221
+			$this->date_end = $this->db->jdate($obj->date_end);
222
+			$this->label = $obj->label;
223 223
 			$this->statut	    = $obj->statut;
224 224
 
225 225
 			return 1;
226 226
 		}
227 227
 		else
228 228
 		{
229
-			$this->error=$this->db->lasterror();
229
+			$this->error = $this->db->lasterror();
230 230
 			return -1;
231 231
 		}
232 232
 	}
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 		}
253 253
 		else
254 254
 		{
255
-			$this->error=$this->db->lasterror();
255
+			$this->error = $this->db->lasterror();
256 256
 			$this->db->rollback();
257 257
 			return -1;
258 258
 		}
@@ -264,9 +264,9 @@  discard block
 block discarded – undo
264 264
 	 * @param	int		$mode   	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
265 265
 	 * @return  string   		   	Label
266 266
 	 */
267
-	function getLibStatut($mode=0)
267
+	function getLibStatut($mode = 0)
268 268
 	{
269
-		return $this->LibStatut($this->statut,$mode);
269
+		return $this->LibStatut($this->statut, $mode);
270 270
 	}
271 271
 
272 272
 	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 	 *  @param  int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
278 278
 	 *  @return string      		Label
279 279
 	 */
280
-	function LibStatut($statut,$mode=0)
280
+	function LibStatut($statut, $mode = 0)
281 281
 	{
282 282
 		// phpcs:enable
283 283
 		global $langs;
@@ -292,23 +292,23 @@  discard block
 block discarded – undo
292 292
 		}
293 293
 		elseif ($mode == 2)
294 294
 		{
295
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
296
-			elseif ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts_short[$statut]);
295
+			if ($statut == 0) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4').' '.$langs->trans($this->statuts_short[$statut]);
296
+			elseif ($statut == 1) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut8').' '.$langs->trans($this->statuts_short[$statut]);
297 297
 		}
298 298
 		elseif ($mode == 3)
299 299
 		{
300
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
301
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8');
300
+			if ($statut == 0 && !empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4');
301
+			elseif ($statut == 1 && !empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut8');
302 302
 		}
303 303
 		elseif ($mode == 4)
304 304
 		{
305
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
306
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]);
305
+			if ($statut == 0 && !empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut4').' '.$langs->trans($this->statuts[$statut]);
306
+			elseif ($statut == 1 && !empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]), 'statut8').' '.$langs->trans($this->statuts[$statut]);
307 307
 		}
308 308
 		elseif ($mode == 5)
309 309
 		{
310
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
311
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
310
+			if ($statut == 0 && !empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut4');
311
+			elseif ($statut == 1 && !empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]), 'statut6');
312 312
 		}
313 313
 	}
314 314
 
@@ -321,9 +321,9 @@  discard block
 block discarded – undo
321 321
 	function info($id)
322 322
 	{
323 323
 		$sql = 'SELECT fy.rowid, fy.datec, fy.fk_user_author, fy.fk_user_modif,';
324
-		$sql.= ' fy.tms';
325
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'accounting_fiscalyear as fy';
326
-		$sql.= ' WHERE fy.rowid = '.$id;
324
+		$sql .= ' fy.tms';
325
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'accounting_fiscalyear as fy';
326
+		$sql .= ' WHERE fy.rowid = '.$id;
327 327
 
328 328
 		dol_syslog(get_class($this)."::fetch info", LOG_DEBUG);
329 329
 		$result = $this->db->query($sql);
@@ -369,10 +369,10 @@  discard block
 block discarded – undo
369 369
 		global $conf;
370 370
 
371 371
 		$sql = "SELECT count(DISTINCT piece_num) as nb";
372
-		$sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
373
-		$sql.= " WHERE doc_date >= '".$datestart."' and doc_date <= '".$dateend."'";
372
+		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
373
+		$sql .= " WHERE doc_date >= '".$datestart."' and doc_date <= '".$dateend."'";
374 374
 
375
-		$resql=$this->db->query($sql);
375
+		$resql = $this->db->query($sql);
376 376
 		if ($resql)
377 377
 		{
378 378
 			$obj = $this->db->fetch_object($resql);
@@ -395,10 +395,10 @@  discard block
 block discarded – undo
395 395
 		global $conf;
396 396
 
397 397
 		$sql = "SELECT count(rowid) as nb";
398
-		$sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
399
-		$sql.= " WHERE doc_date >= '".$datestart."' AND doc_date <= '".$dateend."'";
398
+		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping ";
399
+		$sql .= " WHERE doc_date >= '".$datestart."' AND doc_date <= '".$dateend."'";
400 400
 
401
-		$resql=$this->db->query($sql);
401
+		$resql = $this->db->query($sql);
402 402
 		if ($resql)
403 403
 		{
404 404
 			$obj = $this->db->fetch_object($resql);
Please login to merge, or discard this patch.
Braces   +35 added lines, -32 removed lines patch added patch discarded remove patch
@@ -137,15 +137,13 @@  discard block
 block discarded – undo
137 137
 			{
138 138
 				$this->db->commit();
139 139
 				return $this->id;
140
-			}
141
-			else
140
+			} else
142 141
 			{
143 142
 				$this->error=$this->db->lasterror();
144 143
 				$this->db->rollback();
145 144
 				return $result;
146 145
 			}
147
-		}
148
-		else
146
+		} else
149 147
 		{
150 148
 			$this->error=$this->db->lasterror()." sql=".$sql;
151 149
 			$this->db->rollback();
@@ -187,8 +185,7 @@  discard block
 block discarded – undo
187 185
 		{
188 186
 			$this->db->commit();
189 187
 			return 1;
190
-		}
191
-		else
188
+		} else
192 189
 		{
193 190
 			$this->error=$this->db->lasterror();
194 191
 			dol_syslog($this->error, LOG_ERR);
@@ -223,8 +220,7 @@  discard block
 block discarded – undo
223 220
 			$this->statut	    = $obj->statut;
224 221
 
225 222
 			return 1;
226
-		}
227
-		else
223
+		} else
228 224
 		{
229 225
 			$this->error=$this->db->lasterror();
230 226
 			return -1;
@@ -249,8 +245,7 @@  discard block
 block discarded – undo
249 245
 		{
250 246
 			$this->db->commit();
251 247
 			return 1;
252
-		}
253
-		else
248
+		} else
254 249
 		{
255 250
 			$this->error=$this->db->lasterror();
256 251
 			$this->db->rollback();
@@ -285,30 +280,37 @@  discard block
 block discarded – undo
285 280
 		if ($mode == 0)
286 281
 		{
287 282
 			return $langs->trans($this->statuts[$statut]);
288
-		}
289
-		elseif ($mode == 1)
283
+		} elseif ($mode == 1)
290 284
 		{
291 285
 			return $langs->trans($this->statuts_short[$statut]);
292
-		}
293
-		elseif ($mode == 2)
286
+		} elseif ($mode == 2)
294 287
 		{
295
-			if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
296
-			elseif ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts_short[$statut]);
297
-		}
298
-		elseif ($mode == 3)
288
+			if ($statut==0) {
289
+			    return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]);
290
+			} elseif ($statut==1) {
291
+			    return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts_short[$statut]);
292
+			}
293
+		} elseif ($mode == 3)
299 294
 		{
300
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
301
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8');
302
-		}
303
-		elseif ($mode == 4)
295
+			if ($statut==0 && ! empty($this->statuts_short[$statut])) {
296
+			    return img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
297
+			} elseif ($statut==1 && ! empty($this->statuts_short[$statut])) {
298
+			    return img_picto($langs->trans($this->statuts_short[$statut]),'statut8');
299
+			}
300
+		} elseif ($mode == 4)
304 301
 		{
305
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
306
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]);
307
-		}
308
-		elseif ($mode == 5)
302
+			if ($statut==0 && ! empty($this->statuts_short[$statut])) {
303
+			    return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
304
+			} elseif ($statut==1 && ! empty($this->statuts_short[$statut])) {
305
+			    return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]);
306
+			}
307
+		} elseif ($mode == 5)
309 308
 		{
310
-			if ($statut==0 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
311
-			elseif ($statut==1 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
309
+			if ($statut==0 && ! empty($this->statuts_short[$statut])) {
310
+			    return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4');
311
+			} elseif ($statut==1 && ! empty($this->statuts_short[$statut])) {
312
+			    return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut6');
313
+			}
312 314
 		}
313 315
 	}
314 316
 
@@ -350,8 +352,7 @@  discard block
 block discarded – undo
350 352
 				$this->date_modification = $this->db->jdate($obj->tms);
351 353
 			}
352 354
 			$this->db->free($result);
353
-		}
354
-		else
355
+		} else
355 356
 		{
356 357
 			dol_print_error($this->db);
357 358
 		}
@@ -377,8 +378,9 @@  discard block
 block discarded – undo
377 378
 		{
378 379
 			$obj = $this->db->fetch_object($resql);
379 380
 			$nb = $obj->nb;
381
+		} else {
382
+		    dol_print_error($this->db);
380 383
 		}
381
-		else dol_print_error($this->db);
382 384
 
383 385
 		return $nb;
384 386
 	}
@@ -403,8 +405,9 @@  discard block
 block discarded – undo
403 405
 		{
404 406
 			$obj = $this->db->fetch_object($resql);
405 407
 			$nb = $obj->nb;
408
+		} else {
409
+		    dol_print_error($this->db);
406 410
 		}
407
-		else dol_print_error($this->db);
408 411
 
409 412
 		return $nb;
410 413
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/ctypent.class.php 3 patches
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -27,33 +27,33 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class Ctypent // extends CommonObject
29 29
 {
30
-	/**
30
+    /**
31 31
      * @var DoliDB Database handler.
32 32
      */
33 33
     public $db;
34 34
 
35
-	/**
36
-	 * @var string Error code (or message)
37
-	 */
38
-	public $error='';
35
+    /**
36
+     * @var string Error code (or message)
37
+     */
38
+    public $error='';
39 39
 
40
-	/**
41
-	 * @var string[] Error codes (or messages)
42
-	 */
43
-	public $errors = array();
40
+    /**
41
+     * @var string[] Error codes (or messages)
42
+     */
43
+    public $errors = array();
44 44
 
45
-	//var $element='ctypent';			//!< Id that identify managed objects
46
-	//var $table_element='ctypent';	//!< Name of table without prefix where object is stored
45
+    //var $element='ctypent';			//!< Id that identify managed objects
46
+    //var $table_element='ctypent';	//!< Name of table without prefix where object is stored
47 47
 
48 48
     /**
49
-	 * @var int ID
50
-	 */
51
-	public $id;
49
+     * @var int ID
50
+     */
51
+    public $id;
52 52
 
53
-	public $code;
54
-	public $libelle;
55
-	public $active;
56
-	public $module;
53
+    public $code;
54
+    public $libelle;
55
+    public $active;
56
+    public $module;
57 57
 
58 58
 
59 59
 
@@ -78,83 +78,83 @@  discard block
 block discarded – undo
78 78
      */
79 79
     function create($user, $notrigger=0)
80 80
     {
81
-    	global $conf, $langs;
82
-		$error=0;
81
+        global $conf, $langs;
82
+        $error=0;
83 83
 
84
-		// Clean parameters
84
+        // Clean parameters
85 85
 
86
-		if (isset($this->id)) $this->id=trim($this->id);
87
-		if (isset($this->code)) $this->code=trim($this->code);
88
-		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
89
-		if (isset($this->active)) $this->active=trim($this->active);
90
-		if (isset($this->module)) $this->module=trim($this->module);
86
+        if (isset($this->id)) $this->id=trim($this->id);
87
+        if (isset($this->code)) $this->code=trim($this->code);
88
+        if (isset($this->libelle)) $this->libelle=trim($this->libelle);
89
+        if (isset($this->active)) $this->active=trim($this->active);
90
+        if (isset($this->module)) $this->module=trim($this->module);
91 91
 
92 92
 
93 93
 
94
-		// Check parameters
95
-		// Put here code to add control on parameters values
94
+        // Check parameters
95
+        // Put here code to add control on parameters values
96 96
 
97 97
         // Insert request
98
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_typent(";
98
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_typent(";
99 99
 
100
-		$sql.= "id,";
101
-		$sql.= "code,";
102
-		$sql.= "libelle,";
103
-		$sql.= "active,";
104
-		$sql.= "module";
100
+        $sql.= "id,";
101
+        $sql.= "code,";
102
+        $sql.= "libelle,";
103
+        $sql.= "active,";
104
+        $sql.= "module";
105 105
 
106 106
 
107 107
         $sql.= ") VALUES (";
108 108
 
109
-		$sql.= " ".(! isset($this->id)?'NULL':"'".$this->db->escape($this->id)."'").",";
110
-		$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
111
-		$sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").",";
112
-		$sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->active($this->active)."'").",";
113
-		$sql.= " ".(! isset($this->module)?'NULL':"'".$this->db->escape($this->module)."'")."";
109
+        $sql.= " ".(! isset($this->id)?'NULL':"'".$this->db->escape($this->id)."'").",";
110
+        $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
111
+        $sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").",";
112
+        $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->active($this->active)."'").",";
113
+        $sql.= " ".(! isset($this->module)?'NULL':"'".$this->db->escape($this->module)."'")."";
114 114
 
115 115
 
116
-		$sql.= ")";
116
+        $sql.= ")";
117 117
 
118
-		$this->db->begin();
118
+        $this->db->begin();
119 119
 
120
-	   	dol_syslog(get_class($this)."::create", LOG_DEBUG);
120
+            dol_syslog(get_class($this)."::create", LOG_DEBUG);
121 121
         $resql=$this->db->query($sql);
122
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
122
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
123 123
 
124
-		if (! $error)
124
+        if (! $error)
125 125
         {
126 126
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_typent");
127 127
 
128
-			if (! $notrigger)
129
-			{
130
-	            // Uncomment this and change MYOBJECT to your own tag if you
131
-	            // want this action call a trigger.
132
-
133
-	            //// Call triggers
134
-	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
135
-	            //$interface=new Interfaces($this->db);
136
-	            //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
137
-	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
138
-	            //// End call triggers
139
-			}
128
+            if (! $notrigger)
129
+            {
130
+                // Uncomment this and change MYOBJECT to your own tag if you
131
+                // want this action call a trigger.
132
+
133
+                //// Call triggers
134
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
135
+                //$interface=new Interfaces($this->db);
136
+                //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
137
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
138
+                //// End call triggers
139
+            }
140 140
         }
141 141
 
142 142
         // Commit or rollback
143 143
         if ($error)
144
-		{
145
-			foreach($this->errors as $errmsg)
146
-			{
147
-	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
148
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
149
-			}
150
-			$this->db->rollback();
151
-			return -1*$error;
152
-		}
153
-		else
154
-		{
155
-			$this->db->commit();
144
+        {
145
+            foreach($this->errors as $errmsg)
146
+            {
147
+                dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
148
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
149
+            }
150
+            $this->db->rollback();
151
+            return -1*$error;
152
+        }
153
+        else
154
+        {
155
+            $this->db->commit();
156 156
             return $this->id;
157
-		}
157
+        }
158 158
     }
159 159
 
160 160
 
@@ -168,14 +168,14 @@  discard block
 block discarded – undo
168 168
      */
169 169
     function fetch($id,$code='',$label='')
170 170
     {
171
-    	global $langs;
171
+        global $langs;
172 172
         $sql = "SELECT";
173
-		$sql.= " t.id,";
174
-		$sql.= " t.code,";
175
-		$sql.= " t.libelle as label,";
176
-		$sql.= " t.fk_country as country_id,";
177
-		$sql.= " t.active,";
178
-		$sql.= " t.module";
173
+        $sql.= " t.id,";
174
+        $sql.= " t.code,";
175
+        $sql.= " t.libelle as label,";
176
+        $sql.= " t.fk_country as country_id,";
177
+        $sql.= " t.active,";
178
+        $sql.= " t.module";
179 179
         $sql.= " FROM ".MAIN_DB_PREFIX."c_typent as t";
180 180
         if ($id)   $sql.= " WHERE t.id = ".$id;
181 181
         elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
@@ -189,11 +189,11 @@  discard block
 block discarded – undo
189 189
                 $obj = $this->db->fetch_object($resql);
190 190
 
191 191
                 $this->id    = $obj->id;
192
-				$this->code = $obj->code;
193
-				$this->libelle = $obj->label;
194
-				$this->country_id = $obj->country_id;
195
-				$this->active = $obj->active;
196
-				$this->module = $obj->module;
192
+                $this->code = $obj->code;
193
+                $this->libelle = $obj->label;
194
+                $this->country_id = $obj->country_id;
195
+                $this->active = $obj->active;
196
+                $this->module = $obj->module;
197 197
             }
198 198
             $this->db->free($resql);
199 199
 
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
         }
202 202
         else
203 203
         {
204
-      	    $this->error="Error ".$this->db->lasterror();
204
+                $this->error="Error ".$this->db->lasterror();
205 205
             return -1;
206 206
         }
207 207
     }
@@ -216,120 +216,120 @@  discard block
 block discarded – undo
216 216
      */
217 217
     function update($user=null, $notrigger=0)
218 218
     {
219
-    	global $conf, $langs;
220
-		$error=0;
219
+        global $conf, $langs;
220
+        $error=0;
221 221
 
222
-		// Clean parameters
223
-		if (isset($this->code)) $this->code=trim($this->code);
224
-		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
225
-		if (isset($this->active)) $this->active=trim($this->active);
226
-		if (isset($this->module)) $this->module=trim($this->module);
222
+        // Clean parameters
223
+        if (isset($this->code)) $this->code=trim($this->code);
224
+        if (isset($this->libelle)) $this->libelle=trim($this->libelle);
225
+        if (isset($this->active)) $this->active=trim($this->active);
226
+        if (isset($this->module)) $this->module=trim($this->module);
227 227
 
228 228
 
229
-		// Check parameters
230
-		// Put here code to add control on parameters values
229
+        // Check parameters
230
+        // Put here code to add control on parameters values
231 231
 
232 232
         // Update request
233 233
         $sql = "UPDATE ".MAIN_DB_PREFIX."c_typent SET";
234
-		$sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
235
-		$sql.= " libelle=".(isset($this->libelle)?"'".$this->db->escape($this->libelle)."'":"null").",";
236
-		$sql.= " active=".(isset($this->active)?$this->active:"null").",";
237
-		$sql.= " module=".(isset($this->module)?"'".$this->db->escape($this->module)."'":"null")."";
234
+        $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
235
+        $sql.= " libelle=".(isset($this->libelle)?"'".$this->db->escape($this->libelle)."'":"null").",";
236
+        $sql.= " active=".(isset($this->active)?$this->active:"null").",";
237
+        $sql.= " module=".(isset($this->module)?"'".$this->db->escape($this->module)."'":"null")."";
238 238
         $sql.= " WHERE id=".$this->id;
239 239
 
240
-		$this->db->begin();
240
+        $this->db->begin();
241 241
 
242
-		dol_syslog(get_class($this)."::update", LOG_DEBUG);
242
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
243 243
         $resql = $this->db->query($sql);
244
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
245
-
246
-		if (! $error)
247
-		{
248
-			if (! $notrigger)
249
-			{
250
-	            // Uncomment this and change MYOBJECT to your own tag if you
251
-	            // want this action call a trigger.
252
-
253
-	            //// Call triggers
254
-	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
255
-	            //$interface=new Interfaces($this->db);
256
-	            //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
257
-	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
258
-	            //// End call triggers
259
-	    	}
260
-		}
244
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
245
+
246
+        if (! $error)
247
+        {
248
+            if (! $notrigger)
249
+            {
250
+                // Uncomment this and change MYOBJECT to your own tag if you
251
+                // want this action call a trigger.
252
+
253
+                //// Call triggers
254
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
255
+                //$interface=new Interfaces($this->db);
256
+                //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
257
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
258
+                //// End call triggers
259
+            }
260
+        }
261 261
 
262 262
         // Commit or rollback
263
-		if ($error)
264
-		{
265
-			foreach($this->errors as $errmsg)
266
-			{
267
-	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
268
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
269
-			}
270
-			$this->db->rollback();
271
-			return -1*$error;
272
-		}
273
-		else
274
-		{
275
-			$this->db->commit();
276
-			return 1;
277
-		}
263
+        if ($error)
264
+        {
265
+            foreach($this->errors as $errmsg)
266
+            {
267
+                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
268
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
269
+            }
270
+            $this->db->rollback();
271
+            return -1*$error;
272
+        }
273
+        else
274
+        {
275
+            $this->db->commit();
276
+            return 1;
277
+        }
278 278
     }
279 279
 
280 280
 
281
- 	/**
282
-	 *  Delete object in database
283
-	 *
284
-     *	@param  User	$user        User that delete
285
-     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
286
-	 *  @return	int					 <0 if KO, >0 if OK
287
-	 */
288
-	function delete($user, $notrigger=0)
289
-	{
290
-		global $conf, $langs;
291
-		$error=0;
292
-
293
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_typent";
294
-		$sql.= " WHERE id=".$this->id;
295
-
296
-		$this->db->begin();
297
-
298
-		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
299
-		$resql = $this->db->query($sql);
300
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
301
-
302
-		if (! $error)
303
-		{
304
-			if (! $notrigger)
305
-			{
306
-				// Uncomment this and change MYOBJECT to your own tag if you
307
-		        // want this action call a trigger.
308
-
309
-		        //// Call triggers
310
-		        //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
311
-		        //$interface=new Interfaces($this->db);
312
-		        //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
313
-		        //if ($result < 0) { $error++; $this->errors=$interface->errors; }
314
-		        //// End call triggers
315
-			}
316
-		}
281
+        /**
282
+         *  Delete object in database
283
+         *
284
+         *	@param  User	$user        User that delete
285
+         *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
286
+         *  @return	int					 <0 if KO, >0 if OK
287
+         */
288
+    function delete($user, $notrigger=0)
289
+    {
290
+        global $conf, $langs;
291
+        $error=0;
292
+
293
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_typent";
294
+        $sql.= " WHERE id=".$this->id;
295
+
296
+        $this->db->begin();
297
+
298
+        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
299
+        $resql = $this->db->query($sql);
300
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
301
+
302
+        if (! $error)
303
+        {
304
+            if (! $notrigger)
305
+            {
306
+                // Uncomment this and change MYOBJECT to your own tag if you
307
+                // want this action call a trigger.
308
+
309
+                //// Call triggers
310
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
311
+                //$interface=new Interfaces($this->db);
312
+                //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
313
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
314
+                //// End call triggers
315
+            }
316
+        }
317 317
 
318 318
         // Commit or rollback
319
-		if ($error)
320
-		{
321
-			foreach($this->errors as $errmsg)
322
-			{
323
-	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
324
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
325
-			}
326
-			$this->db->rollback();
327
-			return -1*$error;
328
-		}
329
-		else
330
-		{
331
-			$this->db->commit();
332
-			return 1;
333
-		}
334
-	}
319
+        if ($error)
320
+        {
321
+            foreach($this->errors as $errmsg)
322
+            {
323
+                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
324
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
325
+            }
326
+            $this->db->rollback();
327
+            return -1*$error;
328
+        }
329
+        else
330
+        {
331
+            $this->db->commit();
332
+            return 1;
333
+        }
334
+    }
335 335
 }
Please login to merge, or discard this patch.
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	/**
36 36
 	 * @var string Error code (or message)
37 37
 	 */
38
-	public $error='';
38
+	public $error = '';
39 39
 
40 40
 	/**
41 41
 	 * @var string[] Error codes (or messages)
@@ -76,18 +76,18 @@  discard block
 block discarded – undo
76 76
      *  @param      int		$notrigger   0=launch triggers after, 1=disable triggers
77 77
      *  @return     int      		   	 <0 if KO, Id of created object if OK
78 78
      */
79
-    function create($user, $notrigger=0)
79
+    function create($user, $notrigger = 0)
80 80
     {
81 81
     	global $conf, $langs;
82
-		$error=0;
82
+		$error = 0;
83 83
 
84 84
 		// Clean parameters
85 85
 
86
-		if (isset($this->id)) $this->id=trim($this->id);
87
-		if (isset($this->code)) $this->code=trim($this->code);
88
-		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
89
-		if (isset($this->active)) $this->active=trim($this->active);
90
-		if (isset($this->module)) $this->module=trim($this->module);
86
+		if (isset($this->id)) $this->id = trim($this->id);
87
+		if (isset($this->code)) $this->code = trim($this->code);
88
+		if (isset($this->libelle)) $this->libelle = trim($this->libelle);
89
+		if (isset($this->active)) $this->active = trim($this->active);
90
+		if (isset($this->module)) $this->module = trim($this->module);
91 91
 
92 92
 
93 93
 
@@ -97,35 +97,35 @@  discard block
 block discarded – undo
97 97
         // Insert request
98 98
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_typent(";
99 99
 
100
-		$sql.= "id,";
101
-		$sql.= "code,";
102
-		$sql.= "libelle,";
103
-		$sql.= "active,";
104
-		$sql.= "module";
100
+		$sql .= "id,";
101
+		$sql .= "code,";
102
+		$sql .= "libelle,";
103
+		$sql .= "active,";
104
+		$sql .= "module";
105 105
 
106 106
 
107
-        $sql.= ") VALUES (";
107
+        $sql .= ") VALUES (";
108 108
 
109
-		$sql.= " ".(! isset($this->id)?'NULL':"'".$this->db->escape($this->id)."'").",";
110
-		$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
111
-		$sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").",";
112
-		$sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->active($this->active)."'").",";
113
-		$sql.= " ".(! isset($this->module)?'NULL':"'".$this->db->escape($this->module)."'")."";
109
+		$sql .= " ".(!isset($this->id) ? 'NULL' : "'".$this->db->escape($this->id)."'").",";
110
+		$sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").",";
111
+		$sql .= " ".(!isset($this->libelle) ? 'NULL' : "'".$this->db->escape($this->libelle)."'").",";
112
+		$sql .= " ".(!isset($this->active) ? 'NULL' : "'".$this->db->active($this->active)."'").",";
113
+		$sql .= " ".(!isset($this->module) ? 'NULL' : "'".$this->db->escape($this->module)."'")."";
114 114
 
115 115
 
116
-		$sql.= ")";
116
+		$sql .= ")";
117 117
 
118 118
 		$this->db->begin();
119 119
 
120 120
 	   	dol_syslog(get_class($this)."::create", LOG_DEBUG);
121
-        $resql=$this->db->query($sql);
122
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
121
+        $resql = $this->db->query($sql);
122
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
123 123
 
124
-		if (! $error)
124
+		if (!$error)
125 125
         {
126 126
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_typent");
127 127
 
128
-			if (! $notrigger)
128
+			if (!$notrigger)
129 129
 			{
130 130
 	            // Uncomment this and change MYOBJECT to your own tag if you
131 131
 	            // want this action call a trigger.
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
         // Commit or rollback
143 143
         if ($error)
144 144
 		{
145
-			foreach($this->errors as $errmsg)
145
+			foreach ($this->errors as $errmsg)
146 146
 			{
147 147
 	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
148
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
148
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
149 149
 			}
150 150
 			$this->db->rollback();
151
-			return -1*$error;
151
+			return -1 * $error;
152 152
 		}
153 153
 		else
154 154
 		{
@@ -166,29 +166,29 @@  discard block
 block discarded – undo
166 166
      *  @param		string	$label	Label
167 167
      *  @return     int          	<0 if KO, >0 if OK
168 168
      */
169
-    function fetch($id,$code='',$label='')
169
+    function fetch($id, $code = '', $label = '')
170 170
     {
171 171
     	global $langs;
172 172
         $sql = "SELECT";
173
-		$sql.= " t.id,";
174
-		$sql.= " t.code,";
175
-		$sql.= " t.libelle as label,";
176
-		$sql.= " t.fk_country as country_id,";
177
-		$sql.= " t.active,";
178
-		$sql.= " t.module";
179
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_typent as t";
180
-        if ($id)   $sql.= " WHERE t.id = ".$id;
181
-        elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
182
-        elseif ($label) $sql.= " WHERE t.libelle = '".$this->db->escape($label)."'";
183
-
184
-        $resql=$this->db->query($sql);
173
+		$sql .= " t.id,";
174
+		$sql .= " t.code,";
175
+		$sql .= " t.libelle as label,";
176
+		$sql .= " t.fk_country as country_id,";
177
+		$sql .= " t.active,";
178
+		$sql .= " t.module";
179
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_typent as t";
180
+        if ($id)   $sql .= " WHERE t.id = ".$id;
181
+        elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
182
+        elseif ($label) $sql .= " WHERE t.libelle = '".$this->db->escape($label)."'";
183
+
184
+        $resql = $this->db->query($sql);
185 185
         if ($resql)
186 186
         {
187 187
             if ($this->db->num_rows($resql))
188 188
             {
189 189
                 $obj = $this->db->fetch_object($resql);
190 190
 
191
-                $this->id    = $obj->id;
191
+                $this->id = $obj->id;
192 192
 				$this->code = $obj->code;
193 193
 				$this->libelle = $obj->label;
194 194
 				$this->country_id = $obj->country_id;
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
         }
202 202
         else
203 203
         {
204
-      	    $this->error="Error ".$this->db->lasterror();
204
+      	    $this->error = "Error ".$this->db->lasterror();
205 205
             return -1;
206 206
         }
207 207
     }
@@ -214,16 +214,16 @@  discard block
 block discarded – undo
214 214
      *  @param      int		$notrigger	 0=launch triggers after, 1=disable triggers
215 215
      *  @return     int     		   	 <0 if KO, >0 if OK
216 216
      */
217
-    function update($user=null, $notrigger=0)
217
+    function update($user = null, $notrigger = 0)
218 218
     {
219 219
     	global $conf, $langs;
220
-		$error=0;
220
+		$error = 0;
221 221
 
222 222
 		// Clean parameters
223
-		if (isset($this->code)) $this->code=trim($this->code);
224
-		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
225
-		if (isset($this->active)) $this->active=trim($this->active);
226
-		if (isset($this->module)) $this->module=trim($this->module);
223
+		if (isset($this->code)) $this->code = trim($this->code);
224
+		if (isset($this->libelle)) $this->libelle = trim($this->libelle);
225
+		if (isset($this->active)) $this->active = trim($this->active);
226
+		if (isset($this->module)) $this->module = trim($this->module);
227 227
 
228 228
 
229 229
 		// Check parameters
@@ -231,21 +231,21 @@  discard block
 block discarded – undo
231 231
 
232 232
         // Update request
233 233
         $sql = "UPDATE ".MAIN_DB_PREFIX."c_typent SET";
234
-		$sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
235
-		$sql.= " libelle=".(isset($this->libelle)?"'".$this->db->escape($this->libelle)."'":"null").",";
236
-		$sql.= " active=".(isset($this->active)?$this->active:"null").",";
237
-		$sql.= " module=".(isset($this->module)?"'".$this->db->escape($this->module)."'":"null")."";
238
-        $sql.= " WHERE id=".$this->id;
234
+		$sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").",";
235
+		$sql .= " libelle=".(isset($this->libelle) ? "'".$this->db->escape($this->libelle)."'" : "null").",";
236
+		$sql .= " active=".(isset($this->active) ? $this->active : "null").",";
237
+		$sql .= " module=".(isset($this->module) ? "'".$this->db->escape($this->module)."'" : "null")."";
238
+        $sql .= " WHERE id=".$this->id;
239 239
 
240 240
 		$this->db->begin();
241 241
 
242 242
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
243 243
         $resql = $this->db->query($sql);
244
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
244
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
245 245
 
246
-		if (! $error)
246
+		if (!$error)
247 247
 		{
248
-			if (! $notrigger)
248
+			if (!$notrigger)
249 249
 			{
250 250
 	            // Uncomment this and change MYOBJECT to your own tag if you
251 251
 	            // want this action call a trigger.
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
         // Commit or rollback
263 263
 		if ($error)
264 264
 		{
265
-			foreach($this->errors as $errmsg)
265
+			foreach ($this->errors as $errmsg)
266 266
 			{
267 267
 	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
268
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
268
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
269 269
 			}
270 270
 			$this->db->rollback();
271
-			return -1*$error;
271
+			return -1 * $error;
272 272
 		}
273 273
 		else
274 274
 		{
@@ -285,23 +285,23 @@  discard block
 block discarded – undo
285 285
      *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
286 286
 	 *  @return	int					 <0 if KO, >0 if OK
287 287
 	 */
288
-	function delete($user, $notrigger=0)
288
+	function delete($user, $notrigger = 0)
289 289
 	{
290 290
 		global $conf, $langs;
291
-		$error=0;
291
+		$error = 0;
292 292
 
293 293
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_typent";
294
-		$sql.= " WHERE id=".$this->id;
294
+		$sql .= " WHERE id=".$this->id;
295 295
 
296 296
 		$this->db->begin();
297 297
 
298 298
 		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
299 299
 		$resql = $this->db->query($sql);
300
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
300
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
301 301
 
302
-		if (! $error)
302
+		if (!$error)
303 303
 		{
304
-			if (! $notrigger)
304
+			if (!$notrigger)
305 305
 			{
306 306
 				// Uncomment this and change MYOBJECT to your own tag if you
307 307
 		        // want this action call a trigger.
@@ -318,13 +318,13 @@  discard block
 block discarded – undo
318 318
         // Commit or rollback
319 319
 		if ($error)
320 320
 		{
321
-			foreach($this->errors as $errmsg)
321
+			foreach ($this->errors as $errmsg)
322 322
 			{
323 323
 	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
324
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
324
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
325 325
 			}
326 326
 			$this->db->rollback();
327
-			return -1*$error;
327
+			return -1 * $error;
328 328
 		}
329 329
 		else
330 330
 		{
Please login to merge, or discard this patch.
Braces   +38 added lines, -20 removed lines patch added patch discarded remove patch
@@ -83,11 +83,21 @@  discard block
 block discarded – undo
83 83
 
84 84
 		// Clean parameters
85 85
 
86
-		if (isset($this->id)) $this->id=trim($this->id);
87
-		if (isset($this->code)) $this->code=trim($this->code);
88
-		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
89
-		if (isset($this->active)) $this->active=trim($this->active);
90
-		if (isset($this->module)) $this->module=trim($this->module);
86
+		if (isset($this->id)) {
87
+		    $this->id=trim($this->id);
88
+		}
89
+		if (isset($this->code)) {
90
+		    $this->code=trim($this->code);
91
+		}
92
+		if (isset($this->libelle)) {
93
+		    $this->libelle=trim($this->libelle);
94
+		}
95
+		if (isset($this->active)) {
96
+		    $this->active=trim($this->active);
97
+		}
98
+		if (isset($this->module)) {
99
+		    $this->module=trim($this->module);
100
+		}
91 101
 
92 102
 
93 103
 
@@ -149,8 +159,7 @@  discard block
 block discarded – undo
149 159
 			}
150 160
 			$this->db->rollback();
151 161
 			return -1*$error;
152
-		}
153
-		else
162
+		} else
154 163
 		{
155 164
 			$this->db->commit();
156 165
             return $this->id;
@@ -177,9 +186,13 @@  discard block
 block discarded – undo
177 186
 		$sql.= " t.active,";
178 187
 		$sql.= " t.module";
179 188
         $sql.= " FROM ".MAIN_DB_PREFIX."c_typent as t";
180
-        if ($id)   $sql.= " WHERE t.id = ".$id;
181
-        elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
182
-        elseif ($label) $sql.= " WHERE t.libelle = '".$this->db->escape($label)."'";
189
+        if ($id) {
190
+            $sql.= " WHERE t.id = ".$id;
191
+        } elseif ($code) {
192
+            $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
193
+        } elseif ($label) {
194
+            $sql.= " WHERE t.libelle = '".$this->db->escape($label)."'";
195
+        }
183 196
 
184 197
         $resql=$this->db->query($sql);
185 198
         if ($resql)
@@ -198,8 +211,7 @@  discard block
 block discarded – undo
198 211
             $this->db->free($resql);
199 212
 
200 213
             return 1;
201
-        }
202
-        else
214
+        } else
203 215
         {
204 216
       	    $this->error="Error ".$this->db->lasterror();
205 217
             return -1;
@@ -220,10 +232,18 @@  discard block
 block discarded – undo
220 232
 		$error=0;
221 233
 
222 234
 		// Clean parameters
223
-		if (isset($this->code)) $this->code=trim($this->code);
224
-		if (isset($this->libelle)) $this->libelle=trim($this->libelle);
225
-		if (isset($this->active)) $this->active=trim($this->active);
226
-		if (isset($this->module)) $this->module=trim($this->module);
235
+		if (isset($this->code)) {
236
+		    $this->code=trim($this->code);
237
+		}
238
+		if (isset($this->libelle)) {
239
+		    $this->libelle=trim($this->libelle);
240
+		}
241
+		if (isset($this->active)) {
242
+		    $this->active=trim($this->active);
243
+		}
244
+		if (isset($this->module)) {
245
+		    $this->module=trim($this->module);
246
+		}
227 247
 
228 248
 
229 249
 		// Check parameters
@@ -269,8 +289,7 @@  discard block
 block discarded – undo
269 289
 			}
270 290
 			$this->db->rollback();
271 291
 			return -1*$error;
272
-		}
273
-		else
292
+		} else
274 293
 		{
275 294
 			$this->db->commit();
276 295
 			return 1;
@@ -325,8 +344,7 @@  discard block
 block discarded – undo
325 344
 			}
326 345
 			$this->db->rollback();
327 346
 			return -1*$error;
328
-		}
329
-		else
347
+		} else
330 348
 		{
331 349
 			$this->db->commit();
332 350
 			return 1;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formbank.class.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -35,9 +35,9 @@  discard block
 block discarded – undo
35 35
     public $db;
36 36
     
37 37
     /**
38
-	 * @var string Error code (or message)
39
-	 */
40
-	public $error='';
38
+     * @var string Error code (or message)
39
+     */
40
+    public $error='';
41 41
 
42 42
 
43 43
     /**
@@ -64,19 +64,19 @@  discard block
 block discarded – undo
64 64
         print Form::selectarray($htmlname, $account->type_lib, $selected);
65 65
     }
66 66
 
67
-	/**
68
-	 * Returns the name of the Iban label. India uses 'IFSC' and the rest of the world 'IBAN' name.
69
-	 *
70
-	 * @param Account $account Account object
71
-	 * @return string
72
-	 */
73
-	public static function getIBANLabel(Account $account)
74
-	{
75
-		if ($account->getCountryCode() == 'IN') {
76
-			return 'IFSC';
77
-		}
67
+    /**
68
+     * Returns the name of the Iban label. India uses 'IFSC' and the rest of the world 'IBAN' name.
69
+     *
70
+     * @param Account $account Account object
71
+     * @return string
72
+     */
73
+    public static function getIBANLabel(Account $account)
74
+    {
75
+        if ($account->getCountryCode() == 'IN') {
76
+            return 'IFSC';
77
+        }
78 78
 
79
-		return 'IBANNumber';
80
-	}
79
+        return 'IBANNumber';
80
+    }
81 81
 }
82 82
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
     /**
38 38
 	 * @var string Error code (or message)
39 39
 	 */
40
-	public $error='';
40
+	public $error = '';
41 41
 
42 42
 
43 43
     /**
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/ldap.class.php 3 patches
Indentation   +1474 added lines, -1474 removed lines patch added patch discarded remove patch
@@ -29,1491 +29,1491 @@
 block discarded – undo
29 29
  */
30 30
 class Ldap
31 31
 {
32
-	/**
33
-	 * @var string Error code (or message)
34
-	 */
35
-	public $error='';
36
-
37
-	/**
38
-	 * @var string[]	Array of error strings
39
-	 */
40
-	public $errors = array();
41
-
42
-	/**
43
-	 * Tableau des serveurs (IP addresses ou nom d'hotes)
44
-	 */
45
-	var $server=array();
46
-
47
-	/**
48
-	 * Base DN (e.g. "dc=foo,dc=com")
49
-	 */
50
-	var $dn;
51
-	/**
52
-	 * type de serveur, actuellement OpenLdap et Active Directory
53
-	 */
54
-	var $serverType;
55
-	/**
56
-	 * Version du protocole ldap
57
-	 */
58
-	var $domain;
59
-	/**
60
-	 * User administrateur Ldap
61
-	 * Active Directory ne supporte pas les connexions anonymes
62
-	 */
63
-	var $searchUser;
64
-	/**
65
-	 * Mot de passe de l'administrateur
66
-	 * Active Directory ne supporte pas les connexions anonymes
67
-	 */
68
-	var $searchPassword;
69
-	/**
70
-	 *  DN des utilisateurs
71
-	 */
72
-	var $people;
73
-	/**
74
-	 * DN des groupes
75
-	 */
76
-	var $groups;
77
-	/**
78
-	 * Code erreur retourne par le serveur Ldap
79
-	 */
80
-	var $ldapErrorCode;
81
-	/**
82
-	 * Message texte de l'erreur
83
-	 */
84
-	var $ldapErrorText;
85
-
86
-
87
-	//Fetch user
88
-	var $name;
89
-	var $firstname;
90
-	var $login;
91
-	var $phone;
92
-	var $skype;
93
-	var $fax;
94
-	var $mail;
95
-	var $mobile;
96
-
97
-	var $uacf;
98
-	var $pwdlastset;
99
-
100
-	var $ldapcharset='UTF-8';	// LDAP should be UTF-8 encoded
101
-
102
-
103
-	/**
104
-	 * The internal LDAP connection handle
105
-	 */
106
-	var $connection;
107
-	/**
108
-	 * Result of any connections etc.
109
-	 */
110
-	var $result;
111
-
112
-
113
-	/**
114
-	 *  Constructor
115
-	 */
116
-	function __construct()
117
-	{
118
-		global $conf;
119
-
120
-		// Server
121
-		if (! empty($conf->global->LDAP_SERVER_HOST))       $this->server[] = $conf->global->LDAP_SERVER_HOST;
122
-		if (! empty($conf->global->LDAP_SERVER_HOST_SLAVE)) $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
123
-		$this->serverPort          = $conf->global->LDAP_SERVER_PORT;
124
-		$this->ldapProtocolVersion = $conf->global->LDAP_SERVER_PROTOCOLVERSION;
125
-		$this->dn                  = $conf->global->LDAP_SERVER_DN;
126
-		$this->serverType          = $conf->global->LDAP_SERVER_TYPE;
127
-		$this->domain              = $conf->global->LDAP_SERVER_DN;
128
-		$this->searchUser          = $conf->global->LDAP_ADMIN_DN;
129
-		$this->searchPassword      = $conf->global->LDAP_ADMIN_PASS;
130
-		$this->people              = $conf->global->LDAP_USER_DN;
131
-		$this->groups              = $conf->global->LDAP_GROUP_DN;
132
-
133
-		$this->filter              = $conf->global->LDAP_FILTER_CONNECTION;	// Filter on user
134
-		$this->filtermember        = $conf->global->LDAP_MEMBER_FILTER;		// Filter on member
135
-
136
-		// Users
137
-		$this->attr_login      = $conf->global->LDAP_FIELD_LOGIN; //unix
138
-		$this->attr_sambalogin = $conf->global->LDAP_FIELD_LOGIN_SAMBA; //samba, activedirectory
139
-		$this->attr_name       = $conf->global->LDAP_FIELD_NAME;
140
-		$this->attr_firstname  = $conf->global->LDAP_FIELD_FIRSTNAME;
141
-		$this->attr_mail       = $conf->global->LDAP_FIELD_MAIL;
142
-		$this->attr_phone      = $conf->global->LDAP_FIELD_PHONE;
143
-		$this->attr_skype      = $conf->global->LDAP_FIELD_SKYPE;
144
-		$this->attr_fax        = $conf->global->LDAP_FIELD_FAX;
145
-		$this->attr_mobile     = $conf->global->LDAP_FIELD_MOBILE;
146
-	}
147
-
148
-
149
-
150
-	// Connection handling methods -------------------------------------------
32
+    /**
33
+     * @var string Error code (or message)
34
+     */
35
+    public $error='';
36
+
37
+    /**
38
+     * @var string[]	Array of error strings
39
+     */
40
+    public $errors = array();
41
+
42
+    /**
43
+     * Tableau des serveurs (IP addresses ou nom d'hotes)
44
+     */
45
+    var $server=array();
46
+
47
+    /**
48
+     * Base DN (e.g. "dc=foo,dc=com")
49
+     */
50
+    var $dn;
51
+    /**
52
+     * type de serveur, actuellement OpenLdap et Active Directory
53
+     */
54
+    var $serverType;
55
+    /**
56
+     * Version du protocole ldap
57
+     */
58
+    var $domain;
59
+    /**
60
+     * User administrateur Ldap
61
+     * Active Directory ne supporte pas les connexions anonymes
62
+     */
63
+    var $searchUser;
64
+    /**
65
+     * Mot de passe de l'administrateur
66
+     * Active Directory ne supporte pas les connexions anonymes
67
+     */
68
+    var $searchPassword;
69
+    /**
70
+     *  DN des utilisateurs
71
+     */
72
+    var $people;
73
+    /**
74
+     * DN des groupes
75
+     */
76
+    var $groups;
77
+    /**
78
+     * Code erreur retourne par le serveur Ldap
79
+     */
80
+    var $ldapErrorCode;
81
+    /**
82
+     * Message texte de l'erreur
83
+     */
84
+    var $ldapErrorText;
85
+
86
+
87
+    //Fetch user
88
+    var $name;
89
+    var $firstname;
90
+    var $login;
91
+    var $phone;
92
+    var $skype;
93
+    var $fax;
94
+    var $mail;
95
+    var $mobile;
96
+
97
+    var $uacf;
98
+    var $pwdlastset;
99
+
100
+    var $ldapcharset='UTF-8';	// LDAP should be UTF-8 encoded
101
+
102
+
103
+    /**
104
+     * The internal LDAP connection handle
105
+     */
106
+    var $connection;
107
+    /**
108
+     * Result of any connections etc.
109
+     */
110
+    var $result;
111
+
112
+
113
+    /**
114
+     *  Constructor
115
+     */
116
+    function __construct()
117
+    {
118
+        global $conf;
119
+
120
+        // Server
121
+        if (! empty($conf->global->LDAP_SERVER_HOST))       $this->server[] = $conf->global->LDAP_SERVER_HOST;
122
+        if (! empty($conf->global->LDAP_SERVER_HOST_SLAVE)) $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
123
+        $this->serverPort          = $conf->global->LDAP_SERVER_PORT;
124
+        $this->ldapProtocolVersion = $conf->global->LDAP_SERVER_PROTOCOLVERSION;
125
+        $this->dn                  = $conf->global->LDAP_SERVER_DN;
126
+        $this->serverType          = $conf->global->LDAP_SERVER_TYPE;
127
+        $this->domain              = $conf->global->LDAP_SERVER_DN;
128
+        $this->searchUser          = $conf->global->LDAP_ADMIN_DN;
129
+        $this->searchPassword      = $conf->global->LDAP_ADMIN_PASS;
130
+        $this->people              = $conf->global->LDAP_USER_DN;
131
+        $this->groups              = $conf->global->LDAP_GROUP_DN;
132
+
133
+        $this->filter              = $conf->global->LDAP_FILTER_CONNECTION;	// Filter on user
134
+        $this->filtermember        = $conf->global->LDAP_MEMBER_FILTER;		// Filter on member
135
+
136
+        // Users
137
+        $this->attr_login      = $conf->global->LDAP_FIELD_LOGIN; //unix
138
+        $this->attr_sambalogin = $conf->global->LDAP_FIELD_LOGIN_SAMBA; //samba, activedirectory
139
+        $this->attr_name       = $conf->global->LDAP_FIELD_NAME;
140
+        $this->attr_firstname  = $conf->global->LDAP_FIELD_FIRSTNAME;
141
+        $this->attr_mail       = $conf->global->LDAP_FIELD_MAIL;
142
+        $this->attr_phone      = $conf->global->LDAP_FIELD_PHONE;
143
+        $this->attr_skype      = $conf->global->LDAP_FIELD_SKYPE;
144
+        $this->attr_fax        = $conf->global->LDAP_FIELD_FAX;
145
+        $this->attr_mobile     = $conf->global->LDAP_FIELD_MOBILE;
146
+    }
147
+
148
+
149
+
150
+    // Connection handling methods -------------------------------------------
151 151
 
152 152
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
153
-	/**
154
-	 *	Connect and bind
155
-	 * 	Use this->server, this->serverPort, this->ldapProtocolVersion, this->serverType, this->searchUser, this->searchPassword
156
-	 * 	After return, this->connection and $this->bind are defined
157
-	 *
158
-	 *	@return		int		<0 if KO, 1 if bind anonymous, 2 if bind auth
159
-	 */
160
-	function connect_bind()
161
-	{
153
+    /**
154
+     *	Connect and bind
155
+     * 	Use this->server, this->serverPort, this->ldapProtocolVersion, this->serverType, this->searchUser, this->searchPassword
156
+     * 	After return, this->connection and $this->bind are defined
157
+     *
158
+     *	@return		int		<0 if KO, 1 if bind anonymous, 2 if bind auth
159
+     */
160
+    function connect_bind()
161
+    {
162 162
         // phpcs:enable
163
-		global $langs, $conf;
164
-
165
-		$connected=0;
166
-		$this->bind=0;
167
-
168
-		// Check parameters
169
-		if (count($this->server) == 0 || empty($this->server[0]))
170
-		{
171
-			$this->error='LDAP setup (file conf.php) is not complete';
172
-			dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
173
-			return -1;
174
-		}
175
-
176
-		if (! function_exists("ldap_connect"))
177
-		{
178
-			$this->error='LDAPFunctionsNotAvailableOnPHP';
179
-			dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
180
-			$return=-1;
181
-		}
182
-
183
-		if (empty($this->error))
184
-		{
185
-			// Loop on each ldap server
186
-			foreach ($this->server as $key => $host)
187
-			{
188
-				if ($connected) break;
189
-				if (empty($host)) continue;
190
-
191
-				if ($this->serverPing($host, $this->serverPort) === true) {
192
-					$this->connection = ldap_connect($host, $this->serverPort);
193
-				}
194
-				else continue;
195
-
196
-				if (is_resource($this->connection))
197
-				{
198
-					// Begin TLS if requested by the configuration
199
-					if (! empty($conf->global->LDAP_SERVER_USE_TLS))
200
-					{
201
-						if (! ldap_start_tls($this->connection))
202
-						{
203
-							dol_syslog(get_class($this)."::connect_bind failed to start tls", LOG_WARNING);
204
-							$connected = 0;
205
-							$this->close();
206
-						}
207
-					}
208
-
209
-					// Execute the ldap_set_option here (after connect and before bind)
210
-					$this->setVersion();
211
-					ldap_set_option($this->connection, LDAP_OPT_SIZELIMIT, 0); // no limit here. should return true.
212
-
213
-
214
-					if ($this->serverType == "activedirectory")
215
-					{
216
-						$result=$this->setReferrals();
217
-						dol_syslog(get_class($this)."::connect_bind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./','*',$this->searchPassword),LOG_DEBUG);
218
-						$this->result=$this->bindauth($this->searchUser,$this->searchPassword);
219
-						if ($this->result)
220
-						{
221
-							$this->bind=$this->result;
222
-							$connected=2;
223
-							break;
224
-						}
225
-						else
226
-						{
227
-							$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
228
-						}
229
-					}
230
-					else
231
-					{
232
-						// Try in auth mode
233
-						if ($this->searchUser && $this->searchPassword)
234
-						{
235
-							dol_syslog(get_class($this)."::connect_bind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./','*',$this->searchPassword),LOG_DEBUG);
236
-							$this->result=$this->bindauth($this->searchUser,$this->searchPassword);
237
-							if ($this->result)
238
-							{
239
-								$this->bind=$this->result;
240
-								$connected=2;
241
-								break;
242
-							}
243
-							else
244
-							{
245
-								$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
246
-							}
247
-						}
248
-						// Try in anonymous
249
-						if (! $this->bind)
250
-						{
251
-							dol_syslog(get_class($this)."::connect_bind try bind on ".$host,LOG_DEBUG);
252
-							$result=$this->bind();
253
-							if ($result)
254
-							{
255
-								$this->bind=$this->result;
256
-								$connected=1;
257
-								break;
258
-							}
259
-							else
260
-							{
261
-								$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
262
-							}
263
-						}
264
-					}
265
-				}
266
-
267
-				if (! $connected) $this->close();
268
-			}
269
-		}
270
-
271
-		if ($connected)
272
-		{
273
-			$return=$connected;
274
-			dol_syslog(get_class($this)."::connect_bind return=".$return, LOG_DEBUG);
275
-		}
276
-		else
277
-		{
278
-			$this->error='Failed to connect to LDAP'.($this->error?': '.$this->error:'');
279
-			$return=-1;
280
-			dol_syslog(get_class($this)."::connect_bind return=".$return.' - '.$this->error, LOG_WARNING);
281
-		}
282
-		return $return;
283
-	}
284
-
285
-
286
-
287
-	/**
288
-	 * Simply closes the connection set up earlier.
289
-	 * Returns true if OK, false if there was an error.
290
-	 *
291
-	 * @return	boolean			true or false
292
-	 */
293
-	function close()
294
-	{
295
-		if ($this->connection && ! @ldap_close($this->connection))
296
-		{
297
-			return false;
298
-		}
299
-		else
300
-		{
301
-			return true;
302
-		}
303
-	}
304
-
305
-	/**
306
-	 * Anonymously binds to the connection. After this is done,
307
-	 * queries and searches can be done - but read-only.
308
-	 *
309
-	 * @return	boolean			true or false
310
-	 */
311
-	function bind()
312
-	{
313
-		if (! $this->result=@ldap_bind($this->connection))
314
-		{
315
-			$this->ldapErrorCode = ldap_errno($this->connection);
316
-			$this->ldapErrorText = ldap_error($this->connection);
317
-			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
318
-			return false;
319
-		}
320
-		else
321
-		{
322
-			return true;
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * Binds as an authenticated user, which usually allows for write
328
-	 * access. The FULL dn must be passed. For a directory manager, this is
329
-	 * "cn=Directory Manager" under iPlanet. For a user, it will be something
330
-	 * like "uid=jbloggs,ou=People,dc=foo,dc=com".
331
-	 *
332
-	 * @param	string	$bindDn			DN
333
-	 * @param	string	$pass			Password
334
-	 * @return	boolean					true or false
335
-	 */
336
-	function bindauth($bindDn,$pass)
337
-	{
338
-		if (! $this->result = @ldap_bind($this->connection, $bindDn, $pass))
339
-		{
340
-			$this->ldapErrorCode = ldap_errno($this->connection);
341
-			$this->ldapErrorText = ldap_error($this->connection);
342
-			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
343
-			return false;
344
-		}
345
-		else
346
-		{
347
-			return true;
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * Unbind du serveur ldap.
353
-	 *
354
-	 * @return	boolean					true or false
355
-	 */
356
-	function unbind()
357
-	{
358
-		if (!$this->result=@ldap_unbind($this->connection))
359
-		{
360
-			return false;
361
-		} else {
362
-			return true;
363
-		}
364
-	}
365
-
366
-
367
-	/**
368
-	 * Verification de la version du serveur ldap.
369
-	 *
370
-	 * @return	string					version
371
-	 */
372
-	function getVersion()
373
-	{
374
-		$version = 0;
375
-		$version = @ldap_get_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $version);
376
-		return $version;
377
-	}
378
-
379
-	/**
380
-	 * Change ldap protocol version to use.
381
-	 *
382
-	 * @return	boolean					version
383
-	 */
163
+        global $langs, $conf;
164
+
165
+        $connected=0;
166
+        $this->bind=0;
167
+
168
+        // Check parameters
169
+        if (count($this->server) == 0 || empty($this->server[0]))
170
+        {
171
+            $this->error='LDAP setup (file conf.php) is not complete';
172
+            dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
173
+            return -1;
174
+        }
175
+
176
+        if (! function_exists("ldap_connect"))
177
+        {
178
+            $this->error='LDAPFunctionsNotAvailableOnPHP';
179
+            dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
180
+            $return=-1;
181
+        }
182
+
183
+        if (empty($this->error))
184
+        {
185
+            // Loop on each ldap server
186
+            foreach ($this->server as $key => $host)
187
+            {
188
+                if ($connected) break;
189
+                if (empty($host)) continue;
190
+
191
+                if ($this->serverPing($host, $this->serverPort) === true) {
192
+                    $this->connection = ldap_connect($host, $this->serverPort);
193
+                }
194
+                else continue;
195
+
196
+                if (is_resource($this->connection))
197
+                {
198
+                    // Begin TLS if requested by the configuration
199
+                    if (! empty($conf->global->LDAP_SERVER_USE_TLS))
200
+                    {
201
+                        if (! ldap_start_tls($this->connection))
202
+                        {
203
+                            dol_syslog(get_class($this)."::connect_bind failed to start tls", LOG_WARNING);
204
+                            $connected = 0;
205
+                            $this->close();
206
+                        }
207
+                    }
208
+
209
+                    // Execute the ldap_set_option here (after connect and before bind)
210
+                    $this->setVersion();
211
+                    ldap_set_option($this->connection, LDAP_OPT_SIZELIMIT, 0); // no limit here. should return true.
212
+
213
+
214
+                    if ($this->serverType == "activedirectory")
215
+                    {
216
+                        $result=$this->setReferrals();
217
+                        dol_syslog(get_class($this)."::connect_bind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./','*',$this->searchPassword),LOG_DEBUG);
218
+                        $this->result=$this->bindauth($this->searchUser,$this->searchPassword);
219
+                        if ($this->result)
220
+                        {
221
+                            $this->bind=$this->result;
222
+                            $connected=2;
223
+                            break;
224
+                        }
225
+                        else
226
+                        {
227
+                            $this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
228
+                        }
229
+                    }
230
+                    else
231
+                    {
232
+                        // Try in auth mode
233
+                        if ($this->searchUser && $this->searchPassword)
234
+                        {
235
+                            dol_syslog(get_class($this)."::connect_bind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./','*',$this->searchPassword),LOG_DEBUG);
236
+                            $this->result=$this->bindauth($this->searchUser,$this->searchPassword);
237
+                            if ($this->result)
238
+                            {
239
+                                $this->bind=$this->result;
240
+                                $connected=2;
241
+                                break;
242
+                            }
243
+                            else
244
+                            {
245
+                                $this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
246
+                            }
247
+                        }
248
+                        // Try in anonymous
249
+                        if (! $this->bind)
250
+                        {
251
+                            dol_syslog(get_class($this)."::connect_bind try bind on ".$host,LOG_DEBUG);
252
+                            $result=$this->bind();
253
+                            if ($result)
254
+                            {
255
+                                $this->bind=$this->result;
256
+                                $connected=1;
257
+                                break;
258
+                            }
259
+                            else
260
+                            {
261
+                                $this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
262
+                            }
263
+                        }
264
+                    }
265
+                }
266
+
267
+                if (! $connected) $this->close();
268
+            }
269
+        }
270
+
271
+        if ($connected)
272
+        {
273
+            $return=$connected;
274
+            dol_syslog(get_class($this)."::connect_bind return=".$return, LOG_DEBUG);
275
+        }
276
+        else
277
+        {
278
+            $this->error='Failed to connect to LDAP'.($this->error?': '.$this->error:'');
279
+            $return=-1;
280
+            dol_syslog(get_class($this)."::connect_bind return=".$return.' - '.$this->error, LOG_WARNING);
281
+        }
282
+        return $return;
283
+    }
284
+
285
+
286
+
287
+    /**
288
+     * Simply closes the connection set up earlier.
289
+     * Returns true if OK, false if there was an error.
290
+     *
291
+     * @return	boolean			true or false
292
+     */
293
+    function close()
294
+    {
295
+        if ($this->connection && ! @ldap_close($this->connection))
296
+        {
297
+            return false;
298
+        }
299
+        else
300
+        {
301
+            return true;
302
+        }
303
+    }
304
+
305
+    /**
306
+     * Anonymously binds to the connection. After this is done,
307
+     * queries and searches can be done - but read-only.
308
+     *
309
+     * @return	boolean			true or false
310
+     */
311
+    function bind()
312
+    {
313
+        if (! $this->result=@ldap_bind($this->connection))
314
+        {
315
+            $this->ldapErrorCode = ldap_errno($this->connection);
316
+            $this->ldapErrorText = ldap_error($this->connection);
317
+            $this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
318
+            return false;
319
+        }
320
+        else
321
+        {
322
+            return true;
323
+        }
324
+    }
325
+
326
+    /**
327
+     * Binds as an authenticated user, which usually allows for write
328
+     * access. The FULL dn must be passed. For a directory manager, this is
329
+     * "cn=Directory Manager" under iPlanet. For a user, it will be something
330
+     * like "uid=jbloggs,ou=People,dc=foo,dc=com".
331
+     *
332
+     * @param	string	$bindDn			DN
333
+     * @param	string	$pass			Password
334
+     * @return	boolean					true or false
335
+     */
336
+    function bindauth($bindDn,$pass)
337
+    {
338
+        if (! $this->result = @ldap_bind($this->connection, $bindDn, $pass))
339
+        {
340
+            $this->ldapErrorCode = ldap_errno($this->connection);
341
+            $this->ldapErrorText = ldap_error($this->connection);
342
+            $this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
343
+            return false;
344
+        }
345
+        else
346
+        {
347
+            return true;
348
+        }
349
+    }
350
+
351
+    /**
352
+     * Unbind du serveur ldap.
353
+     *
354
+     * @return	boolean					true or false
355
+     */
356
+    function unbind()
357
+    {
358
+        if (!$this->result=@ldap_unbind($this->connection))
359
+        {
360
+            return false;
361
+        } else {
362
+            return true;
363
+        }
364
+    }
365
+
366
+
367
+    /**
368
+     * Verification de la version du serveur ldap.
369
+     *
370
+     * @return	string					version
371
+     */
372
+    function getVersion()
373
+    {
374
+        $version = 0;
375
+        $version = @ldap_get_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $version);
376
+        return $version;
377
+    }
378
+
379
+    /**
380
+     * Change ldap protocol version to use.
381
+     *
382
+     * @return	boolean					version
383
+     */
384 384
     function setVersion()
385 385
     {
386
-		// LDAP_OPT_PROTOCOL_VERSION est une constante qui vaut 17
387
-		$ldapsetversion = ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $this->ldapProtocolVersion);
388
-		return $ldapsetversion;
389
-	}
390
-
391
-	/**
392
-	 * changement du referrals.
393
-	 *
394
-	 * @return	boolean					referrals
395
-	 */
386
+        // LDAP_OPT_PROTOCOL_VERSION est une constante qui vaut 17
387
+        $ldapsetversion = ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $this->ldapProtocolVersion);
388
+        return $ldapsetversion;
389
+    }
390
+
391
+    /**
392
+     * changement du referrals.
393
+     *
394
+     * @return	boolean					referrals
395
+     */
396 396
     function setReferrals()
397 397
     {
398
-		// LDAP_OPT_REFERRALS est une constante qui vaut ?
399
-		$ldapreferrals = ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
400
-		return $ldapreferrals;
401
-	}
402
-
403
-
404
-	/**
405
-	 * 	Add a LDAP entry
406
-	 *	Ldap object connect and bind must have been done
407
-	 *
408
-	 *	@param	string	$dn			DN entry key
409
-	 *	@param	array	$info		Attributes array
410
-	 *	@param	User		$user		Objet user that create
411
-	 *	@return	int					<0 if KO, >0 if OK
412
-	 */
413
-	function add($dn, $info, $user)
414
-	{
415
-		global $conf;
416
-
417
-		dol_syslog(get_class($this)."::add dn=".$dn." info=".join(',',$info));
418
-
419
-		// Check parameters
420
-		if (! $this->connection)
421
-		{
422
-			$this->error="NotConnected";
423
-			return -2;
424
-		}
425
-		if (! $this->bind)
426
-		{
427
-			$this->error="NotConnected";
428
-			return -3;
429
-		}
430
-
431
-		// Encode to LDAP page code
432
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
433
-		foreach($info as $key => $val)
434
-		{
435
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
436
-		}
437
-
438
-		$this->dump($dn,$info);
439
-
440
-		//print_r($info);
441
-		$result=@ldap_add($this->connection, $dn, $info);
442
-
443
-		if ($result)
444
-		{
445
-			dol_syslog(get_class($this)."::add successfull", LOG_DEBUG);
446
-			return 1;
447
-		}
448
-		else
449
-		{
450
-			$this->ldapErrorCode = @ldap_errno($this->connection);
451
-			$this->ldapErrorText = @ldap_error($this->connection);
452
-			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
453
-			dol_syslog(get_class($this)."::add failed: ".$this->error, LOG_ERR);
454
-			return -1;
455
-		}
456
-	}
457
-
458
-	/**
459
-	 * 	Modify a LDAP entry
460
-	 *	Ldap object connect and bind must have been done
461
-	 *
462
-	 *	@param	string		$dn			DN entry key
463
-	 *	@param	array		$info		Attributes array
464
-	 *	@param	User			$user		Objet user that modify
465
-	 *	@return	int						<0 if KO, >0 if OK
466
-	 */
467
-	function modify($dn, $info, $user)
468
-	{
469
-		global $conf;
470
-
471
-		dol_syslog(get_class($this)."::modify dn=".$dn." info=".join(',',$info));
472
-
473
-		// Check parameters
474
-		if (! $this->connection)
475
-		{
476
-			$this->error="NotConnected";
477
-			return -2;
478
-		}
479
-		if (! $this->bind)
480
-		{
481
-			$this->error="NotConnected";
482
-			return -3;
483
-		}
484
-
485
-		// Encode to LDAP page code
486
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
487
-		foreach($info as $key => $val)
488
-		{
489
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
490
-		}
491
-
492
-		$this->dump($dn,$info);
493
-
494
-		//print_r($info);
495
-		$result=@ldap_modify($this->connection, $dn, $info);
496
-
497
-		if ($result)
498
-		{
499
-			dol_syslog(get_class($this)."::modify successfull", LOG_DEBUG);
500
-			return 1;
501
-		}
502
-		else
503
-		{
504
-			$this->error=@ldap_error($this->connection);
505
-			dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
506
-			return -1;
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * 	Rename a LDAP entry
512
-	 *	Ldap object connect and bind must have been done
513
-	 *
514
-	 *	@param	string		$dn				Old DN entry key (uid=qqq,ou=xxx,dc=aaa,dc=bbb) (before update)
515
-	 *	@param	string		$newrdn			New RDN entry key (uid=qqq)
516
-	 *	@param	string		$newparent		New parent (ou=xxx,dc=aaa,dc=bbb)
517
-	 *	@param	User			$user			Objet user that modify
518
-	 *	@param	bool			$deleteoldrdn	If true the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.
519
-	 *	@return	int							<0 if KO, >0 if OK
520
-	 */
521
-	function rename($dn, $newrdn, $newparent, $user, $deleteoldrdn = true)
522
-	{
523
-		global $conf;
524
-
525
-		dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn?1:0));
526
-
527
-		// Check parameters
528
-		if (! $this->connection)
529
-		{
530
-			$this->error="NotConnected";
531
-			return -2;
532
-		}
533
-		if (! $this->bind)
534
-		{
535
-			$this->error="NotConnected";
536
-			return -3;
537
-		}
538
-
539
-		// Encode to LDAP page code
540
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
541
-		$newrdn=$this->convFromOutputCharset($newrdn,$this->ldapcharset);
542
-		$newparent=$this->convFromOutputCharset($newparent,$this->ldapcharset);
543
-
544
-		//print_r($info);
545
-		$result=@ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
546
-
547
-		if ($result)
548
-		{
549
-			dol_syslog(get_class($this)."::rename successfull", LOG_DEBUG);
550
-			return 1;
551
-		}
552
-		else
553
-		{
554
-			$this->error=@ldap_error($this->connection);
555
-			dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
556
-			return -1;
557
-		}
558
-	}
559
-
560
-	/**
561
-	 *  Modify a LDAP entry (to use if dn != olddn)
562
-	 *	Ldap object connect and bind must have been done
563
-	 *
564
-	 *  @param	string	$dn			DN entry key
565
-	 *  @param	array	$info		Attributes array
566
-	 *  @param	User		$user		Objet user that update
567
-	 * 	@param	string	$olddn		Old DN entry key (before update)
568
-	 * 	@param	string	$newrdn		New RDN entry key (uid=qqq) (for ldap_rename)
569
-	 *	@param	string	$newparent	New parent (ou=xxx,dc=aaa,dc=bbb) (for ldap_rename)
570
-	 *	@return	int					<0 if KO, >0 if OK
571
-	 */
572
-	function update($dn, $info, $user, $olddn, $newrdn=false, $newparent=false)
573
-	{
574
-		global $conf;
575
-
576
-		dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
577
-
578
-		// Check parameters
579
-		if (! $this->connection)
580
-		{
581
-			$this->error="NotConnected";
582
-			return -2;
583
-		}
584
-		if (! $this->bind)
585
-		{
586
-			$this->error="NotConnected";
587
-			return -3;
588
-		}
589
-
590
-		if (! $olddn || $olddn != $dn)
591
-		{
592
-			if (! empty($olddn) && ! empty($newrdn) && ! empty($newparent) && $conf->global->LDAP_SERVER_PROTOCOLVERSION === '3')
593
-			{
594
-				// This function currently only works with LDAPv3
595
-				$result = $this->rename($olddn, $newrdn, $newparent, $user, true);
596
-			}
597
-			else
598
-			{
599
-				// If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
600
-				$result = $this->add($dn, $info, $user);
601
-				if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn);	// If add fails, we do not try to delete old one
602
-			}
603
-		}
604
-		else
605
-		{
606
-			//$result = $this->delete($olddn);
607
-			$result = $this->add($dn, $info, $user);	// If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
608
-			$result = $this->modify($dn, $info, $user);	// We use add/modify instead of delete/add when olddn is received
609
-		}
610
-		if ($result <= 0)
611
-		{
612
-			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection)." ".$this->error;
613
-			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
614
-			//print_r($info);
615
-			return -1;
616
-		}
617
-		else
618
-		{
619
-			dol_syslog(get_class($this)."::update done successfully");
620
-			return 1;
621
-		}
622
-	}
623
-
624
-
625
-	/**
626
-	 * 	Delete a LDAP entry
627
-	 *	Ldap object connect and bind must have been done
628
-	 *
629
-	 *	@param	string	$dn			DN entry key
630
-	 *	@return	int					<0 if KO, >0 if OK
631
-	 */
632
-	function delete($dn)
633
-	{
634
-		global $conf;
635
-
636
-		dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
637
-
638
-		// Check parameters
639
-		if (! $this->connection)
640
-		{
641
-			$this->error="NotConnected";
642
-			return -2;
643
-		}
644
-		if (! $this->bind)
645
-		{
646
-			$this->error="NotConnected";
647
-			return -3;
648
-		}
649
-
650
-		// Encode to LDAP page code
651
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
652
-
653
-		$result=@ldap_delete($this->connection, $dn);
654
-
655
-		if ($result) return 1;
656
-		return -1;
657
-	}
398
+        // LDAP_OPT_REFERRALS est une constante qui vaut ?
399
+        $ldapreferrals = ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
400
+        return $ldapreferrals;
401
+    }
402
+
403
+
404
+    /**
405
+     * 	Add a LDAP entry
406
+     *	Ldap object connect and bind must have been done
407
+     *
408
+     *	@param	string	$dn			DN entry key
409
+     *	@param	array	$info		Attributes array
410
+     *	@param	User		$user		Objet user that create
411
+     *	@return	int					<0 if KO, >0 if OK
412
+     */
413
+    function add($dn, $info, $user)
414
+    {
415
+        global $conf;
416
+
417
+        dol_syslog(get_class($this)."::add dn=".$dn." info=".join(',',$info));
418
+
419
+        // Check parameters
420
+        if (! $this->connection)
421
+        {
422
+            $this->error="NotConnected";
423
+            return -2;
424
+        }
425
+        if (! $this->bind)
426
+        {
427
+            $this->error="NotConnected";
428
+            return -3;
429
+        }
430
+
431
+        // Encode to LDAP page code
432
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
433
+        foreach($info as $key => $val)
434
+        {
435
+            if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
436
+        }
437
+
438
+        $this->dump($dn,$info);
439
+
440
+        //print_r($info);
441
+        $result=@ldap_add($this->connection, $dn, $info);
442
+
443
+        if ($result)
444
+        {
445
+            dol_syslog(get_class($this)."::add successfull", LOG_DEBUG);
446
+            return 1;
447
+        }
448
+        else
449
+        {
450
+            $this->ldapErrorCode = @ldap_errno($this->connection);
451
+            $this->ldapErrorText = @ldap_error($this->connection);
452
+            $this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
453
+            dol_syslog(get_class($this)."::add failed: ".$this->error, LOG_ERR);
454
+            return -1;
455
+        }
456
+    }
457
+
458
+    /**
459
+     * 	Modify a LDAP entry
460
+     *	Ldap object connect and bind must have been done
461
+     *
462
+     *	@param	string		$dn			DN entry key
463
+     *	@param	array		$info		Attributes array
464
+     *	@param	User			$user		Objet user that modify
465
+     *	@return	int						<0 if KO, >0 if OK
466
+     */
467
+    function modify($dn, $info, $user)
468
+    {
469
+        global $conf;
470
+
471
+        dol_syslog(get_class($this)."::modify dn=".$dn." info=".join(',',$info));
472
+
473
+        // Check parameters
474
+        if (! $this->connection)
475
+        {
476
+            $this->error="NotConnected";
477
+            return -2;
478
+        }
479
+        if (! $this->bind)
480
+        {
481
+            $this->error="NotConnected";
482
+            return -3;
483
+        }
484
+
485
+        // Encode to LDAP page code
486
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
487
+        foreach($info as $key => $val)
488
+        {
489
+            if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
490
+        }
491
+
492
+        $this->dump($dn,$info);
493
+
494
+        //print_r($info);
495
+        $result=@ldap_modify($this->connection, $dn, $info);
496
+
497
+        if ($result)
498
+        {
499
+            dol_syslog(get_class($this)."::modify successfull", LOG_DEBUG);
500
+            return 1;
501
+        }
502
+        else
503
+        {
504
+            $this->error=@ldap_error($this->connection);
505
+            dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
506
+            return -1;
507
+        }
508
+    }
509
+
510
+    /**
511
+     * 	Rename a LDAP entry
512
+     *	Ldap object connect and bind must have been done
513
+     *
514
+     *	@param	string		$dn				Old DN entry key (uid=qqq,ou=xxx,dc=aaa,dc=bbb) (before update)
515
+     *	@param	string		$newrdn			New RDN entry key (uid=qqq)
516
+     *	@param	string		$newparent		New parent (ou=xxx,dc=aaa,dc=bbb)
517
+     *	@param	User			$user			Objet user that modify
518
+     *	@param	bool			$deleteoldrdn	If true the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.
519
+     *	@return	int							<0 if KO, >0 if OK
520
+     */
521
+    function rename($dn, $newrdn, $newparent, $user, $deleteoldrdn = true)
522
+    {
523
+        global $conf;
524
+
525
+        dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn?1:0));
526
+
527
+        // Check parameters
528
+        if (! $this->connection)
529
+        {
530
+            $this->error="NotConnected";
531
+            return -2;
532
+        }
533
+        if (! $this->bind)
534
+        {
535
+            $this->error="NotConnected";
536
+            return -3;
537
+        }
538
+
539
+        // Encode to LDAP page code
540
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
541
+        $newrdn=$this->convFromOutputCharset($newrdn,$this->ldapcharset);
542
+        $newparent=$this->convFromOutputCharset($newparent,$this->ldapcharset);
543
+
544
+        //print_r($info);
545
+        $result=@ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
546
+
547
+        if ($result)
548
+        {
549
+            dol_syslog(get_class($this)."::rename successfull", LOG_DEBUG);
550
+            return 1;
551
+        }
552
+        else
553
+        {
554
+            $this->error=@ldap_error($this->connection);
555
+            dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
556
+            return -1;
557
+        }
558
+    }
559
+
560
+    /**
561
+     *  Modify a LDAP entry (to use if dn != olddn)
562
+     *	Ldap object connect and bind must have been done
563
+     *
564
+     *  @param	string	$dn			DN entry key
565
+     *  @param	array	$info		Attributes array
566
+     *  @param	User		$user		Objet user that update
567
+     * 	@param	string	$olddn		Old DN entry key (before update)
568
+     * 	@param	string	$newrdn		New RDN entry key (uid=qqq) (for ldap_rename)
569
+     *	@param	string	$newparent	New parent (ou=xxx,dc=aaa,dc=bbb) (for ldap_rename)
570
+     *	@return	int					<0 if KO, >0 if OK
571
+     */
572
+    function update($dn, $info, $user, $olddn, $newrdn=false, $newparent=false)
573
+    {
574
+        global $conf;
575
+
576
+        dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
577
+
578
+        // Check parameters
579
+        if (! $this->connection)
580
+        {
581
+            $this->error="NotConnected";
582
+            return -2;
583
+        }
584
+        if (! $this->bind)
585
+        {
586
+            $this->error="NotConnected";
587
+            return -3;
588
+        }
589
+
590
+        if (! $olddn || $olddn != $dn)
591
+        {
592
+            if (! empty($olddn) && ! empty($newrdn) && ! empty($newparent) && $conf->global->LDAP_SERVER_PROTOCOLVERSION === '3')
593
+            {
594
+                // This function currently only works with LDAPv3
595
+                $result = $this->rename($olddn, $newrdn, $newparent, $user, true);
596
+            }
597
+            else
598
+            {
599
+                // If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
600
+                $result = $this->add($dn, $info, $user);
601
+                if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn);	// If add fails, we do not try to delete old one
602
+            }
603
+        }
604
+        else
605
+        {
606
+            //$result = $this->delete($olddn);
607
+            $result = $this->add($dn, $info, $user);	// If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
608
+            $result = $this->modify($dn, $info, $user);	// We use add/modify instead of delete/add when olddn is received
609
+        }
610
+        if ($result <= 0)
611
+        {
612
+            $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection)." ".$this->error;
613
+            dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
614
+            //print_r($info);
615
+            return -1;
616
+        }
617
+        else
618
+        {
619
+            dol_syslog(get_class($this)."::update done successfully");
620
+            return 1;
621
+        }
622
+    }
623
+
624
+
625
+    /**
626
+     * 	Delete a LDAP entry
627
+     *	Ldap object connect and bind must have been done
628
+     *
629
+     *	@param	string	$dn			DN entry key
630
+     *	@return	int					<0 if KO, >0 if OK
631
+     */
632
+    function delete($dn)
633
+    {
634
+        global $conf;
635
+
636
+        dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
637
+
638
+        // Check parameters
639
+        if (! $this->connection)
640
+        {
641
+            $this->error="NotConnected";
642
+            return -2;
643
+        }
644
+        if (! $this->bind)
645
+        {
646
+            $this->error="NotConnected";
647
+            return -3;
648
+        }
649
+
650
+        // Encode to LDAP page code
651
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
652
+
653
+        $result=@ldap_delete($this->connection, $dn);
654
+
655
+        if ($result) return 1;
656
+        return -1;
657
+    }
658 658
 
659 659
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
660
-	/**
661
-	 * 	Build a LDAP message
662
-	 *
663
-	 *	@param	string		$dn			DN entry key
664
-	 *	@param	array		$info		Attributes array
665
-	 *	@return	string					Content of file
666
-	 */
667
-	function dump_content($dn, $info)
668
-	{
660
+    /**
661
+     * 	Build a LDAP message
662
+     *
663
+     *	@param	string		$dn			DN entry key
664
+     *	@param	array		$info		Attributes array
665
+     *	@return	string					Content of file
666
+     */
667
+    function dump_content($dn, $info)
668
+    {
669 669
         // phpcs:enable
670
-		$content='';
671
-
672
-		// Create file content
673
-		if (preg_match('/^ldap/',$this->server[0]))
674
-		{
675
-			$target="-H ".join(',',$this->server);
676
-		}
677
-		else
678
-		{
679
-			$target="-h ".join(',',$this->server)." -p ".$this->serverPort;
680
-		}
681
-		$content.="# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
682
-		$content.="# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
683
-		$content.="# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
684
-		if (in_array('localhost',$this->server)) $content.="# If commands fails to connect, try without -h and -p\n";
685
-		$content.="dn: ".$dn."\n";
686
-		foreach($info as $key => $value)
687
-		{
688
-			if (! is_array($value))
689
-			{
690
-				$content.="$key: $value\n";
691
-			}
692
-			else
693
-			{
694
-				foreach($value as $valuekey => $valuevalue)
695
-				{
696
-					$content.="$key: $valuevalue\n";
697
-				}
698
-			}
699
-		}
700
-		return $content;
701
-	}
702
-
703
-	/**
704
-	 * 	Dump a LDAP message to ldapinput.in file
705
-	 *
706
-	 *	@param	string		$dn			DN entry key
707
-	 *	@param	array		$info		Attributes array
708
-	 *	@return	int						<0 if KO, >0 if OK
709
-	 */
710
-	function dump($dn, $info)
711
-	{
712
-		global $conf;
713
-
714
-		// Create content
715
-		$content=$this->dump_content($dn, $info);
716
-
717
-		//Create file
718
-		$result=dol_mkdir($conf->ldap->dir_temp);
719
-
720
-		$outputfile=$conf->ldap->dir_temp.'/ldapinput.in';
721
-		$fp=fopen($outputfile,"w");
722
-		if ($fp)
723
-		{
724
-			fputs($fp, $content);
725
-			fclose($fp);
726
-			if (! empty($conf->global->MAIN_UMASK))
727
-			@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
728
-			return 1;
729
-		}
730
-		else
731
-		{
732
-			return -1;
733
-		}
734
-	}
735
-
736
-	/**
737
-	 * Ping a server before ldap_connect for avoid waiting
738
-	 *
739
-	 * @param string		$host		Server host or address
740
-	 * @param int		$port		Server port (default 389)
741
-	 * @param int		$timeout		Timeout in second (default 1s)
742
-	 * @return boolean				true or false
743
-	 */
744
-	function serverPing($host, $port=389, $timeout=1)
745
-	{
746
-		// Replace ldaps:// by ssl://
747
-		if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/',$host, $regs)) {
748
-			$host = 'ssl://'.$regs[1];
749
-		}
750
-		// Remove ldap://
751
-		if (preg_match('/^ldap:\/\/([^\/]+)\/?$/',$host, $regs)) {
752
-			$host = $regs[1];
753
-		}
754
-		$op = @fsockopen($host, $port, $errno, $errstr, $timeout);
755
-		if (!$op) return false; //DC is N/A
756
-		else {
757
-			fclose($op); //explicitly close open socket connection
758
-			return true; //DC is up & running, we can safely connect with ldap_connect
759
-		}
760
-	}
761
-
762
-
763
-	// Attribute methods -----------------------------------------------------
764
-
765
-	/**
766
-	 * 	Add a LDAP attribute in entry
767
-	 *	Ldap object connect and bind must have been done
768
-	 *
769
-	 *	@param	string		$dn			DN entry key
770
-	 *	@param	array		$info		Attributes array
771
-	 *	@param	User		$user		Objet user that create
772
-	 *	@return	int						<0 if KO, >0 if OK
773
-	 */
774
-	function addAttribute($dn, $info, $user)
775
-	{
776
-		global $conf;
777
-
778
-		dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".join(',',$info));
779
-
780
-		// Check parameters
781
-		if (! $this->connection)
782
-		{
783
-			$this->error="NotConnected";
784
-			return -2;
785
-		}
786
-		if (! $this->bind)
787
-		{
788
-			$this->error="NotConnected";
789
-			return -3;
790
-		}
791
-
792
-		// Encode to LDAP page code
793
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
794
-		foreach($info as $key => $val)
795
-		{
796
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
797
-		}
798
-
799
-		$this->dump($dn,$info);
800
-
801
-		//print_r($info);
802
-		$result=@ldap_mod_add($this->connection, $dn, $info);
803
-
804
-		if ($result)
805
-		{
806
-			dol_syslog(get_class($this)."::add_attribute successfull", LOG_DEBUG);
807
-			return 1;
808
-		}
809
-		else
810
-		{
811
-			$this->error=@ldap_error($this->connection);
812
-			dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
813
-			return -1;
814
-		}
815
-	}
816
-
817
-	/**
818
-	 * 	Update a LDAP attribute in entry
819
-	 *	Ldap object connect and bind must have been done
820
-	 *
821
-	 *	@param	string		$dn			DN entry key
822
-	 *	@param	array		$info		Attributes array
823
-	 *	@param	User		$user		Objet user that create
824
-	 *	@return	int						<0 if KO, >0 if OK
825
-	 */
826
-	function updateAttribute($dn, $info, $user)
827
-	{
828
-		global $conf;
829
-
830
-		dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".join(',',$info));
831
-
832
-		// Check parameters
833
-		if (! $this->connection)
834
-		{
835
-			$this->error="NotConnected";
836
-			return -2;
837
-		}
838
-		if (! $this->bind)
839
-		{
840
-			$this->error="NotConnected";
841
-			return -3;
842
-		}
843
-
844
-		// Encode to LDAP page code
845
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
846
-		foreach($info as $key => $val)
847
-		{
848
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
849
-		}
850
-
851
-		$this->dump($dn,$info);
852
-
853
-		//print_r($info);
854
-		$result=@ldap_mod_replace($this->connection, $dn, $info);
855
-
856
-		if ($result)
857
-		{
858
-			dol_syslog(get_class($this)."::updateAttribute successfull", LOG_DEBUG);
859
-			return 1;
860
-		}
861
-		else
862
-		{
863
-			$this->error=@ldap_error($this->connection);
864
-			dol_syslog(get_class($this)."::updateAttribute failed: ".$this->error, LOG_ERR);
865
-			return -1;
866
-		}
867
-	}
868
-
869
-	/**
870
-	 * 	Delete a LDAP attribute in entry
871
-	 *	Ldap object connect and bind must have been done
872
-	 *
873
-	 *	@param	string		$dn			DN entry key
874
-	 *	@param	array		$info		Attributes array
875
-	 *	@param	User		$user		Objet user that create
876
-	 *	@return	int						<0 if KO, >0 if OK
877
-	 */
878
-	function deleteAttribute($dn, $info, $user)
879
-	{
880
-		global $conf;
881
-
882
-		dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".join(',',$info));
883
-
884
-		// Check parameters
885
-		if (! $this->connection)
886
-		{
887
-			$this->error="NotConnected";
888
-			return -2;
889
-		}
890
-		if (! $this->bind)
891
-		{
892
-			$this->error="NotConnected";
893
-			return -3;
894
-		}
895
-
896
-		// Encode to LDAP page code
897
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
898
-		foreach($info as $key => $val)
899
-		{
900
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
901
-		}
902
-
903
-		$this->dump($dn,$info);
904
-
905
-		//print_r($info);
906
-		$result=@ldap_mod_del($this->connection, $dn, $info);
907
-
908
-		if ($result)
909
-		{
910
-			dol_syslog(get_class($this)."::deleteAttribute successfull", LOG_DEBUG);
911
-			return 1;
912
-		}
913
-		else
914
-		{
915
-			$this->error=@ldap_error($this->connection);
916
-			dol_syslog(get_class($this)."::deleteAttribute failed: ".$this->error, LOG_ERR);
917
-			return -1;
918
-		}
919
-	}
920
-
921
-	/**
922
-	 *  Returns an array containing attributes and values for first record
923
-	 *
924
-	 *	@param	string	$dn			DN entry key
925
-	 *	@param	string	$filter		Filter
926
-	 *	@return	int|array			<0 or false if KO, array if OK
927
-	 */
928
-	function getAttribute($dn,$filter)
929
-	{
930
-		// Check parameters
931
-		if (! $this->connection)
932
-		{
933
-			$this->error="NotConnected";
934
-			return -2;
935
-		}
936
-		if (! $this->bind)
937
-		{
938
-			$this->error="NotConnected";
939
-			return -3;
940
-		}
941
-
942
-		$search = ldap_search($this->connection,$dn,$filter);
943
-
944
-		// Only one entry should ever be returned
945
-		$entry = ldap_first_entry($this->connection, $search);
946
-
947
-		if (!$entry)
948
-		{
949
-			$this->ldapErrorCode = -1;
950
-			$this->ldapErrorText = "Couldn't find entry";
951
-			return 0;  // Couldn't find entry...
952
-		}
953
-
954
-		// Get values
955
-		if (! $values = ldap_get_attributes($this->connection, $entry))
956
-		{
957
-			$this->ldapErrorCode = ldap_errno($this->connection);
958
-			$this->ldapErrorText = ldap_error($this->connection);
959
-			return 0; // No matching attributes
960
-		}
961
-
962
-		// Return an array containing the attributes.
963
-		return $values;
964
-	}
965
-
966
-	/**
967
-	 *  Returns an array containing values for an attribute and for first record matching filterrecord
968
-	 *
969
-	 * 	@param	string	$filterrecord		Record
970
-	 * 	@param	string	$attribute			Attributes
971
-	 * 	@return void
972
-	 */
973
-	function getAttributeValues($filterrecord,$attribute)
974
-	{
975
-		$attributes=array();
976
-		$attributes[0] = $attribute;
977
-
978
-		// We need to search for this user in order to get their entry.
979
-		$this->result = @ldap_search($this->connection,$this->people,$filterrecord,$attributes);
980
-
981
-		// Pourquoi cette ligne ?
982
-		//$info = ldap_get_entries($this->connection, $this->result);
983
-
984
-		// Only one entry should ever be returned (no user will have the same uid)
985
-		$entry = ldap_first_entry($this->connection, $this->result);
986
-
987
-		if (!$entry)
988
-		{
989
-			$this->ldapErrorCode = -1;
990
-			$this->ldapErrorText = "Couldn't find user";
991
-			return false;  // Couldn't find the user...
992
-		}
993
-
994
-		// Get values
995
-		if (! $values = @ldap_get_values($this->connection, $entry, $attribute))
996
-		{
997
-			$this->ldapErrorCode = ldap_errno($this->connection);
998
-			$this->ldapErrorText = ldap_error($this->connection);
999
-			return false; // No matching attributes
1000
-		}
1001
-
1002
-		// Return an array containing the attributes.
1003
-		return $values;
1004
-	}
1005
-
1006
-	/**
1007
-	 * 	Returns an array containing a details or list of LDAP record(s)
1008
-	 * 	ldapsearch -LLLx -hlocalhost -Dcn=admin,dc=parinux,dc=org -w password -b "ou=adherents,ou=people,dc=parinux,dc=org" userPassword
1009
-	 *
1010
-	 *	@param	string	$search			 	Value of fiel to search, '*' for all. Not used if $activefilter is set.
1011
-	 *	@param	string	$userDn			 	DN (Ex: ou=adherents,ou=people,dc=parinux,dc=org)
1012
-	 *	@param	string	$useridentifier 	Name of key field (Ex: uid)
1013
-	 *	@param	array	$attributeArray 	Array of fields required. Note this array must also contains field $useridentifier (Ex: sn,userPassword)
1014
-	 *	@param	int		$activefilter		'1' or 'user'=use field this->filter as filter instead of parameter $search, 'member'=use field this->filtermember as filter
1015
-	 *	@param	array	$attributeAsArray 	Array of fields wanted as an array not a string
1016
-	 *	@return	array						Array of [id_record][ldap_field]=value
1017
-	 */
1018
-	function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter=0, $attributeAsArray=array())
1019
-	{
1020
-		$fulllist=array();
1021
-
1022
-		dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".join(',',$attributeArray).") activefilter=".$activefilter);
1023
-
1024
-		// if the directory is AD, then bind first with the search user first
1025
-		if ($this->serverType == "activedirectory")
1026
-		{
1027
-			$this->bindauth($this->searchUser, $this->searchPassword);
1028
-			dol_syslog(get_class($this)."::bindauth serverType=activedirectory searchUser=".$this->searchUser);
1029
-		}
1030
-
1031
-		// Define filter
1032
-		if (! empty($activefilter))
1033
-		{
1034
-			if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter)
1035
-			{
1036
-				$filter = '('.$this->filter.')';
1037
-			}
1038
-			elseif (((string) $activefilter == 'member') && $this->filter)
1039
-			{
1040
-				$filter = '('.$this->filtermember.')';
1041
-			}
1042
-			else	// If this->filter is empty, make fiter on * (all)
1043
-			{
1044
-				$filter = '('.$useridentifier.'=*)';
1045
-			}
1046
-		}
1047
-		else
1048
-		{
1049
-			$filter = '('.$useridentifier.'='.$search.')';
1050
-		}
1051
-
1052
-		if (is_array($attributeArray))
1053
-		{
1054
-			// Return list with required fields
1055
-			$attributeArray=array_values($attributeArray);	// This is to force to have index reordered from 0 (not make ldap_search fails)
1056
-			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter. " attributeArray=(".join(',',$attributeArray).")");
1057
-			//var_dump($attributeArray);
1058
-			$this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1059
-		}
1060
-		else
1061
-		{
1062
-			// Return list with fields selected by default
1063
-			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter);
1064
-			$this->result = @ldap_search($this->connection, $userDn, $filter);
1065
-		}
1066
-		if (!$this->result)
1067
-		{
1068
-			$this->error = 'LDAP search failed: '.ldap_errno($this->connection)." ".ldap_error($this->connection);
1069
-			return -1;
1070
-		}
1071
-
1072
-		$info = @ldap_get_entries($this->connection, $this->result);
1073
-
1074
-		// Warning: Dans info, les noms d'attributs sont en minuscule meme si passe
1075
-		// a ldap_search en majuscule !!!
1076
-		//print_r($info);
1077
-
1078
-		for ($i = 0; $i < $info["count"]; $i++)
1079
-		{
1080
-			$recordid=$this->convToOutputCharset($info[$i][$useridentifier][0],$this->ldapcharset);
1081
-			if ($recordid)
1082
-			{
1083
-				//print "Found record with key $useridentifier=".$recordid."<br>\n";
1084
-				$fulllist[$recordid][$useridentifier]=$recordid;
1085
-
1086
-				// Add to the array for each attribute in my list
1087
-				$num = count($attributeArray);
1088
-				for ($j = 0; $j < $num; $j++)
1089
-				{
1090
-					$keyattributelower=strtolower($attributeArray[$j]);
1091
-					//print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]."<br>\n";
1092
-
1093
-					//permet de recuperer le SID avec Active Directory
1094
-					if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid")
1095
-					{
1096
-						$objectsid = $this->getObjectSid($recordid);
1097
-						$fulllist[$recordid][$attributeArray[$j]]    = $objectsid;
1098
-					}
1099
-					else
1100
-					{
1101
-						if(in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1102
-							$valueTab = array();
1103
-							foreach($info[$i][$keyattributelower] as $key => $value) {
1104
-								$valueTab[$key] = $this->convToOutputCharset($value,$this->ldapcharset);
1105
-							}
1106
-							$fulllist[$recordid][$attributeArray[$j]] = $valueTab;
1107
-						} else {
1108
-							$fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0],$this->ldapcharset);
1109
-						}
1110
-					}
1111
-				}
1112
-			}
1113
-		}
1114
-
1115
-		asort($fulllist);
1116
-		return $fulllist;
1117
-	}
1118
-
1119
-	/**
1120
-	 *  Converts a little-endian hex-number to one, that 'hexdec' can convert
1121
-	 *	Required by Active Directory
1122
-	 *
1123
-	 *	@param	string		$hex			Hex value
1124
-	 *	@return	string						Little endian
1125
-	 */
1126
-	function littleEndian($hex)
1127
-	{
1128
-		for ($x=dol_strlen($hex)-2; $x >= 0; $x=$x-2) {
1129
-			$result .= substr($hex,$x,2);
1130
-		}
1131
-		return $result;
1132
-	}
1133
-
1134
-
1135
-	/**
1136
-	 *  Recupere le SID de l'utilisateur
1137
-	 *	Required by Active Directory
1138
-	 *
1139
-	 * 	@param	string		$ldapUser		Login de l'utilisateur
1140
-	 * 	@return	string						Sid
1141
-	 */
1142
-	function getObjectSid($ldapUser)
1143
-	{
1144
-		$criteria =  '('.$this->getUserIdentifier().'='.$ldapUser.')';
1145
-		$justthese = array("objectsid");
1146
-
1147
-		// if the directory is AD, then bind first with the search user first
1148
-		if ($this->serverType == "activedirectory")
1149
-		{
1150
-			$this->bindauth($this->searchUser, $this->searchPassword);
1151
-		}
1152
-
1153
-		$i = 0;
1154
-		$searchDN = $this->people;
1155
-
1156
-		while ($i <= 2)
1157
-		{
1158
-			$ldapSearchResult = @ldap_search($this->connection, $searchDN, $criteria, $justthese);
1159
-
1160
-			if (!$ldapSearchResult)
1161
-			{
1162
-				$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1163
-				return -1;
1164
-			}
1165
-
1166
-			$entry = ldap_first_entry($this->connection, $ldapSearchResult);
1167
-
1168
-			if (!$entry)
1169
-			{
1170
-				// Si pas de resultat on cherche dans le domaine
1171
-				$searchDN = $this->domain;
1172
-				$i++;
1173
-			}
1174
-			else
1175
-			{
1176
-				$i++;
1177
-				$i++;
1178
-			}
1179
-		}
1180
-
1181
-		if ($entry)
1182
-		{
1183
-			$ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
1184
-			$SIDText = $this->binSIDtoText($ldapBinary[0]);
1185
-			return $SIDText;
1186
-		}
1187
-		else
1188
-		{
1189
-			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1190
-			return '?';
1191
-		}
1192
-	}
1193
-
1194
-	/**
1195
-	 * Returns the textual SID
1196
-	 * Indispensable pour Active Directory
1197
-	 *
1198
-	 * @param	string	$binsid		Binary SID
1199
-	 * @return	string				Textual SID
1200
-	 */
1201
-	function binSIDtoText($binsid)
1202
-	{
1203
-		$hex_sid=bin2hex($binsid);
1204
-		$rev = hexdec(substr($hex_sid,0,2));          // Get revision-part of SID
1205
-		$subcount = hexdec(substr($hex_sid,2,2));    // Get count of sub-auth entries
1206
-		$auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
1207
-		$result = "$rev-$auth";
1208
-		for ($x=0;$x < $subcount; $x++)
1209
-		{
1210
-			$result .= "-".hexdec($this->littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
1211
-		}
1212
-		return $result;
1213
-	}
1214
-
1215
-
1216
-	/**
1217
-	 * 	Fonction de recherche avec filtre
1218
-	 *	this->connection doit etre defini donc la methode bind ou bindauth doit avoir deja ete appelee
1219
-	 *	Ne pas utiliser pour recherche d'une liste donnee de proprietes
1220
-	 *	car conflit majuscule-minuscule. A n'utiliser que pour les pages
1221
-	 *	'Fiche LDAP' qui affiche champ lisibles par defaut.
1222
-	 *
1223
-	 * 	@param	string		$checkDn		DN de recherche (Ex: ou=users,cn=my-domain,cn=com)
1224
-	 * 	@param 	string		$filter			Search filter (ex: (sn=nom_personne) )
1225
-	 *	@return	array|int					Array with answers (key lowercased - value)
1226
-	 */
1227
-	function search($checkDn, $filter)
1228
-	{
1229
-		dol_syslog(get_class($this)."::search checkDn=".$checkDn." filter=".$filter);
1230
-
1231
-		$checkDn=$this->convFromOutputCharset($checkDn,$this->ldapcharset);
1232
-		$filter=$this->convFromOutputCharset($filter,$this->ldapcharset);
1233
-
1234
-		// if the directory is AD, then bind first with the search user first
1235
-		if ($this->serverType == "activedirectory") {
1236
-			$this->bindauth($this->searchUser, $this->searchPassword);
1237
-		}
1238
-
1239
-		$this->result = @ldap_search($this->connection, $checkDn, $filter);
1240
-
1241
-		$result = @ldap_get_entries($this->connection, $this->result);
1242
-		if (! $result)
1243
-		{
1244
-			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1245
-			return -1;
1246
-		}
1247
-		else
1248
-		{
1249
-			ldap_free_result($this->result);
1250
-			return $result;
1251
-		}
1252
-	}
1253
-
1254
-
1255
-	/**
1256
-	 * 		Load all attribute of a LDAP user
1257
-	 *
1258
-	 * 		@param	User	$user		User to search for. Not used if a filter is provided.
1259
-	 *      @param  string	$filter		Filter for search. Must start with &.
1260
-	 *                       	       	Examples: &(objectClass=inetOrgPerson) &(objectClass=user)(objectCategory=person) &(isMemberOf=cn=Sales,ou=Groups,dc=opencsi,dc=com)
1261
-	 *		@return	int					>0 if OK, <0 if KO
1262
-	 */
1263
-	function fetch($user,$filter)
1264
-	{
1265
-		// Perform the search and get the entry handles
1266
-
1267
-		// if the directory is AD, then bind first with the search user first
1268
-		if ($this->serverType == "activedirectory") {
1269
-			$this->bindauth($this->searchUser, $this->searchPassword);
1270
-		}
1271
-
1272
-		$searchDN = $this->people;    // TODO Why searching in people then domain ?
1273
-
1274
-		$result = '';
1275
-		$i=0;
1276
-		while ($i <= 2)
1277
-		{
1278
-			dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
1279
-			$this->result = @ldap_search($this->connection, $searchDN, $filter);
1280
-			if ($this->result)
1281
-			{
1282
-				$result = @ldap_get_entries($this->connection, $this->result);
1283
-				if ($result['count'] > 0) dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1284
-				else dol_syslog('Ldap::fetch search returns but found no records');
1285
-				//var_dump($result);exit;
1286
-			}
1287
-			else
1288
-			{
1289
-				$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1290
-				dol_syslog(get_class($this)."::fetch search fails");
1291
-				return -1;
1292
-			}
1293
-
1294
-			if (! $result)
1295
-			{
1296
-				// Si pas de resultat on cherche dans le domaine
1297
-				$searchDN = $this->domain;
1298
-				$i++;
1299
-			}
1300
-			else
1301
-			{
1302
-				break;
1303
-			}
1304
-		}
1305
-
1306
-		if (! $result)
1307
-		{
1308
-			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1309
-			return -1;
1310
-		}
1311
-		else
1312
-		{
1313
-			$this->name       = $this->convToOutputCharset($result[0][$this->attr_name][0],$this->ldapcharset);
1314
-			$this->firstname  = $this->convToOutputCharset($result[0][$this->attr_firstname][0],$this->ldapcharset);
1315
-			$this->login      = $this->convToOutputCharset($result[0][$this->attr_login][0],$this->ldapcharset);
1316
-			$this->phone      = $this->convToOutputCharset($result[0][$this->attr_phone][0],$this->ldapcharset);
1317
-			$this->skype      = $this->convToOutputCharset($result[0][$this->attr_skype][0],$this->ldapcharset);
1318
-			$this->fax        = $this->convToOutputCharset($result[0][$this->attr_fax][0],$this->ldapcharset);
1319
-			$this->mail       = $this->convToOutputCharset($result[0][$this->attr_mail][0],$this->ldapcharset);
1320
-			$this->mobile     = $this->convToOutputCharset($result[0][$this->attr_mobile][0],$this->ldapcharset);
1321
-
1322
-			$this->uacf       = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0],$this->ldapcharset));
1323
-			if (isset($result[0]["pwdlastset"][0]))	// If expiration on password exists
1324
-			{
1325
-				$this->pwdlastset = ($result[0]["pwdlastset"][0] != 0)?$this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0],$this->ldapcharset)):0;
1326
-			}
1327
-			else
1328
-			{
1329
-				$this->pwdlastset = -1;
1330
-			}
1331
-			if (!$this->name && !$this->login) $this->pwdlastset = -1;
1332
-			$this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0],$this->ldapcharset));
1333
-
1334
-			// FQDN domain
1335
-			$domain = str_replace('dc=','',$this->domain);
1336
-			$domain = str_replace(',','.',$domain);
1337
-			$this->domainFQDN = $domain;
1338
-
1339
-			// Set ldapUserDn (each user can have a different dn)
1340
-			//var_dump($result[0]);exit;
1341
-			$this->ldapUserDN=$result[0]['dn'];
1342
-
1343
-			ldap_free_result($this->result);
1344
-			return 1;
1345
-		}
1346
-	}
1347
-
1348
-
1349
-	// helper methods
1350
-
1351
-	/**
1352
-	 * 	Returns the correct user identifier to use, based on the ldap server type
1353
-	 *
1354
-	 *	@return	string 				Login
1355
-	 */
1356
-	function getUserIdentifier()
1357
-	{
1358
-		if ($this->serverType == "activedirectory") {
1359
-			return $this->attr_sambalogin;
1360
-		} else {
1361
-			return $this->attr_login;
1362
-		}
1363
-	}
1364
-
1365
-   /**
1366
-    * 	UserAccountControl Flgs to more human understandable form...
1367
-    *
1368
-    *	@param	string		$uacf		UACF
1369
-    *	@return	void
1370
-    */
1371
-	function parseUACF($uacf)
1372
-	{
1373
-		//All flags array
1374
-		$flags = array(
1375
-			"TRUSTED_TO_AUTH_FOR_DELEGATION"  =>    16777216,
1376
-			"PASSWORD_EXPIRED"                =>    8388608,
1377
-			"DONT_REQ_PREAUTH"                =>    4194304,
1378
-			"USE_DES_KEY_ONLY"                =>    2097152,
1379
-			"NOT_DELEGATED"                   =>    1048576,
1380
-			"TRUSTED_FOR_DELEGATION"          =>    524288,
1381
-			"SMARTCARD_REQUIRED"              =>    262144,
1382
-			"MNS_LOGON_ACCOUNT"               =>    131072,
1383
-			"DONT_EXPIRE_PASSWORD"            =>    65536,
1384
-			"SERVER_TRUST_ACCOUNT"            =>    8192,
1385
-			"WORKSTATION_TRUST_ACCOUNT"       =>    4096,
1386
-			"INTERDOMAIN_TRUST_ACCOUNT"       =>    2048,
1387
-			"NORMAL_ACCOUNT"                  =>    512,
1388
-			"TEMP_DUPLICATE_ACCOUNT"          =>    256,
1389
-			"ENCRYPTED_TEXT_PWD_ALLOWED"      =>    128,
1390
-			"PASSWD_CANT_CHANGE"              =>    64,
1391
-			"PASSWD_NOTREQD"                  =>    32,
1392
-			"LOCKOUT"                         =>    16,
1393
-			"HOMEDIR_REQUIRED"                =>    8,
1394
-			"ACCOUNTDISABLE"                  =>    2,
1395
-			"SCRIPT"                          =>    1
1396
-		);
1397
-
1398
-		//Parse flags to text
1399
-		$retval = array();
1400
-		while (list($flag, $val) = each($flags)) {
1401
-			if ($uacf >= $val) {
1402
-				$uacf -= $val;
1403
-				$retval[$val] = $flag;
1404
-			}
1405
-		}
1406
-
1407
-		//Return human friendly flags
1408
-		return($retval);
1409
-	}
1410
-
1411
-   /**
1412
-    * 	SamAccountType value to text
1413
-    *
1414
-    *	@param	string	$samtype	SamType
1415
-    *	@return	string				Sam string
1416
-    */
1417
-	function parseSAT($samtype)
1418
-	{
1419
-		$stypes = array(
1420
-			805306368    =>    "NORMAL_ACCOUNT",
1421
-			805306369    =>    "WORKSTATION_TRUST",
1422
-			805306370    =>    "INTERDOMAIN_TRUST",
1423
-			268435456    =>    "SECURITY_GLOBAL_GROUP",
1424
-			268435457    =>    "DISTRIBUTION_GROUP",
1425
-			536870912    =>    "SECURITY_LOCAL_GROUP",
1426
-			536870913    =>    "DISTRIBUTION_LOCAL_GROUP"
1427
-		);
1428
-
1429
-		$retval = "";
1430
-		while (list($sat, $val) = each($stypes)) {
1431
-			if ($samtype == $sat) {
1432
-				$retval = $val;
1433
-				break;
1434
-			}
1435
-		}
1436
-		if (empty($retval)) $retval = "UNKNOWN_TYPE_" . $samtype;
1437
-
1438
-		return($retval);
1439
-	}
670
+        $content='';
671
+
672
+        // Create file content
673
+        if (preg_match('/^ldap/',$this->server[0]))
674
+        {
675
+            $target="-H ".join(',',$this->server);
676
+        }
677
+        else
678
+        {
679
+            $target="-h ".join(',',$this->server)." -p ".$this->serverPort;
680
+        }
681
+        $content.="# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
682
+        $content.="# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
683
+        $content.="# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
684
+        if (in_array('localhost',$this->server)) $content.="# If commands fails to connect, try without -h and -p\n";
685
+        $content.="dn: ".$dn."\n";
686
+        foreach($info as $key => $value)
687
+        {
688
+            if (! is_array($value))
689
+            {
690
+                $content.="$key: $value\n";
691
+            }
692
+            else
693
+            {
694
+                foreach($value as $valuekey => $valuevalue)
695
+                {
696
+                    $content.="$key: $valuevalue\n";
697
+                }
698
+            }
699
+        }
700
+        return $content;
701
+    }
702
+
703
+    /**
704
+     * 	Dump a LDAP message to ldapinput.in file
705
+     *
706
+     *	@param	string		$dn			DN entry key
707
+     *	@param	array		$info		Attributes array
708
+     *	@return	int						<0 if KO, >0 if OK
709
+     */
710
+    function dump($dn, $info)
711
+    {
712
+        global $conf;
713
+
714
+        // Create content
715
+        $content=$this->dump_content($dn, $info);
716
+
717
+        //Create file
718
+        $result=dol_mkdir($conf->ldap->dir_temp);
719
+
720
+        $outputfile=$conf->ldap->dir_temp.'/ldapinput.in';
721
+        $fp=fopen($outputfile,"w");
722
+        if ($fp)
723
+        {
724
+            fputs($fp, $content);
725
+            fclose($fp);
726
+            if (! empty($conf->global->MAIN_UMASK))
727
+            @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
728
+            return 1;
729
+        }
730
+        else
731
+        {
732
+            return -1;
733
+        }
734
+    }
735
+
736
+    /**
737
+     * Ping a server before ldap_connect for avoid waiting
738
+     *
739
+     * @param string		$host		Server host or address
740
+     * @param int		$port		Server port (default 389)
741
+     * @param int		$timeout		Timeout in second (default 1s)
742
+     * @return boolean				true or false
743
+     */
744
+    function serverPing($host, $port=389, $timeout=1)
745
+    {
746
+        // Replace ldaps:// by ssl://
747
+        if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/',$host, $regs)) {
748
+            $host = 'ssl://'.$regs[1];
749
+        }
750
+        // Remove ldap://
751
+        if (preg_match('/^ldap:\/\/([^\/]+)\/?$/',$host, $regs)) {
752
+            $host = $regs[1];
753
+        }
754
+        $op = @fsockopen($host, $port, $errno, $errstr, $timeout);
755
+        if (!$op) return false; //DC is N/A
756
+        else {
757
+            fclose($op); //explicitly close open socket connection
758
+            return true; //DC is up & running, we can safely connect with ldap_connect
759
+        }
760
+    }
761
+
762
+
763
+    // Attribute methods -----------------------------------------------------
764
+
765
+    /**
766
+     * 	Add a LDAP attribute in entry
767
+     *	Ldap object connect and bind must have been done
768
+     *
769
+     *	@param	string		$dn			DN entry key
770
+     *	@param	array		$info		Attributes array
771
+     *	@param	User		$user		Objet user that create
772
+     *	@return	int						<0 if KO, >0 if OK
773
+     */
774
+    function addAttribute($dn, $info, $user)
775
+    {
776
+        global $conf;
777
+
778
+        dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".join(',',$info));
779
+
780
+        // Check parameters
781
+        if (! $this->connection)
782
+        {
783
+            $this->error="NotConnected";
784
+            return -2;
785
+        }
786
+        if (! $this->bind)
787
+        {
788
+            $this->error="NotConnected";
789
+            return -3;
790
+        }
791
+
792
+        // Encode to LDAP page code
793
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
794
+        foreach($info as $key => $val)
795
+        {
796
+            if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
797
+        }
798
+
799
+        $this->dump($dn,$info);
800
+
801
+        //print_r($info);
802
+        $result=@ldap_mod_add($this->connection, $dn, $info);
803
+
804
+        if ($result)
805
+        {
806
+            dol_syslog(get_class($this)."::add_attribute successfull", LOG_DEBUG);
807
+            return 1;
808
+        }
809
+        else
810
+        {
811
+            $this->error=@ldap_error($this->connection);
812
+            dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
813
+            return -1;
814
+        }
815
+    }
816
+
817
+    /**
818
+     * 	Update a LDAP attribute in entry
819
+     *	Ldap object connect and bind must have been done
820
+     *
821
+     *	@param	string		$dn			DN entry key
822
+     *	@param	array		$info		Attributes array
823
+     *	@param	User		$user		Objet user that create
824
+     *	@return	int						<0 if KO, >0 if OK
825
+     */
826
+    function updateAttribute($dn, $info, $user)
827
+    {
828
+        global $conf;
829
+
830
+        dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".join(',',$info));
831
+
832
+        // Check parameters
833
+        if (! $this->connection)
834
+        {
835
+            $this->error="NotConnected";
836
+            return -2;
837
+        }
838
+        if (! $this->bind)
839
+        {
840
+            $this->error="NotConnected";
841
+            return -3;
842
+        }
843
+
844
+        // Encode to LDAP page code
845
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
846
+        foreach($info as $key => $val)
847
+        {
848
+            if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
849
+        }
850
+
851
+        $this->dump($dn,$info);
852
+
853
+        //print_r($info);
854
+        $result=@ldap_mod_replace($this->connection, $dn, $info);
855
+
856
+        if ($result)
857
+        {
858
+            dol_syslog(get_class($this)."::updateAttribute successfull", LOG_DEBUG);
859
+            return 1;
860
+        }
861
+        else
862
+        {
863
+            $this->error=@ldap_error($this->connection);
864
+            dol_syslog(get_class($this)."::updateAttribute failed: ".$this->error, LOG_ERR);
865
+            return -1;
866
+        }
867
+    }
868
+
869
+    /**
870
+     * 	Delete a LDAP attribute in entry
871
+     *	Ldap object connect and bind must have been done
872
+     *
873
+     *	@param	string		$dn			DN entry key
874
+     *	@param	array		$info		Attributes array
875
+     *	@param	User		$user		Objet user that create
876
+     *	@return	int						<0 if KO, >0 if OK
877
+     */
878
+    function deleteAttribute($dn, $info, $user)
879
+    {
880
+        global $conf;
881
+
882
+        dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".join(',',$info));
883
+
884
+        // Check parameters
885
+        if (! $this->connection)
886
+        {
887
+            $this->error="NotConnected";
888
+            return -2;
889
+        }
890
+        if (! $this->bind)
891
+        {
892
+            $this->error="NotConnected";
893
+            return -3;
894
+        }
895
+
896
+        // Encode to LDAP page code
897
+        $dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
898
+        foreach($info as $key => $val)
899
+        {
900
+            if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
901
+        }
902
+
903
+        $this->dump($dn,$info);
904
+
905
+        //print_r($info);
906
+        $result=@ldap_mod_del($this->connection, $dn, $info);
907
+
908
+        if ($result)
909
+        {
910
+            dol_syslog(get_class($this)."::deleteAttribute successfull", LOG_DEBUG);
911
+            return 1;
912
+        }
913
+        else
914
+        {
915
+            $this->error=@ldap_error($this->connection);
916
+            dol_syslog(get_class($this)."::deleteAttribute failed: ".$this->error, LOG_ERR);
917
+            return -1;
918
+        }
919
+    }
920
+
921
+    /**
922
+     *  Returns an array containing attributes and values for first record
923
+     *
924
+     *	@param	string	$dn			DN entry key
925
+     *	@param	string	$filter		Filter
926
+     *	@return	int|array			<0 or false if KO, array if OK
927
+     */
928
+    function getAttribute($dn,$filter)
929
+    {
930
+        // Check parameters
931
+        if (! $this->connection)
932
+        {
933
+            $this->error="NotConnected";
934
+            return -2;
935
+        }
936
+        if (! $this->bind)
937
+        {
938
+            $this->error="NotConnected";
939
+            return -3;
940
+        }
941
+
942
+        $search = ldap_search($this->connection,$dn,$filter);
943
+
944
+        // Only one entry should ever be returned
945
+        $entry = ldap_first_entry($this->connection, $search);
946
+
947
+        if (!$entry)
948
+        {
949
+            $this->ldapErrorCode = -1;
950
+            $this->ldapErrorText = "Couldn't find entry";
951
+            return 0;  // Couldn't find entry...
952
+        }
953
+
954
+        // Get values
955
+        if (! $values = ldap_get_attributes($this->connection, $entry))
956
+        {
957
+            $this->ldapErrorCode = ldap_errno($this->connection);
958
+            $this->ldapErrorText = ldap_error($this->connection);
959
+            return 0; // No matching attributes
960
+        }
961
+
962
+        // Return an array containing the attributes.
963
+        return $values;
964
+    }
965
+
966
+    /**
967
+     *  Returns an array containing values for an attribute and for first record matching filterrecord
968
+     *
969
+     * 	@param	string	$filterrecord		Record
970
+     * 	@param	string	$attribute			Attributes
971
+     * 	@return void
972
+     */
973
+    function getAttributeValues($filterrecord,$attribute)
974
+    {
975
+        $attributes=array();
976
+        $attributes[0] = $attribute;
977
+
978
+        // We need to search for this user in order to get their entry.
979
+        $this->result = @ldap_search($this->connection,$this->people,$filterrecord,$attributes);
980
+
981
+        // Pourquoi cette ligne ?
982
+        //$info = ldap_get_entries($this->connection, $this->result);
983
+
984
+        // Only one entry should ever be returned (no user will have the same uid)
985
+        $entry = ldap_first_entry($this->connection, $this->result);
986
+
987
+        if (!$entry)
988
+        {
989
+            $this->ldapErrorCode = -1;
990
+            $this->ldapErrorText = "Couldn't find user";
991
+            return false;  // Couldn't find the user...
992
+        }
993
+
994
+        // Get values
995
+        if (! $values = @ldap_get_values($this->connection, $entry, $attribute))
996
+        {
997
+            $this->ldapErrorCode = ldap_errno($this->connection);
998
+            $this->ldapErrorText = ldap_error($this->connection);
999
+            return false; // No matching attributes
1000
+        }
1001
+
1002
+        // Return an array containing the attributes.
1003
+        return $values;
1004
+    }
1005
+
1006
+    /**
1007
+     * 	Returns an array containing a details or list of LDAP record(s)
1008
+     * 	ldapsearch -LLLx -hlocalhost -Dcn=admin,dc=parinux,dc=org -w password -b "ou=adherents,ou=people,dc=parinux,dc=org" userPassword
1009
+     *
1010
+     *	@param	string	$search			 	Value of fiel to search, '*' for all. Not used if $activefilter is set.
1011
+     *	@param	string	$userDn			 	DN (Ex: ou=adherents,ou=people,dc=parinux,dc=org)
1012
+     *	@param	string	$useridentifier 	Name of key field (Ex: uid)
1013
+     *	@param	array	$attributeArray 	Array of fields required. Note this array must also contains field $useridentifier (Ex: sn,userPassword)
1014
+     *	@param	int		$activefilter		'1' or 'user'=use field this->filter as filter instead of parameter $search, 'member'=use field this->filtermember as filter
1015
+     *	@param	array	$attributeAsArray 	Array of fields wanted as an array not a string
1016
+     *	@return	array						Array of [id_record][ldap_field]=value
1017
+     */
1018
+    function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter=0, $attributeAsArray=array())
1019
+    {
1020
+        $fulllist=array();
1021
+
1022
+        dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".join(',',$attributeArray).") activefilter=".$activefilter);
1023
+
1024
+        // if the directory is AD, then bind first with the search user first
1025
+        if ($this->serverType == "activedirectory")
1026
+        {
1027
+            $this->bindauth($this->searchUser, $this->searchPassword);
1028
+            dol_syslog(get_class($this)."::bindauth serverType=activedirectory searchUser=".$this->searchUser);
1029
+        }
1030
+
1031
+        // Define filter
1032
+        if (! empty($activefilter))
1033
+        {
1034
+            if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter)
1035
+            {
1036
+                $filter = '('.$this->filter.')';
1037
+            }
1038
+            elseif (((string) $activefilter == 'member') && $this->filter)
1039
+            {
1040
+                $filter = '('.$this->filtermember.')';
1041
+            }
1042
+            else	// If this->filter is empty, make fiter on * (all)
1043
+            {
1044
+                $filter = '('.$useridentifier.'=*)';
1045
+            }
1046
+        }
1047
+        else
1048
+        {
1049
+            $filter = '('.$useridentifier.'='.$search.')';
1050
+        }
1051
+
1052
+        if (is_array($attributeArray))
1053
+        {
1054
+            // Return list with required fields
1055
+            $attributeArray=array_values($attributeArray);	// This is to force to have index reordered from 0 (not make ldap_search fails)
1056
+            dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter. " attributeArray=(".join(',',$attributeArray).")");
1057
+            //var_dump($attributeArray);
1058
+            $this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1059
+        }
1060
+        else
1061
+        {
1062
+            // Return list with fields selected by default
1063
+            dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter);
1064
+            $this->result = @ldap_search($this->connection, $userDn, $filter);
1065
+        }
1066
+        if (!$this->result)
1067
+        {
1068
+            $this->error = 'LDAP search failed: '.ldap_errno($this->connection)." ".ldap_error($this->connection);
1069
+            return -1;
1070
+        }
1071
+
1072
+        $info = @ldap_get_entries($this->connection, $this->result);
1073
+
1074
+        // Warning: Dans info, les noms d'attributs sont en minuscule meme si passe
1075
+        // a ldap_search en majuscule !!!
1076
+        //print_r($info);
1077
+
1078
+        for ($i = 0; $i < $info["count"]; $i++)
1079
+        {
1080
+            $recordid=$this->convToOutputCharset($info[$i][$useridentifier][0],$this->ldapcharset);
1081
+            if ($recordid)
1082
+            {
1083
+                //print "Found record with key $useridentifier=".$recordid."<br>\n";
1084
+                $fulllist[$recordid][$useridentifier]=$recordid;
1085
+
1086
+                // Add to the array for each attribute in my list
1087
+                $num = count($attributeArray);
1088
+                for ($j = 0; $j < $num; $j++)
1089
+                {
1090
+                    $keyattributelower=strtolower($attributeArray[$j]);
1091
+                    //print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]."<br>\n";
1092
+
1093
+                    //permet de recuperer le SID avec Active Directory
1094
+                    if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid")
1095
+                    {
1096
+                        $objectsid = $this->getObjectSid($recordid);
1097
+                        $fulllist[$recordid][$attributeArray[$j]]    = $objectsid;
1098
+                    }
1099
+                    else
1100
+                    {
1101
+                        if(in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1102
+                            $valueTab = array();
1103
+                            foreach($info[$i][$keyattributelower] as $key => $value) {
1104
+                                $valueTab[$key] = $this->convToOutputCharset($value,$this->ldapcharset);
1105
+                            }
1106
+                            $fulllist[$recordid][$attributeArray[$j]] = $valueTab;
1107
+                        } else {
1108
+                            $fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0],$this->ldapcharset);
1109
+                        }
1110
+                    }
1111
+                }
1112
+            }
1113
+        }
1114
+
1115
+        asort($fulllist);
1116
+        return $fulllist;
1117
+    }
1118
+
1119
+    /**
1120
+     *  Converts a little-endian hex-number to one, that 'hexdec' can convert
1121
+     *	Required by Active Directory
1122
+     *
1123
+     *	@param	string		$hex			Hex value
1124
+     *	@return	string						Little endian
1125
+     */
1126
+    function littleEndian($hex)
1127
+    {
1128
+        for ($x=dol_strlen($hex)-2; $x >= 0; $x=$x-2) {
1129
+            $result .= substr($hex,$x,2);
1130
+        }
1131
+        return $result;
1132
+    }
1133
+
1134
+
1135
+    /**
1136
+     *  Recupere le SID de l'utilisateur
1137
+     *	Required by Active Directory
1138
+     *
1139
+     * 	@param	string		$ldapUser		Login de l'utilisateur
1140
+     * 	@return	string						Sid
1141
+     */
1142
+    function getObjectSid($ldapUser)
1143
+    {
1144
+        $criteria =  '('.$this->getUserIdentifier().'='.$ldapUser.')';
1145
+        $justthese = array("objectsid");
1146
+
1147
+        // if the directory is AD, then bind first with the search user first
1148
+        if ($this->serverType == "activedirectory")
1149
+        {
1150
+            $this->bindauth($this->searchUser, $this->searchPassword);
1151
+        }
1152
+
1153
+        $i = 0;
1154
+        $searchDN = $this->people;
1155
+
1156
+        while ($i <= 2)
1157
+        {
1158
+            $ldapSearchResult = @ldap_search($this->connection, $searchDN, $criteria, $justthese);
1159
+
1160
+            if (!$ldapSearchResult)
1161
+            {
1162
+                $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1163
+                return -1;
1164
+            }
1165
+
1166
+            $entry = ldap_first_entry($this->connection, $ldapSearchResult);
1167
+
1168
+            if (!$entry)
1169
+            {
1170
+                // Si pas de resultat on cherche dans le domaine
1171
+                $searchDN = $this->domain;
1172
+                $i++;
1173
+            }
1174
+            else
1175
+            {
1176
+                $i++;
1177
+                $i++;
1178
+            }
1179
+        }
1180
+
1181
+        if ($entry)
1182
+        {
1183
+            $ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
1184
+            $SIDText = $this->binSIDtoText($ldapBinary[0]);
1185
+            return $SIDText;
1186
+        }
1187
+        else
1188
+        {
1189
+            $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1190
+            return '?';
1191
+        }
1192
+    }
1193
+
1194
+    /**
1195
+     * Returns the textual SID
1196
+     * Indispensable pour Active Directory
1197
+     *
1198
+     * @param	string	$binsid		Binary SID
1199
+     * @return	string				Textual SID
1200
+     */
1201
+    function binSIDtoText($binsid)
1202
+    {
1203
+        $hex_sid=bin2hex($binsid);
1204
+        $rev = hexdec(substr($hex_sid,0,2));          // Get revision-part of SID
1205
+        $subcount = hexdec(substr($hex_sid,2,2));    // Get count of sub-auth entries
1206
+        $auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
1207
+        $result = "$rev-$auth";
1208
+        for ($x=0;$x < $subcount; $x++)
1209
+        {
1210
+            $result .= "-".hexdec($this->littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
1211
+        }
1212
+        return $result;
1213
+    }
1214
+
1215
+
1216
+    /**
1217
+     * 	Fonction de recherche avec filtre
1218
+     *	this->connection doit etre defini donc la methode bind ou bindauth doit avoir deja ete appelee
1219
+     *	Ne pas utiliser pour recherche d'une liste donnee de proprietes
1220
+     *	car conflit majuscule-minuscule. A n'utiliser que pour les pages
1221
+     *	'Fiche LDAP' qui affiche champ lisibles par defaut.
1222
+     *
1223
+     * 	@param	string		$checkDn		DN de recherche (Ex: ou=users,cn=my-domain,cn=com)
1224
+     * 	@param 	string		$filter			Search filter (ex: (sn=nom_personne) )
1225
+     *	@return	array|int					Array with answers (key lowercased - value)
1226
+     */
1227
+    function search($checkDn, $filter)
1228
+    {
1229
+        dol_syslog(get_class($this)."::search checkDn=".$checkDn." filter=".$filter);
1230
+
1231
+        $checkDn=$this->convFromOutputCharset($checkDn,$this->ldapcharset);
1232
+        $filter=$this->convFromOutputCharset($filter,$this->ldapcharset);
1233
+
1234
+        // if the directory is AD, then bind first with the search user first
1235
+        if ($this->serverType == "activedirectory") {
1236
+            $this->bindauth($this->searchUser, $this->searchPassword);
1237
+        }
1238
+
1239
+        $this->result = @ldap_search($this->connection, $checkDn, $filter);
1240
+
1241
+        $result = @ldap_get_entries($this->connection, $this->result);
1242
+        if (! $result)
1243
+        {
1244
+            $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1245
+            return -1;
1246
+        }
1247
+        else
1248
+        {
1249
+            ldap_free_result($this->result);
1250
+            return $result;
1251
+        }
1252
+    }
1253
+
1254
+
1255
+    /**
1256
+     * 		Load all attribute of a LDAP user
1257
+     *
1258
+     * 		@param	User	$user		User to search for. Not used if a filter is provided.
1259
+     *      @param  string	$filter		Filter for search. Must start with &.
1260
+     *                       	       	Examples: &(objectClass=inetOrgPerson) &(objectClass=user)(objectCategory=person) &(isMemberOf=cn=Sales,ou=Groups,dc=opencsi,dc=com)
1261
+     *		@return	int					>0 if OK, <0 if KO
1262
+     */
1263
+    function fetch($user,$filter)
1264
+    {
1265
+        // Perform the search and get the entry handles
1266
+
1267
+        // if the directory is AD, then bind first with the search user first
1268
+        if ($this->serverType == "activedirectory") {
1269
+            $this->bindauth($this->searchUser, $this->searchPassword);
1270
+        }
1271
+
1272
+        $searchDN = $this->people;    // TODO Why searching in people then domain ?
1273
+
1274
+        $result = '';
1275
+        $i=0;
1276
+        while ($i <= 2)
1277
+        {
1278
+            dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
1279
+            $this->result = @ldap_search($this->connection, $searchDN, $filter);
1280
+            if ($this->result)
1281
+            {
1282
+                $result = @ldap_get_entries($this->connection, $this->result);
1283
+                if ($result['count'] > 0) dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1284
+                else dol_syslog('Ldap::fetch search returns but found no records');
1285
+                //var_dump($result);exit;
1286
+            }
1287
+            else
1288
+            {
1289
+                $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1290
+                dol_syslog(get_class($this)."::fetch search fails");
1291
+                return -1;
1292
+            }
1293
+
1294
+            if (! $result)
1295
+            {
1296
+                // Si pas de resultat on cherche dans le domaine
1297
+                $searchDN = $this->domain;
1298
+                $i++;
1299
+            }
1300
+            else
1301
+            {
1302
+                break;
1303
+            }
1304
+        }
1305
+
1306
+        if (! $result)
1307
+        {
1308
+            $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1309
+            return -1;
1310
+        }
1311
+        else
1312
+        {
1313
+            $this->name       = $this->convToOutputCharset($result[0][$this->attr_name][0],$this->ldapcharset);
1314
+            $this->firstname  = $this->convToOutputCharset($result[0][$this->attr_firstname][0],$this->ldapcharset);
1315
+            $this->login      = $this->convToOutputCharset($result[0][$this->attr_login][0],$this->ldapcharset);
1316
+            $this->phone      = $this->convToOutputCharset($result[0][$this->attr_phone][0],$this->ldapcharset);
1317
+            $this->skype      = $this->convToOutputCharset($result[0][$this->attr_skype][0],$this->ldapcharset);
1318
+            $this->fax        = $this->convToOutputCharset($result[0][$this->attr_fax][0],$this->ldapcharset);
1319
+            $this->mail       = $this->convToOutputCharset($result[0][$this->attr_mail][0],$this->ldapcharset);
1320
+            $this->mobile     = $this->convToOutputCharset($result[0][$this->attr_mobile][0],$this->ldapcharset);
1321
+
1322
+            $this->uacf       = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0],$this->ldapcharset));
1323
+            if (isset($result[0]["pwdlastset"][0]))	// If expiration on password exists
1324
+            {
1325
+                $this->pwdlastset = ($result[0]["pwdlastset"][0] != 0)?$this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0],$this->ldapcharset)):0;
1326
+            }
1327
+            else
1328
+            {
1329
+                $this->pwdlastset = -1;
1330
+            }
1331
+            if (!$this->name && !$this->login) $this->pwdlastset = -1;
1332
+            $this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0],$this->ldapcharset));
1333
+
1334
+            // FQDN domain
1335
+            $domain = str_replace('dc=','',$this->domain);
1336
+            $domain = str_replace(',','.',$domain);
1337
+            $this->domainFQDN = $domain;
1338
+
1339
+            // Set ldapUserDn (each user can have a different dn)
1340
+            //var_dump($result[0]);exit;
1341
+            $this->ldapUserDN=$result[0]['dn'];
1342
+
1343
+            ldap_free_result($this->result);
1344
+            return 1;
1345
+        }
1346
+    }
1347
+
1348
+
1349
+    // helper methods
1350
+
1351
+    /**
1352
+     * 	Returns the correct user identifier to use, based on the ldap server type
1353
+     *
1354
+     *	@return	string 				Login
1355
+     */
1356
+    function getUserIdentifier()
1357
+    {
1358
+        if ($this->serverType == "activedirectory") {
1359
+            return $this->attr_sambalogin;
1360
+        } else {
1361
+            return $this->attr_login;
1362
+        }
1363
+    }
1364
+
1365
+    /**
1366
+     * 	UserAccountControl Flgs to more human understandable form...
1367
+     *
1368
+     *	@param	string		$uacf		UACF
1369
+     *	@return	void
1370
+     */
1371
+    function parseUACF($uacf)
1372
+    {
1373
+        //All flags array
1374
+        $flags = array(
1375
+            "TRUSTED_TO_AUTH_FOR_DELEGATION"  =>    16777216,
1376
+            "PASSWORD_EXPIRED"                =>    8388608,
1377
+            "DONT_REQ_PREAUTH"                =>    4194304,
1378
+            "USE_DES_KEY_ONLY"                =>    2097152,
1379
+            "NOT_DELEGATED"                   =>    1048576,
1380
+            "TRUSTED_FOR_DELEGATION"          =>    524288,
1381
+            "SMARTCARD_REQUIRED"              =>    262144,
1382
+            "MNS_LOGON_ACCOUNT"               =>    131072,
1383
+            "DONT_EXPIRE_PASSWORD"            =>    65536,
1384
+            "SERVER_TRUST_ACCOUNT"            =>    8192,
1385
+            "WORKSTATION_TRUST_ACCOUNT"       =>    4096,
1386
+            "INTERDOMAIN_TRUST_ACCOUNT"       =>    2048,
1387
+            "NORMAL_ACCOUNT"                  =>    512,
1388
+            "TEMP_DUPLICATE_ACCOUNT"          =>    256,
1389
+            "ENCRYPTED_TEXT_PWD_ALLOWED"      =>    128,
1390
+            "PASSWD_CANT_CHANGE"              =>    64,
1391
+            "PASSWD_NOTREQD"                  =>    32,
1392
+            "LOCKOUT"                         =>    16,
1393
+            "HOMEDIR_REQUIRED"                =>    8,
1394
+            "ACCOUNTDISABLE"                  =>    2,
1395
+            "SCRIPT"                          =>    1
1396
+        );
1397
+
1398
+        //Parse flags to text
1399
+        $retval = array();
1400
+        while (list($flag, $val) = each($flags)) {
1401
+            if ($uacf >= $val) {
1402
+                $uacf -= $val;
1403
+                $retval[$val] = $flag;
1404
+            }
1405
+        }
1406
+
1407
+        //Return human friendly flags
1408
+        return($retval);
1409
+    }
1410
+
1411
+    /**
1412
+     * 	SamAccountType value to text
1413
+     *
1414
+     *	@param	string	$samtype	SamType
1415
+     *	@return	string				Sam string
1416
+     */
1417
+    function parseSAT($samtype)
1418
+    {
1419
+        $stypes = array(
1420
+            805306368    =>    "NORMAL_ACCOUNT",
1421
+            805306369    =>    "WORKSTATION_TRUST",
1422
+            805306370    =>    "INTERDOMAIN_TRUST",
1423
+            268435456    =>    "SECURITY_GLOBAL_GROUP",
1424
+            268435457    =>    "DISTRIBUTION_GROUP",
1425
+            536870912    =>    "SECURITY_LOCAL_GROUP",
1426
+            536870913    =>    "DISTRIBUTION_LOCAL_GROUP"
1427
+        );
1428
+
1429
+        $retval = "";
1430
+        while (list($sat, $val) = each($stypes)) {
1431
+            if ($samtype == $sat) {
1432
+                $retval = $val;
1433
+                break;
1434
+            }
1435
+        }
1436
+        if (empty($retval)) $retval = "UNKNOWN_TYPE_" . $samtype;
1437
+
1438
+        return($retval);
1439
+    }
1440 1440
 
1441 1441
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1442
-	/**
1443
-	 *	Convertit le temps ActiveDirectory en Unix timestamp
1444
-	 *
1445
-	 *	@param	string	$value		AD time to convert
1446
-	 *	@return	integer				Unix timestamp
1447
-	 */
1448
-	function convert_time($value)
1449
-	{
1442
+    /**
1443
+     *	Convertit le temps ActiveDirectory en Unix timestamp
1444
+     *
1445
+     *	@param	string	$value		AD time to convert
1446
+     *	@return	integer				Unix timestamp
1447
+     */
1448
+    function convert_time($value)
1449
+    {
1450 1450
         // phpcs:enable
1451
-		$dateLargeInt=$value; // nano secondes depuis 1601 !!!!
1452
-		$secsAfterADEpoch = $dateLargeInt / (10000000); // secondes depuis le 1 jan 1601
1453
-		$ADToUnixConvertor=((1970-1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1454
-		$unixTimeStamp=intval($secsAfterADEpoch-$ADToUnixConvertor); // Unix time stamp
1455
-		return $unixTimeStamp;
1456
-	}
1457
-
1458
-
1459
-	/**
1460
-	 *  Convert a string into output/memory charset
1461
-	 *
1462
-	 *  @param	string	$str            String to convert
1463
-	 *  @param	string	$pagecodefrom	Page code of src string
1464
-	 *  @return string         			Converted string
1465
-	 */
1466
-	private function convToOutputCharset($str,$pagecodefrom='UTF-8')
1467
-	{
1468
-		global $conf;
1469
-		if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8')  $str=utf8_encode($str);
1470
-		if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1')  $str=utf8_decode($str);
1471
-		return $str;
1472
-	}
1473
-
1474
-	/**
1475
-	 *  Convert a string from output/memory charset
1476
-	 *
1477
-	 *  @param	string	$str            String to convert
1478
-	 *  @param	string	$pagecodeto		Page code for result string
1479
-	 *  @return string         			Converted string
1480
-	 */
1481
-	function convFromOutputCharset($str,$pagecodeto='UTF-8')
1482
-	{
1483
-		global $conf;
1484
-		if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str=utf8_decode($str);
1485
-		if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str=utf8_encode($str);
1486
-		return $str;
1487
-	}
1488
-
1489
-
1490
-	/**
1491
-	 *	Return available value of group GID
1492
-	 *
1493
-	 *	@param	string	$keygroup	Key of group
1494
-	 *	@return	int					gid number
1495
-	 */
1496
-	function getNextGroupGid($keygroup='LDAP_KEY_GROUPS')
1497
-	{
1498
-		global $conf;
1499
-
1500
-		if (empty($keygroup)) $keygroup='LDAP_KEY_GROUPS';
1501
-
1502
-		$search='('.$conf->global->$keygroup.'=*)';
1503
-		$result = $this->search($this->groups,$search);
1504
-		if ($result)
1505
-		{
1506
-			$c = $result['count'];
1507
-			$gids = array();
1508
-			for($i=0;$i<$c;$i++)
1509
-			{
1510
-				$gids[] = $result[$i]['gidnumber'][0];
1511
-			}
1512
-			rsort($gids);
1513
-
1514
-			return $gids[0]+1;
1515
-		}
1516
-
1517
-		return 0;
1518
-	}
1451
+        $dateLargeInt=$value; // nano secondes depuis 1601 !!!!
1452
+        $secsAfterADEpoch = $dateLargeInt / (10000000); // secondes depuis le 1 jan 1601
1453
+        $ADToUnixConvertor=((1970-1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1454
+        $unixTimeStamp=intval($secsAfterADEpoch-$ADToUnixConvertor); // Unix time stamp
1455
+        return $unixTimeStamp;
1456
+    }
1457
+
1458
+
1459
+    /**
1460
+     *  Convert a string into output/memory charset
1461
+     *
1462
+     *  @param	string	$str            String to convert
1463
+     *  @param	string	$pagecodefrom	Page code of src string
1464
+     *  @return string         			Converted string
1465
+     */
1466
+    private function convToOutputCharset($str,$pagecodefrom='UTF-8')
1467
+    {
1468
+        global $conf;
1469
+        if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8')  $str=utf8_encode($str);
1470
+        if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1')  $str=utf8_decode($str);
1471
+        return $str;
1472
+    }
1473
+
1474
+    /**
1475
+     *  Convert a string from output/memory charset
1476
+     *
1477
+     *  @param	string	$str            String to convert
1478
+     *  @param	string	$pagecodeto		Page code for result string
1479
+     *  @return string         			Converted string
1480
+     */
1481
+    function convFromOutputCharset($str,$pagecodeto='UTF-8')
1482
+    {
1483
+        global $conf;
1484
+        if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str=utf8_decode($str);
1485
+        if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str=utf8_encode($str);
1486
+        return $str;
1487
+    }
1488
+
1489
+
1490
+    /**
1491
+     *	Return available value of group GID
1492
+     *
1493
+     *	@param	string	$keygroup	Key of group
1494
+     *	@return	int					gid number
1495
+     */
1496
+    function getNextGroupGid($keygroup='LDAP_KEY_GROUPS')
1497
+    {
1498
+        global $conf;
1499
+
1500
+        if (empty($keygroup)) $keygroup='LDAP_KEY_GROUPS';
1501
+
1502
+        $search='('.$conf->global->$keygroup.'=*)';
1503
+        $result = $this->search($this->groups,$search);
1504
+        if ($result)
1505
+        {
1506
+            $c = $result['count'];
1507
+            $gids = array();
1508
+            for($i=0;$i<$c;$i++)
1509
+            {
1510
+                $gids[] = $result[$i]['gidnumber'][0];
1511
+            }
1512
+            rsort($gids);
1513
+
1514
+            return $gids[0]+1;
1515
+        }
1516
+
1517
+        return 0;
1518
+    }
1519 1519
 }
Please login to merge, or discard this patch.
Spacing   +221 added lines, -221 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
 	/**
33 33
 	 * @var string Error code (or message)
34 34
 	 */
35
-	public $error='';
35
+	public $error = '';
36 36
 
37 37
 	/**
38 38
 	 * @var string[]	Array of error strings
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 	/**
43 43
 	 * Tableau des serveurs (IP addresses ou nom d'hotes)
44 44
 	 */
45
-	var $server=array();
45
+	var $server = array();
46 46
 
47 47
 	/**
48 48
 	 * Base DN (e.g. "dc=foo,dc=com")
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 	var $uacf;
98 98
 	var $pwdlastset;
99 99
 
100
-	var $ldapcharset='UTF-8';	// LDAP should be UTF-8 encoded
100
+	var $ldapcharset = 'UTF-8'; // LDAP should be UTF-8 encoded
101 101
 
102 102
 
103 103
 	/**
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
 		global $conf;
119 119
 
120 120
 		// Server
121
-		if (! empty($conf->global->LDAP_SERVER_HOST))       $this->server[] = $conf->global->LDAP_SERVER_HOST;
122
-		if (! empty($conf->global->LDAP_SERVER_HOST_SLAVE)) $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
121
+		if (!empty($conf->global->LDAP_SERVER_HOST))       $this->server[] = $conf->global->LDAP_SERVER_HOST;
122
+		if (!empty($conf->global->LDAP_SERVER_HOST_SLAVE)) $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
123 123
 		$this->serverPort          = $conf->global->LDAP_SERVER_PORT;
124 124
 		$this->ldapProtocolVersion = $conf->global->LDAP_SERVER_PROTOCOLVERSION;
125 125
 		$this->dn                  = $conf->global->LDAP_SERVER_DN;
@@ -130,8 +130,8 @@  discard block
 block discarded – undo
130 130
 		$this->people              = $conf->global->LDAP_USER_DN;
131 131
 		$this->groups              = $conf->global->LDAP_GROUP_DN;
132 132
 
133
-		$this->filter              = $conf->global->LDAP_FILTER_CONNECTION;	// Filter on user
134
-		$this->filtermember        = $conf->global->LDAP_MEMBER_FILTER;		// Filter on member
133
+		$this->filter              = $conf->global->LDAP_FILTER_CONNECTION; // Filter on user
134
+		$this->filtermember        = $conf->global->LDAP_MEMBER_FILTER; // Filter on member
135 135
 
136 136
 		// Users
137 137
 		$this->attr_login      = $conf->global->LDAP_FIELD_LOGIN; //unix
@@ -162,22 +162,22 @@  discard block
 block discarded – undo
162 162
         // phpcs:enable
163 163
 		global $langs, $conf;
164 164
 
165
-		$connected=0;
166
-		$this->bind=0;
165
+		$connected = 0;
166
+		$this->bind = 0;
167 167
 
168 168
 		// Check parameters
169 169
 		if (count($this->server) == 0 || empty($this->server[0]))
170 170
 		{
171
-			$this->error='LDAP setup (file conf.php) is not complete';
171
+			$this->error = 'LDAP setup (file conf.php) is not complete';
172 172
 			dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
173 173
 			return -1;
174 174
 		}
175 175
 
176
-		if (! function_exists("ldap_connect"))
176
+		if (!function_exists("ldap_connect"))
177 177
 		{
178
-			$this->error='LDAPFunctionsNotAvailableOnPHP';
178
+			$this->error = 'LDAPFunctionsNotAvailableOnPHP';
179 179
 			dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
180
-			$return=-1;
180
+			$return = -1;
181 181
 		}
182 182
 
183 183
 		if (empty($this->error))
@@ -196,9 +196,9 @@  discard block
 block discarded – undo
196 196
 				if (is_resource($this->connection))
197 197
 				{
198 198
 					// Begin TLS if requested by the configuration
199
-					if (! empty($conf->global->LDAP_SERVER_USE_TLS))
199
+					if (!empty($conf->global->LDAP_SERVER_USE_TLS))
200 200
 					{
201
-						if (! ldap_start_tls($this->connection))
201
+						if (!ldap_start_tls($this->connection))
202 202
 						{
203 203
 							dol_syslog(get_class($this)."::connect_bind failed to start tls", LOG_WARNING);
204 204
 							$connected = 0;
@@ -213,18 +213,18 @@  discard block
 block discarded – undo
213 213
 
214 214
 					if ($this->serverType == "activedirectory")
215 215
 					{
216
-						$result=$this->setReferrals();
217
-						dol_syslog(get_class($this)."::connect_bind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./','*',$this->searchPassword),LOG_DEBUG);
218
-						$this->result=$this->bindauth($this->searchUser,$this->searchPassword);
216
+						$result = $this->setReferrals();
217
+						dol_syslog(get_class($this)."::connect_bind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
218
+						$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
219 219
 						if ($this->result)
220 220
 						{
221
-							$this->bind=$this->result;
222
-							$connected=2;
221
+							$this->bind = $this->result;
222
+							$connected = 2;
223 223
 							break;
224 224
 						}
225 225
 						else
226 226
 						{
227
-							$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
227
+							$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
228 228
 						}
229 229
 					}
230 230
 					else
@@ -232,51 +232,51 @@  discard block
 block discarded – undo
232 232
 						// Try in auth mode
233 233
 						if ($this->searchUser && $this->searchPassword)
234 234
 						{
235
-							dol_syslog(get_class($this)."::connect_bind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./','*',$this->searchPassword),LOG_DEBUG);
236
-							$this->result=$this->bindauth($this->searchUser,$this->searchPassword);
235
+							dol_syslog(get_class($this)."::connect_bind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
236
+							$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
237 237
 							if ($this->result)
238 238
 							{
239
-								$this->bind=$this->result;
240
-								$connected=2;
239
+								$this->bind = $this->result;
240
+								$connected = 2;
241 241
 								break;
242 242
 							}
243 243
 							else
244 244
 							{
245
-								$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
245
+								$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
246 246
 							}
247 247
 						}
248 248
 						// Try in anonymous
249
-						if (! $this->bind)
249
+						if (!$this->bind)
250 250
 						{
251
-							dol_syslog(get_class($this)."::connect_bind try bind on ".$host,LOG_DEBUG);
252
-							$result=$this->bind();
251
+							dol_syslog(get_class($this)."::connect_bind try bind on ".$host, LOG_DEBUG);
252
+							$result = $this->bind();
253 253
 							if ($result)
254 254
 							{
255
-								$this->bind=$this->result;
256
-								$connected=1;
255
+								$this->bind = $this->result;
256
+								$connected = 1;
257 257
 								break;
258 258
 							}
259 259
 							else
260 260
 							{
261
-								$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
261
+								$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
262 262
 							}
263 263
 						}
264 264
 					}
265 265
 				}
266 266
 
267
-				if (! $connected) $this->close();
267
+				if (!$connected) $this->close();
268 268
 			}
269 269
 		}
270 270
 
271 271
 		if ($connected)
272 272
 		{
273
-			$return=$connected;
273
+			$return = $connected;
274 274
 			dol_syslog(get_class($this)."::connect_bind return=".$return, LOG_DEBUG);
275 275
 		}
276 276
 		else
277 277
 		{
278
-			$this->error='Failed to connect to LDAP'.($this->error?': '.$this->error:'');
279
-			$return=-1;
278
+			$this->error = 'Failed to connect to LDAP'.($this->error ? ': '.$this->error : '');
279
+			$return = -1;
280 280
 			dol_syslog(get_class($this)."::connect_bind return=".$return.' - '.$this->error, LOG_WARNING);
281 281
 		}
282 282
 		return $return;
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 	 */
293 293
 	function close()
294 294
 	{
295
-		if ($this->connection && ! @ldap_close($this->connection))
295
+		if ($this->connection && !@ldap_close($this->connection))
296 296
 		{
297 297
 			return false;
298 298
 		}
@@ -310,11 +310,11 @@  discard block
 block discarded – undo
310 310
 	 */
311 311
 	function bind()
312 312
 	{
313
-		if (! $this->result=@ldap_bind($this->connection))
313
+		if (!$this->result = @ldap_bind($this->connection))
314 314
 		{
315 315
 			$this->ldapErrorCode = ldap_errno($this->connection);
316 316
 			$this->ldapErrorText = ldap_error($this->connection);
317
-			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
317
+			$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
318 318
 			return false;
319 319
 		}
320 320
 		else
@@ -333,13 +333,13 @@  discard block
 block discarded – undo
333 333
 	 * @param	string	$pass			Password
334 334
 	 * @return	boolean					true or false
335 335
 	 */
336
-	function bindauth($bindDn,$pass)
336
+	function bindauth($bindDn, $pass)
337 337
 	{
338
-		if (! $this->result = @ldap_bind($this->connection, $bindDn, $pass))
338
+		if (!$this->result = @ldap_bind($this->connection, $bindDn, $pass))
339 339
 		{
340 340
 			$this->ldapErrorCode = ldap_errno($this->connection);
341 341
 			$this->ldapErrorText = ldap_error($this->connection);
342
-			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
342
+			$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
343 343
 			return false;
344 344
 		}
345 345
 		else
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 	 */
356 356
 	function unbind()
357 357
 	{
358
-		if (!$this->result=@ldap_unbind($this->connection))
358
+		if (!$this->result = @ldap_unbind($this->connection))
359 359
 		{
360 360
 			return false;
361 361
 		} else {
@@ -414,31 +414,31 @@  discard block
 block discarded – undo
414 414
 	{
415 415
 		global $conf;
416 416
 
417
-		dol_syslog(get_class($this)."::add dn=".$dn." info=".join(',',$info));
417
+		dol_syslog(get_class($this)."::add dn=".$dn." info=".join(',', $info));
418 418
 
419 419
 		// Check parameters
420
-		if (! $this->connection)
420
+		if (!$this->connection)
421 421
 		{
422
-			$this->error="NotConnected";
422
+			$this->error = "NotConnected";
423 423
 			return -2;
424 424
 		}
425
-		if (! $this->bind)
425
+		if (!$this->bind)
426 426
 		{
427
-			$this->error="NotConnected";
427
+			$this->error = "NotConnected";
428 428
 			return -3;
429 429
 		}
430 430
 
431 431
 		// Encode to LDAP page code
432
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
433
-		foreach($info as $key => $val)
432
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
433
+		foreach ($info as $key => $val)
434 434
 		{
435
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
435
+			if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
436 436
 		}
437 437
 
438
-		$this->dump($dn,$info);
438
+		$this->dump($dn, $info);
439 439
 
440 440
 		//print_r($info);
441
-		$result=@ldap_add($this->connection, $dn, $info);
441
+		$result = @ldap_add($this->connection, $dn, $info);
442 442
 
443 443
 		if ($result)
444 444
 		{
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
 		{
450 450
 			$this->ldapErrorCode = @ldap_errno($this->connection);
451 451
 			$this->ldapErrorText = @ldap_error($this->connection);
452
-			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
452
+			$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
453 453
 			dol_syslog(get_class($this)."::add failed: ".$this->error, LOG_ERR);
454 454
 			return -1;
455 455
 		}
@@ -468,31 +468,31 @@  discard block
 block discarded – undo
468 468
 	{
469 469
 		global $conf;
470 470
 
471
-		dol_syslog(get_class($this)."::modify dn=".$dn." info=".join(',',$info));
471
+		dol_syslog(get_class($this)."::modify dn=".$dn." info=".join(',', $info));
472 472
 
473 473
 		// Check parameters
474
-		if (! $this->connection)
474
+		if (!$this->connection)
475 475
 		{
476
-			$this->error="NotConnected";
476
+			$this->error = "NotConnected";
477 477
 			return -2;
478 478
 		}
479
-		if (! $this->bind)
479
+		if (!$this->bind)
480 480
 		{
481
-			$this->error="NotConnected";
481
+			$this->error = "NotConnected";
482 482
 			return -3;
483 483
 		}
484 484
 
485 485
 		// Encode to LDAP page code
486
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
487
-		foreach($info as $key => $val)
486
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
487
+		foreach ($info as $key => $val)
488 488
 		{
489
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
489
+			if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
490 490
 		}
491 491
 
492
-		$this->dump($dn,$info);
492
+		$this->dump($dn, $info);
493 493
 
494 494
 		//print_r($info);
495
-		$result=@ldap_modify($this->connection, $dn, $info);
495
+		$result = @ldap_modify($this->connection, $dn, $info);
496 496
 
497 497
 		if ($result)
498 498
 		{
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 		}
502 502
 		else
503 503
 		{
504
-			$this->error=@ldap_error($this->connection);
504
+			$this->error = @ldap_error($this->connection);
505 505
 			dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
506 506
 			return -1;
507 507
 		}
@@ -522,27 +522,27 @@  discard block
 block discarded – undo
522 522
 	{
523 523
 		global $conf;
524 524
 
525
-		dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn?1:0));
525
+		dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn ? 1 : 0));
526 526
 
527 527
 		// Check parameters
528
-		if (! $this->connection)
528
+		if (!$this->connection)
529 529
 		{
530
-			$this->error="NotConnected";
530
+			$this->error = "NotConnected";
531 531
 			return -2;
532 532
 		}
533
-		if (! $this->bind)
533
+		if (!$this->bind)
534 534
 		{
535
-			$this->error="NotConnected";
535
+			$this->error = "NotConnected";
536 536
 			return -3;
537 537
 		}
538 538
 
539 539
 		// Encode to LDAP page code
540
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
541
-		$newrdn=$this->convFromOutputCharset($newrdn,$this->ldapcharset);
542
-		$newparent=$this->convFromOutputCharset($newparent,$this->ldapcharset);
540
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
541
+		$newrdn = $this->convFromOutputCharset($newrdn, $this->ldapcharset);
542
+		$newparent = $this->convFromOutputCharset($newparent, $this->ldapcharset);
543 543
 
544 544
 		//print_r($info);
545
-		$result=@ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
545
+		$result = @ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
546 546
 
547 547
 		if ($result)
548 548
 		{
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 		}
552 552
 		else
553 553
 		{
554
-			$this->error=@ldap_error($this->connection);
554
+			$this->error = @ldap_error($this->connection);
555 555
 			dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
556 556
 			return -1;
557 557
 		}
@@ -569,27 +569,27 @@  discard block
 block discarded – undo
569 569
 	 *	@param	string	$newparent	New parent (ou=xxx,dc=aaa,dc=bbb) (for ldap_rename)
570 570
 	 *	@return	int					<0 if KO, >0 if OK
571 571
 	 */
572
-	function update($dn, $info, $user, $olddn, $newrdn=false, $newparent=false)
572
+	function update($dn, $info, $user, $olddn, $newrdn = false, $newparent = false)
573 573
 	{
574 574
 		global $conf;
575 575
 
576 576
 		dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
577 577
 
578 578
 		// Check parameters
579
-		if (! $this->connection)
579
+		if (!$this->connection)
580 580
 		{
581
-			$this->error="NotConnected";
581
+			$this->error = "NotConnected";
582 582
 			return -2;
583 583
 		}
584
-		if (! $this->bind)
584
+		if (!$this->bind)
585 585
 		{
586
-			$this->error="NotConnected";
586
+			$this->error = "NotConnected";
587 587
 			return -3;
588 588
 		}
589 589
 
590
-		if (! $olddn || $olddn != $dn)
590
+		if (!$olddn || $olddn != $dn)
591 591
 		{
592
-			if (! empty($olddn) && ! empty($newrdn) && ! empty($newparent) && $conf->global->LDAP_SERVER_PROTOCOLVERSION === '3')
592
+			if (!empty($olddn) && !empty($newrdn) && !empty($newparent) && $conf->global->LDAP_SERVER_PROTOCOLVERSION === '3')
593 593
 			{
594 594
 				// This function currently only works with LDAPv3
595 595
 				$result = $this->rename($olddn, $newrdn, $newparent, $user, true);
@@ -598,19 +598,19 @@  discard block
 block discarded – undo
598 598
 			{
599 599
 				// If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
600 600
 				$result = $this->add($dn, $info, $user);
601
-				if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn);	// If add fails, we do not try to delete old one
601
+				if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn); // If add fails, we do not try to delete old one
602 602
 			}
603 603
 		}
604 604
 		else
605 605
 		{
606 606
 			//$result = $this->delete($olddn);
607
-			$result = $this->add($dn, $info, $user);	// If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
608
-			$result = $this->modify($dn, $info, $user);	// We use add/modify instead of delete/add when olddn is received
607
+			$result = $this->add($dn, $info, $user); // If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
608
+			$result = $this->modify($dn, $info, $user); // We use add/modify instead of delete/add when olddn is received
609 609
 		}
610 610
 		if ($result <= 0)
611 611
 		{
612 612
 			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection)." ".$this->error;
613
-			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
613
+			dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
614 614
 			//print_r($info);
615 615
 			return -1;
616 616
 		}
@@ -636,21 +636,21 @@  discard block
 block discarded – undo
636 636
 		dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
637 637
 
638 638
 		// Check parameters
639
-		if (! $this->connection)
639
+		if (!$this->connection)
640 640
 		{
641
-			$this->error="NotConnected";
641
+			$this->error = "NotConnected";
642 642
 			return -2;
643 643
 		}
644
-		if (! $this->bind)
644
+		if (!$this->bind)
645 645
 		{
646
-			$this->error="NotConnected";
646
+			$this->error = "NotConnected";
647 647
 			return -3;
648 648
 		}
649 649
 
650 650
 		// Encode to LDAP page code
651
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
651
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
652 652
 
653
-		$result=@ldap_delete($this->connection, $dn);
653
+		$result = @ldap_delete($this->connection, $dn);
654 654
 
655 655
 		if ($result) return 1;
656 656
 		return -1;
@@ -667,33 +667,33 @@  discard block
 block discarded – undo
667 667
 	function dump_content($dn, $info)
668 668
 	{
669 669
         // phpcs:enable
670
-		$content='';
670
+		$content = '';
671 671
 
672 672
 		// Create file content
673
-		if (preg_match('/^ldap/',$this->server[0]))
673
+		if (preg_match('/^ldap/', $this->server[0]))
674 674
 		{
675
-			$target="-H ".join(',',$this->server);
675
+			$target = "-H ".join(',', $this->server);
676 676
 		}
677 677
 		else
678 678
 		{
679
-			$target="-h ".join(',',$this->server)." -p ".$this->serverPort;
679
+			$target = "-h ".join(',', $this->server)." -p ".$this->serverPort;
680 680
 		}
681
-		$content.="# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
682
-		$content.="# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
683
-		$content.="# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
684
-		if (in_array('localhost',$this->server)) $content.="# If commands fails to connect, try without -h and -p\n";
685
-		$content.="dn: ".$dn."\n";
686
-		foreach($info as $key => $value)
681
+		$content .= "# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
682
+		$content .= "# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
683
+		$content .= "# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
684
+		if (in_array('localhost', $this->server)) $content .= "# If commands fails to connect, try without -h and -p\n";
685
+		$content .= "dn: ".$dn."\n";
686
+		foreach ($info as $key => $value)
687 687
 		{
688
-			if (! is_array($value))
688
+			if (!is_array($value))
689 689
 			{
690
-				$content.="$key: $value\n";
690
+				$content .= "$key: $value\n";
691 691
 			}
692 692
 			else
693 693
 			{
694
-				foreach($value as $valuekey => $valuevalue)
694
+				foreach ($value as $valuekey => $valuevalue)
695 695
 				{
696
-					$content.="$key: $valuevalue\n";
696
+					$content .= "$key: $valuevalue\n";
697 697
 				}
698 698
 			}
699 699
 		}
@@ -712,18 +712,18 @@  discard block
 block discarded – undo
712 712
 		global $conf;
713 713
 
714 714
 		// Create content
715
-		$content=$this->dump_content($dn, $info);
715
+		$content = $this->dump_content($dn, $info);
716 716
 
717 717
 		//Create file
718
-		$result=dol_mkdir($conf->ldap->dir_temp);
718
+		$result = dol_mkdir($conf->ldap->dir_temp);
719 719
 
720
-		$outputfile=$conf->ldap->dir_temp.'/ldapinput.in';
721
-		$fp=fopen($outputfile,"w");
720
+		$outputfile = $conf->ldap->dir_temp.'/ldapinput.in';
721
+		$fp = fopen($outputfile, "w");
722 722
 		if ($fp)
723 723
 		{
724 724
 			fputs($fp, $content);
725 725
 			fclose($fp);
726
-			if (! empty($conf->global->MAIN_UMASK))
726
+			if (!empty($conf->global->MAIN_UMASK))
727 727
 			@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
728 728
 			return 1;
729 729
 		}
@@ -741,14 +741,14 @@  discard block
 block discarded – undo
741 741
 	 * @param int		$timeout		Timeout in second (default 1s)
742 742
 	 * @return boolean				true or false
743 743
 	 */
744
-	function serverPing($host, $port=389, $timeout=1)
744
+	function serverPing($host, $port = 389, $timeout = 1)
745 745
 	{
746 746
 		// Replace ldaps:// by ssl://
747
-		if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/',$host, $regs)) {
747
+		if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/', $host, $regs)) {
748 748
 			$host = 'ssl://'.$regs[1];
749 749
 		}
750 750
 		// Remove ldap://
751
-		if (preg_match('/^ldap:\/\/([^\/]+)\/?$/',$host, $regs)) {
751
+		if (preg_match('/^ldap:\/\/([^\/]+)\/?$/', $host, $regs)) {
752 752
 			$host = $regs[1];
753 753
 		}
754 754
 		$op = @fsockopen($host, $port, $errno, $errstr, $timeout);
@@ -775,31 +775,31 @@  discard block
 block discarded – undo
775 775
 	{
776 776
 		global $conf;
777 777
 
778
-		dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".join(',',$info));
778
+		dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".join(',', $info));
779 779
 
780 780
 		// Check parameters
781
-		if (! $this->connection)
781
+		if (!$this->connection)
782 782
 		{
783
-			$this->error="NotConnected";
783
+			$this->error = "NotConnected";
784 784
 			return -2;
785 785
 		}
786
-		if (! $this->bind)
786
+		if (!$this->bind)
787 787
 		{
788
-			$this->error="NotConnected";
788
+			$this->error = "NotConnected";
789 789
 			return -3;
790 790
 		}
791 791
 
792 792
 		// Encode to LDAP page code
793
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
794
-		foreach($info as $key => $val)
793
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
794
+		foreach ($info as $key => $val)
795 795
 		{
796
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
796
+			if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
797 797
 		}
798 798
 
799
-		$this->dump($dn,$info);
799
+		$this->dump($dn, $info);
800 800
 
801 801
 		//print_r($info);
802
-		$result=@ldap_mod_add($this->connection, $dn, $info);
802
+		$result = @ldap_mod_add($this->connection, $dn, $info);
803 803
 
804 804
 		if ($result)
805 805
 		{
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 		}
809 809
 		else
810 810
 		{
811
-			$this->error=@ldap_error($this->connection);
811
+			$this->error = @ldap_error($this->connection);
812 812
 			dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
813 813
 			return -1;
814 814
 		}
@@ -827,31 +827,31 @@  discard block
 block discarded – undo
827 827
 	{
828 828
 		global $conf;
829 829
 
830
-		dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".join(',',$info));
830
+		dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".join(',', $info));
831 831
 
832 832
 		// Check parameters
833
-		if (! $this->connection)
833
+		if (!$this->connection)
834 834
 		{
835
-			$this->error="NotConnected";
835
+			$this->error = "NotConnected";
836 836
 			return -2;
837 837
 		}
838
-		if (! $this->bind)
838
+		if (!$this->bind)
839 839
 		{
840
-			$this->error="NotConnected";
840
+			$this->error = "NotConnected";
841 841
 			return -3;
842 842
 		}
843 843
 
844 844
 		// Encode to LDAP page code
845
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
846
-		foreach($info as $key => $val)
845
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
846
+		foreach ($info as $key => $val)
847 847
 		{
848
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
848
+			if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
849 849
 		}
850 850
 
851
-		$this->dump($dn,$info);
851
+		$this->dump($dn, $info);
852 852
 
853 853
 		//print_r($info);
854
-		$result=@ldap_mod_replace($this->connection, $dn, $info);
854
+		$result = @ldap_mod_replace($this->connection, $dn, $info);
855 855
 
856 856
 		if ($result)
857 857
 		{
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
 		}
861 861
 		else
862 862
 		{
863
-			$this->error=@ldap_error($this->connection);
863
+			$this->error = @ldap_error($this->connection);
864 864
 			dol_syslog(get_class($this)."::updateAttribute failed: ".$this->error, LOG_ERR);
865 865
 			return -1;
866 866
 		}
@@ -879,31 +879,31 @@  discard block
 block discarded – undo
879 879
 	{
880 880
 		global $conf;
881 881
 
882
-		dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".join(',',$info));
882
+		dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".join(',', $info));
883 883
 
884 884
 		// Check parameters
885
-		if (! $this->connection)
885
+		if (!$this->connection)
886 886
 		{
887
-			$this->error="NotConnected";
887
+			$this->error = "NotConnected";
888 888
 			return -2;
889 889
 		}
890
-		if (! $this->bind)
890
+		if (!$this->bind)
891 891
 		{
892
-			$this->error="NotConnected";
892
+			$this->error = "NotConnected";
893 893
 			return -3;
894 894
 		}
895 895
 
896 896
 		// Encode to LDAP page code
897
-		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
898
-		foreach($info as $key => $val)
897
+		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
898
+		foreach ($info as $key => $val)
899 899
 		{
900
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
900
+			if (!is_array($val)) $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
901 901
 		}
902 902
 
903
-		$this->dump($dn,$info);
903
+		$this->dump($dn, $info);
904 904
 
905 905
 		//print_r($info);
906
-		$result=@ldap_mod_del($this->connection, $dn, $info);
906
+		$result = @ldap_mod_del($this->connection, $dn, $info);
907 907
 
908 908
 		if ($result)
909 909
 		{
@@ -912,7 +912,7 @@  discard block
 block discarded – undo
912 912
 		}
913 913
 		else
914 914
 		{
915
-			$this->error=@ldap_error($this->connection);
915
+			$this->error = @ldap_error($this->connection);
916 916
 			dol_syslog(get_class($this)."::deleteAttribute failed: ".$this->error, LOG_ERR);
917 917
 			return -1;
918 918
 		}
@@ -925,21 +925,21 @@  discard block
 block discarded – undo
925 925
 	 *	@param	string	$filter		Filter
926 926
 	 *	@return	int|array			<0 or false if KO, array if OK
927 927
 	 */
928
-	function getAttribute($dn,$filter)
928
+	function getAttribute($dn, $filter)
929 929
 	{
930 930
 		// Check parameters
931
-		if (! $this->connection)
931
+		if (!$this->connection)
932 932
 		{
933
-			$this->error="NotConnected";
933
+			$this->error = "NotConnected";
934 934
 			return -2;
935 935
 		}
936
-		if (! $this->bind)
936
+		if (!$this->bind)
937 937
 		{
938
-			$this->error="NotConnected";
938
+			$this->error = "NotConnected";
939 939
 			return -3;
940 940
 		}
941 941
 
942
-		$search = ldap_search($this->connection,$dn,$filter);
942
+		$search = ldap_search($this->connection, $dn, $filter);
943 943
 
944 944
 		// Only one entry should ever be returned
945 945
 		$entry = ldap_first_entry($this->connection, $search);
@@ -948,11 +948,11 @@  discard block
 block discarded – undo
948 948
 		{
949 949
 			$this->ldapErrorCode = -1;
950 950
 			$this->ldapErrorText = "Couldn't find entry";
951
-			return 0;  // Couldn't find entry...
951
+			return 0; // Couldn't find entry...
952 952
 		}
953 953
 
954 954
 		// Get values
955
-		if (! $values = ldap_get_attributes($this->connection, $entry))
955
+		if (!$values = ldap_get_attributes($this->connection, $entry))
956 956
 		{
957 957
 			$this->ldapErrorCode = ldap_errno($this->connection);
958 958
 			$this->ldapErrorText = ldap_error($this->connection);
@@ -970,13 +970,13 @@  discard block
 block discarded – undo
970 970
 	 * 	@param	string	$attribute			Attributes
971 971
 	 * 	@return void
972 972
 	 */
973
-	function getAttributeValues($filterrecord,$attribute)
973
+	function getAttributeValues($filterrecord, $attribute)
974 974
 	{
975
-		$attributes=array();
975
+		$attributes = array();
976 976
 		$attributes[0] = $attribute;
977 977
 
978 978
 		// We need to search for this user in order to get their entry.
979
-		$this->result = @ldap_search($this->connection,$this->people,$filterrecord,$attributes);
979
+		$this->result = @ldap_search($this->connection, $this->people, $filterrecord, $attributes);
980 980
 
981 981
 		// Pourquoi cette ligne ?
982 982
 		//$info = ldap_get_entries($this->connection, $this->result);
@@ -988,11 +988,11 @@  discard block
 block discarded – undo
988 988
 		{
989 989
 			$this->ldapErrorCode = -1;
990 990
 			$this->ldapErrorText = "Couldn't find user";
991
-			return false;  // Couldn't find the user...
991
+			return false; // Couldn't find the user...
992 992
 		}
993 993
 
994 994
 		// Get values
995
-		if (! $values = @ldap_get_values($this->connection, $entry, $attribute))
995
+		if (!$values = @ldap_get_values($this->connection, $entry, $attribute))
996 996
 		{
997 997
 			$this->ldapErrorCode = ldap_errno($this->connection);
998 998
 			$this->ldapErrorText = ldap_error($this->connection);
@@ -1015,11 +1015,11 @@  discard block
 block discarded – undo
1015 1015
 	 *	@param	array	$attributeAsArray 	Array of fields wanted as an array not a string
1016 1016
 	 *	@return	array						Array of [id_record][ldap_field]=value
1017 1017
 	 */
1018
-	function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter=0, $attributeAsArray=array())
1018
+	function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter = 0, $attributeAsArray = array())
1019 1019
 	{
1020
-		$fulllist=array();
1020
+		$fulllist = array();
1021 1021
 
1022
-		dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".join(',',$attributeArray).") activefilter=".$activefilter);
1022
+		dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".join(',', $attributeArray).") activefilter=".$activefilter);
1023 1023
 
1024 1024
 		// if the directory is AD, then bind first with the search user first
1025 1025
 		if ($this->serverType == "activedirectory")
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
 		}
1030 1030
 
1031 1031
 		// Define filter
1032
-		if (! empty($activefilter))
1032
+		if (!empty($activefilter))
1033 1033
 		{
1034 1034
 			if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter)
1035 1035
 			{
@@ -1052,8 +1052,8 @@  discard block
 block discarded – undo
1052 1052
 		if (is_array($attributeArray))
1053 1053
 		{
1054 1054
 			// Return list with required fields
1055
-			$attributeArray=array_values($attributeArray);	// This is to force to have index reordered from 0 (not make ldap_search fails)
1056
-			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter. " attributeArray=(".join(',',$attributeArray).")");
1055
+			$attributeArray = array_values($attributeArray); // This is to force to have index reordered from 0 (not make ldap_search fails)
1056
+			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter." attributeArray=(".join(',', $attributeArray).")");
1057 1057
 			//var_dump($attributeArray);
1058 1058
 			$this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1059 1059
 		}
@@ -1077,35 +1077,35 @@  discard block
 block discarded – undo
1077 1077
 
1078 1078
 		for ($i = 0; $i < $info["count"]; $i++)
1079 1079
 		{
1080
-			$recordid=$this->convToOutputCharset($info[$i][$useridentifier][0],$this->ldapcharset);
1080
+			$recordid = $this->convToOutputCharset($info[$i][$useridentifier][0], $this->ldapcharset);
1081 1081
 			if ($recordid)
1082 1082
 			{
1083 1083
 				//print "Found record with key $useridentifier=".$recordid."<br>\n";
1084
-				$fulllist[$recordid][$useridentifier]=$recordid;
1084
+				$fulllist[$recordid][$useridentifier] = $recordid;
1085 1085
 
1086 1086
 				// Add to the array for each attribute in my list
1087 1087
 				$num = count($attributeArray);
1088 1088
 				for ($j = 0; $j < $num; $j++)
1089 1089
 				{
1090
-					$keyattributelower=strtolower($attributeArray[$j]);
1090
+					$keyattributelower = strtolower($attributeArray[$j]);
1091 1091
 					//print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]."<br>\n";
1092 1092
 
1093 1093
 					//permet de recuperer le SID avec Active Directory
1094 1094
 					if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid")
1095 1095
 					{
1096 1096
 						$objectsid = $this->getObjectSid($recordid);
1097
-						$fulllist[$recordid][$attributeArray[$j]]    = $objectsid;
1097
+						$fulllist[$recordid][$attributeArray[$j]] = $objectsid;
1098 1098
 					}
1099 1099
 					else
1100 1100
 					{
1101
-						if(in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1101
+						if (in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1102 1102
 							$valueTab = array();
1103
-							foreach($info[$i][$keyattributelower] as $key => $value) {
1104
-								$valueTab[$key] = $this->convToOutputCharset($value,$this->ldapcharset);
1103
+							foreach ($info[$i][$keyattributelower] as $key => $value) {
1104
+								$valueTab[$key] = $this->convToOutputCharset($value, $this->ldapcharset);
1105 1105
 							}
1106 1106
 							$fulllist[$recordid][$attributeArray[$j]] = $valueTab;
1107 1107
 						} else {
1108
-							$fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0],$this->ldapcharset);
1108
+							$fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0], $this->ldapcharset);
1109 1109
 						}
1110 1110
 					}
1111 1111
 				}
@@ -1125,8 +1125,8 @@  discard block
 block discarded – undo
1125 1125
 	 */
1126 1126
 	function littleEndian($hex)
1127 1127
 	{
1128
-		for ($x=dol_strlen($hex)-2; $x >= 0; $x=$x-2) {
1129
-			$result .= substr($hex,$x,2);
1128
+		for ($x = dol_strlen($hex) - 2; $x >= 0; $x = $x - 2) {
1129
+			$result .= substr($hex, $x, 2);
1130 1130
 		}
1131 1131
 		return $result;
1132 1132
 	}
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
 	 */
1142 1142
 	function getObjectSid($ldapUser)
1143 1143
 	{
1144
-		$criteria =  '('.$this->getUserIdentifier().'='.$ldapUser.')';
1144
+		$criteria = '('.$this->getUserIdentifier().'='.$ldapUser.')';
1145 1145
 		$justthese = array("objectsid");
1146 1146
 
1147 1147
 		// if the directory is AD, then bind first with the search user first
@@ -1200,14 +1200,14 @@  discard block
 block discarded – undo
1200 1200
 	 */
1201 1201
 	function binSIDtoText($binsid)
1202 1202
 	{
1203
-		$hex_sid=bin2hex($binsid);
1204
-		$rev = hexdec(substr($hex_sid,0,2));          // Get revision-part of SID
1205
-		$subcount = hexdec(substr($hex_sid,2,2));    // Get count of sub-auth entries
1206
-		$auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
1203
+		$hex_sid = bin2hex($binsid);
1204
+		$rev = hexdec(substr($hex_sid, 0, 2)); // Get revision-part of SID
1205
+		$subcount = hexdec(substr($hex_sid, 2, 2)); // Get count of sub-auth entries
1206
+		$auth = hexdec(substr($hex_sid, 4, 12)); // SECURITY_NT_AUTHORITY
1207 1207
 		$result = "$rev-$auth";
1208
-		for ($x=0;$x < $subcount; $x++)
1208
+		for ($x = 0; $x < $subcount; $x++)
1209 1209
 		{
1210
-			$result .= "-".hexdec($this->littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
1210
+			$result .= "-".hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8))); // get all SECURITY_NT_AUTHORITY
1211 1211
 		}
1212 1212
 		return $result;
1213 1213
 	}
@@ -1228,8 +1228,8 @@  discard block
 block discarded – undo
1228 1228
 	{
1229 1229
 		dol_syslog(get_class($this)."::search checkDn=".$checkDn." filter=".$filter);
1230 1230
 
1231
-		$checkDn=$this->convFromOutputCharset($checkDn,$this->ldapcharset);
1232
-		$filter=$this->convFromOutputCharset($filter,$this->ldapcharset);
1231
+		$checkDn = $this->convFromOutputCharset($checkDn, $this->ldapcharset);
1232
+		$filter = $this->convFromOutputCharset($filter, $this->ldapcharset);
1233 1233
 
1234 1234
 		// if the directory is AD, then bind first with the search user first
1235 1235
 		if ($this->serverType == "activedirectory") {
@@ -1239,7 +1239,7 @@  discard block
 block discarded – undo
1239 1239
 		$this->result = @ldap_search($this->connection, $checkDn, $filter);
1240 1240
 
1241 1241
 		$result = @ldap_get_entries($this->connection, $this->result);
1242
-		if (! $result)
1242
+		if (!$result)
1243 1243
 		{
1244 1244
 			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1245 1245
 			return -1;
@@ -1260,7 +1260,7 @@  discard block
 block discarded – undo
1260 1260
 	 *                       	       	Examples: &(objectClass=inetOrgPerson) &(objectClass=user)(objectCategory=person) &(isMemberOf=cn=Sales,ou=Groups,dc=opencsi,dc=com)
1261 1261
 	 *		@return	int					>0 if OK, <0 if KO
1262 1262
 	 */
1263
-	function fetch($user,$filter)
1263
+	function fetch($user, $filter)
1264 1264
 	{
1265 1265
 		// Perform the search and get the entry handles
1266 1266
 
@@ -1269,10 +1269,10 @@  discard block
 block discarded – undo
1269 1269
 			$this->bindauth($this->searchUser, $this->searchPassword);
1270 1270
 		}
1271 1271
 
1272
-		$searchDN = $this->people;    // TODO Why searching in people then domain ?
1272
+		$searchDN = $this->people; // TODO Why searching in people then domain ?
1273 1273
 
1274 1274
 		$result = '';
1275
-		$i=0;
1275
+		$i = 0;
1276 1276
 		while ($i <= 2)
1277 1277
 		{
1278 1278
 			dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
@@ -1291,7 +1291,7 @@  discard block
 block discarded – undo
1291 1291
 				return -1;
1292 1292
 			}
1293 1293
 
1294
-			if (! $result)
1294
+			if (!$result)
1295 1295
 			{
1296 1296
 				// Si pas de resultat on cherche dans le domaine
1297 1297
 				$searchDN = $this->domain;
@@ -1303,42 +1303,42 @@  discard block
 block discarded – undo
1303 1303
 			}
1304 1304
 		}
1305 1305
 
1306
-		if (! $result)
1306
+		if (!$result)
1307 1307
 		{
1308 1308
 			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1309 1309
 			return -1;
1310 1310
 		}
1311 1311
 		else
1312 1312
 		{
1313
-			$this->name       = $this->convToOutputCharset($result[0][$this->attr_name][0],$this->ldapcharset);
1314
-			$this->firstname  = $this->convToOutputCharset($result[0][$this->attr_firstname][0],$this->ldapcharset);
1315
-			$this->login      = $this->convToOutputCharset($result[0][$this->attr_login][0],$this->ldapcharset);
1316
-			$this->phone      = $this->convToOutputCharset($result[0][$this->attr_phone][0],$this->ldapcharset);
1317
-			$this->skype      = $this->convToOutputCharset($result[0][$this->attr_skype][0],$this->ldapcharset);
1318
-			$this->fax        = $this->convToOutputCharset($result[0][$this->attr_fax][0],$this->ldapcharset);
1319
-			$this->mail       = $this->convToOutputCharset($result[0][$this->attr_mail][0],$this->ldapcharset);
1320
-			$this->mobile     = $this->convToOutputCharset($result[0][$this->attr_mobile][0],$this->ldapcharset);
1313
+			$this->name       = $this->convToOutputCharset($result[0][$this->attr_name][0], $this->ldapcharset);
1314
+			$this->firstname  = $this->convToOutputCharset($result[0][$this->attr_firstname][0], $this->ldapcharset);
1315
+			$this->login      = $this->convToOutputCharset($result[0][$this->attr_login][0], $this->ldapcharset);
1316
+			$this->phone      = $this->convToOutputCharset($result[0][$this->attr_phone][0], $this->ldapcharset);
1317
+			$this->skype      = $this->convToOutputCharset($result[0][$this->attr_skype][0], $this->ldapcharset);
1318
+			$this->fax        = $this->convToOutputCharset($result[0][$this->attr_fax][0], $this->ldapcharset);
1319
+			$this->mail       = $this->convToOutputCharset($result[0][$this->attr_mail][0], $this->ldapcharset);
1320
+			$this->mobile     = $this->convToOutputCharset($result[0][$this->attr_mobile][0], $this->ldapcharset);
1321 1321
 
1322
-			$this->uacf       = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0],$this->ldapcharset));
1322
+			$this->uacf       = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0], $this->ldapcharset));
1323 1323
 			if (isset($result[0]["pwdlastset"][0]))	// If expiration on password exists
1324 1324
 			{
1325
-				$this->pwdlastset = ($result[0]["pwdlastset"][0] != 0)?$this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0],$this->ldapcharset)):0;
1325
+				$this->pwdlastset = ($result[0]["pwdlastset"][0] != 0) ? $this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0], $this->ldapcharset)) : 0;
1326 1326
 			}
1327 1327
 			else
1328 1328
 			{
1329 1329
 				$this->pwdlastset = -1;
1330 1330
 			}
1331 1331
 			if (!$this->name && !$this->login) $this->pwdlastset = -1;
1332
-			$this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0],$this->ldapcharset));
1332
+			$this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0], $this->ldapcharset));
1333 1333
 
1334 1334
 			// FQDN domain
1335
-			$domain = str_replace('dc=','',$this->domain);
1336
-			$domain = str_replace(',','.',$domain);
1335
+			$domain = str_replace('dc=', '', $this->domain);
1336
+			$domain = str_replace(',', '.', $domain);
1337 1337
 			$this->domainFQDN = $domain;
1338 1338
 
1339 1339
 			// Set ldapUserDn (each user can have a different dn)
1340 1340
 			//var_dump($result[0]);exit;
1341
-			$this->ldapUserDN=$result[0]['dn'];
1341
+			$this->ldapUserDN = $result[0]['dn'];
1342 1342
 
1343 1343
 			ldap_free_result($this->result);
1344 1344
 			return 1;
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
 				break;
1434 1434
 			}
1435 1435
 		}
1436
-		if (empty($retval)) $retval = "UNKNOWN_TYPE_" . $samtype;
1436
+		if (empty($retval)) $retval = "UNKNOWN_TYPE_".$samtype;
1437 1437
 
1438 1438
 		return($retval);
1439 1439
 	}
@@ -1448,10 +1448,10 @@  discard block
 block discarded – undo
1448 1448
 	function convert_time($value)
1449 1449
 	{
1450 1450
         // phpcs:enable
1451
-		$dateLargeInt=$value; // nano secondes depuis 1601 !!!!
1451
+		$dateLargeInt = $value; // nano secondes depuis 1601 !!!!
1452 1452
 		$secsAfterADEpoch = $dateLargeInt / (10000000); // secondes depuis le 1 jan 1601
1453
-		$ADToUnixConvertor=((1970-1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1454
-		$unixTimeStamp=intval($secsAfterADEpoch-$ADToUnixConvertor); // Unix time stamp
1453
+		$ADToUnixConvertor = ((1970 - 1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1454
+		$unixTimeStamp = intval($secsAfterADEpoch - $ADToUnixConvertor); // Unix time stamp
1455 1455
 		return $unixTimeStamp;
1456 1456
 	}
1457 1457
 
@@ -1463,11 +1463,11 @@  discard block
 block discarded – undo
1463 1463
 	 *  @param	string	$pagecodefrom	Page code of src string
1464 1464
 	 *  @return string         			Converted string
1465 1465
 	 */
1466
-	private function convToOutputCharset($str,$pagecodefrom='UTF-8')
1466
+	private function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
1467 1467
 	{
1468 1468
 		global $conf;
1469
-		if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8')  $str=utf8_encode($str);
1470
-		if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1')  $str=utf8_decode($str);
1469
+		if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8')  $str = utf8_encode($str);
1470
+		if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1')  $str = utf8_decode($str);
1471 1471
 		return $str;
1472 1472
 	}
1473 1473
 
@@ -1478,11 +1478,11 @@  discard block
 block discarded – undo
1478 1478
 	 *  @param	string	$pagecodeto		Page code for result string
1479 1479
 	 *  @return string         			Converted string
1480 1480
 	 */
1481
-	function convFromOutputCharset($str,$pagecodeto='UTF-8')
1481
+	function convFromOutputCharset($str, $pagecodeto = 'UTF-8')
1482 1482
 	{
1483 1483
 		global $conf;
1484
-		if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str=utf8_decode($str);
1485
-		if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str=utf8_encode($str);
1484
+		if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str = utf8_decode($str);
1485
+		if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str = utf8_encode($str);
1486 1486
 		return $str;
1487 1487
 	}
1488 1488
 
@@ -1493,25 +1493,25 @@  discard block
 block discarded – undo
1493 1493
 	 *	@param	string	$keygroup	Key of group
1494 1494
 	 *	@return	int					gid number
1495 1495
 	 */
1496
-	function getNextGroupGid($keygroup='LDAP_KEY_GROUPS')
1496
+	function getNextGroupGid($keygroup = 'LDAP_KEY_GROUPS')
1497 1497
 	{
1498 1498
 		global $conf;
1499 1499
 
1500
-		if (empty($keygroup)) $keygroup='LDAP_KEY_GROUPS';
1500
+		if (empty($keygroup)) $keygroup = 'LDAP_KEY_GROUPS';
1501 1501
 
1502
-		$search='('.$conf->global->$keygroup.'=*)';
1503
-		$result = $this->search($this->groups,$search);
1502
+		$search = '('.$conf->global->$keygroup.'=*)';
1503
+		$result = $this->search($this->groups, $search);
1504 1504
 		if ($result)
1505 1505
 		{
1506 1506
 			$c = $result['count'];
1507 1507
 			$gids = array();
1508
-			for($i=0;$i<$c;$i++)
1508
+			for ($i = 0; $i < $c; $i++)
1509 1509
 			{
1510 1510
 				$gids[] = $result[$i]['gidnumber'][0];
1511 1511
 			}
1512 1512
 			rsort($gids);
1513 1513
 
1514
-			return $gids[0]+1;
1514
+			return $gids[0] + 1;
1515 1515
 		}
1516 1516
 
1517 1517
 		return 0;
Please login to merge, or discard this patch.
Braces   +109 added lines, -90 removed lines patch added patch discarded remove patch
@@ -118,8 +118,12 @@  discard block
 block discarded – undo
118 118
 		global $conf;
119 119
 
120 120
 		// Server
121
-		if (! empty($conf->global->LDAP_SERVER_HOST))       $this->server[] = $conf->global->LDAP_SERVER_HOST;
122
-		if (! empty($conf->global->LDAP_SERVER_HOST_SLAVE)) $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
121
+		if (! empty($conf->global->LDAP_SERVER_HOST)) {
122
+		    $this->server[] = $conf->global->LDAP_SERVER_HOST;
123
+		}
124
+		if (! empty($conf->global->LDAP_SERVER_HOST_SLAVE)) {
125
+		    $this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
126
+		}
123 127
 		$this->serverPort          = $conf->global->LDAP_SERVER_PORT;
124 128
 		$this->ldapProtocolVersion = $conf->global->LDAP_SERVER_PROTOCOLVERSION;
125 129
 		$this->dn                  = $conf->global->LDAP_SERVER_DN;
@@ -185,13 +189,18 @@  discard block
 block discarded – undo
185 189
 			// Loop on each ldap server
186 190
 			foreach ($this->server as $key => $host)
187 191
 			{
188
-				if ($connected) break;
189
-				if (empty($host)) continue;
192
+				if ($connected) {
193
+				    break;
194
+				}
195
+				if (empty($host)) {
196
+				    continue;
197
+				}
190 198
 
191 199
 				if ($this->serverPing($host, $this->serverPort) === true) {
192 200
 					$this->connection = ldap_connect($host, $this->serverPort);
201
+				} else {
202
+				    continue;
193 203
 				}
194
-				else continue;
195 204
 
196 205
 				if (is_resource($this->connection))
197 206
 				{
@@ -221,13 +230,11 @@  discard block
 block discarded – undo
221 230
 							$this->bind=$this->result;
222 231
 							$connected=2;
223 232
 							break;
224
-						}
225
-						else
233
+						} else
226 234
 						{
227 235
 							$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
228 236
 						}
229
-					}
230
-					else
237
+					} else
231 238
 					{
232 239
 						// Try in auth mode
233 240
 						if ($this->searchUser && $this->searchPassword)
@@ -239,8 +246,7 @@  discard block
 block discarded – undo
239 246
 								$this->bind=$this->result;
240 247
 								$connected=2;
241 248
 								break;
242
-							}
243
-							else
249
+							} else
244 250
 							{
245 251
 								$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
246 252
 							}
@@ -255,8 +261,7 @@  discard block
 block discarded – undo
255 261
 								$this->bind=$this->result;
256 262
 								$connected=1;
257 263
 								break;
258
-							}
259
-							else
264
+							} else
260 265
 							{
261 266
 								$this->error=ldap_errno($this->connection).' '.ldap_error($this->connection);
262 267
 							}
@@ -264,7 +269,9 @@  discard block
 block discarded – undo
264 269
 					}
265 270
 				}
266 271
 
267
-				if (! $connected) $this->close();
272
+				if (! $connected) {
273
+				    $this->close();
274
+				}
268 275
 			}
269 276
 		}
270 277
 
@@ -272,8 +279,7 @@  discard block
 block discarded – undo
272 279
 		{
273 280
 			$return=$connected;
274 281
 			dol_syslog(get_class($this)."::connect_bind return=".$return, LOG_DEBUG);
275
-		}
276
-		else
282
+		} else
277 283
 		{
278 284
 			$this->error='Failed to connect to LDAP'.($this->error?': '.$this->error:'');
279 285
 			$return=-1;
@@ -295,8 +301,7 @@  discard block
 block discarded – undo
295 301
 		if ($this->connection && ! @ldap_close($this->connection))
296 302
 		{
297 303
 			return false;
298
-		}
299
-		else
304
+		} else
300 305
 		{
301 306
 			return true;
302 307
 		}
@@ -316,8 +321,7 @@  discard block
 block discarded – undo
316 321
 			$this->ldapErrorText = ldap_error($this->connection);
317 322
 			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
318 323
 			return false;
319
-		}
320
-		else
324
+		} else
321 325
 		{
322 326
 			return true;
323 327
 		}
@@ -341,8 +345,7 @@  discard block
 block discarded – undo
341 345
 			$this->ldapErrorText = ldap_error($this->connection);
342 346
 			$this->error=$this->ldapErrorCode." ".$this->ldapErrorText;
343 347
 			return false;
344
-		}
345
-		else
348
+		} else
346 349
 		{
347 350
 			return true;
348 351
 		}
@@ -432,7 +435,9 @@  discard block
 block discarded – undo
432 435
 		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
433 436
 		foreach($info as $key => $val)
434 437
 		{
435
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
438
+			if (! is_array($val)) {
439
+			    $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
440
+			}
436 441
 		}
437 442
 
438 443
 		$this->dump($dn,$info);
@@ -444,8 +449,7 @@  discard block
 block discarded – undo
444 449
 		{
445 450
 			dol_syslog(get_class($this)."::add successfull", LOG_DEBUG);
446 451
 			return 1;
447
-		}
448
-		else
452
+		} else
449 453
 		{
450 454
 			$this->ldapErrorCode = @ldap_errno($this->connection);
451 455
 			$this->ldapErrorText = @ldap_error($this->connection);
@@ -486,7 +490,9 @@  discard block
 block discarded – undo
486 490
 		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
487 491
 		foreach($info as $key => $val)
488 492
 		{
489
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
493
+			if (! is_array($val)) {
494
+			    $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
495
+			}
490 496
 		}
491 497
 
492 498
 		$this->dump($dn,$info);
@@ -498,8 +504,7 @@  discard block
 block discarded – undo
498 504
 		{
499 505
 			dol_syslog(get_class($this)."::modify successfull", LOG_DEBUG);
500 506
 			return 1;
501
-		}
502
-		else
507
+		} else
503 508
 		{
504 509
 			$this->error=@ldap_error($this->connection);
505 510
 			dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
@@ -548,8 +553,7 @@  discard block
 block discarded – undo
548 553
 		{
549 554
 			dol_syslog(get_class($this)."::rename successfull", LOG_DEBUG);
550 555
 			return 1;
551
-		}
552
-		else
556
+		} else
553 557
 		{
554 558
 			$this->error=@ldap_error($this->connection);
555 559
 			dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
@@ -593,15 +597,16 @@  discard block
 block discarded – undo
593 597
 			{
594 598
 				// This function currently only works with LDAPv3
595 599
 				$result = $this->rename($olddn, $newrdn, $newparent, $user, true);
596
-			}
597
-			else
600
+			} else
598 601
 			{
599 602
 				// If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
600 603
 				$result = $this->add($dn, $info, $user);
601
-				if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn);	// If add fails, we do not try to delete old one
604
+				if ($result > 0 && $olddn && $olddn != $dn) {
605
+				    $result = $this->delete($olddn);
606
+				}
607
+				// If add fails, we do not try to delete old one
602 608
 			}
603
-		}
604
-		else
609
+		} else
605 610
 		{
606 611
 			//$result = $this->delete($olddn);
607 612
 			$result = $this->add($dn, $info, $user);	// If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
@@ -613,8 +618,7 @@  discard block
 block discarded – undo
613 618
 			dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
614 619
 			//print_r($info);
615 620
 			return -1;
616
-		}
617
-		else
621
+		} else
618 622
 		{
619 623
 			dol_syslog(get_class($this)."::update done successfully");
620 624
 			return 1;
@@ -652,7 +656,9 @@  discard block
 block discarded – undo
652 656
 
653 657
 		$result=@ldap_delete($this->connection, $dn);
654 658
 
655
-		if ($result) return 1;
659
+		if ($result) {
660
+		    return 1;
661
+		}
656 662
 		return -1;
657 663
 	}
658 664
 
@@ -673,23 +679,23 @@  discard block
 block discarded – undo
673 679
 		if (preg_match('/^ldap/',$this->server[0]))
674 680
 		{
675 681
 			$target="-H ".join(',',$this->server);
676
-		}
677
-		else
682
+		} else
678 683
 		{
679 684
 			$target="-h ".join(',',$this->server)." -p ".$this->serverPort;
680 685
 		}
681 686
 		$content.="# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
682 687
 		$content.="# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
683 688
 		$content.="# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
684
-		if (in_array('localhost',$this->server)) $content.="# If commands fails to connect, try without -h and -p\n";
689
+		if (in_array('localhost',$this->server)) {
690
+		    $content.="# If commands fails to connect, try without -h and -p\n";
691
+		}
685 692
 		$content.="dn: ".$dn."\n";
686 693
 		foreach($info as $key => $value)
687 694
 		{
688 695
 			if (! is_array($value))
689 696
 			{
690 697
 				$content.="$key: $value\n";
691
-			}
692
-			else
698
+			} else
693 699
 			{
694 700
 				foreach($value as $valuekey => $valuevalue)
695 701
 				{
@@ -723,11 +729,11 @@  discard block
 block discarded – undo
723 729
 		{
724 730
 			fputs($fp, $content);
725 731
 			fclose($fp);
726
-			if (! empty($conf->global->MAIN_UMASK))
727
-			@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
732
+			if (! empty($conf->global->MAIN_UMASK)) {
733
+						@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
734
+			}
728 735
 			return 1;
729
-		}
730
-		else
736
+		} else
731 737
 		{
732 738
 			return -1;
733 739
 		}
@@ -752,7 +758,10 @@  discard block
 block discarded – undo
752 758
 			$host = $regs[1];
753 759
 		}
754 760
 		$op = @fsockopen($host, $port, $errno, $errstr, $timeout);
755
-		if (!$op) return false; //DC is N/A
761
+		if (!$op) {
762
+		    return false;
763
+		}
764
+		//DC is N/A
756 765
 		else {
757 766
 			fclose($op); //explicitly close open socket connection
758 767
 			return true; //DC is up & running, we can safely connect with ldap_connect
@@ -793,7 +802,9 @@  discard block
 block discarded – undo
793 802
 		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
794 803
 		foreach($info as $key => $val)
795 804
 		{
796
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
805
+			if (! is_array($val)) {
806
+			    $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
807
+			}
797 808
 		}
798 809
 
799 810
 		$this->dump($dn,$info);
@@ -805,8 +816,7 @@  discard block
 block discarded – undo
805 816
 		{
806 817
 			dol_syslog(get_class($this)."::add_attribute successfull", LOG_DEBUG);
807 818
 			return 1;
808
-		}
809
-		else
819
+		} else
810 820
 		{
811 821
 			$this->error=@ldap_error($this->connection);
812 822
 			dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
@@ -845,7 +855,9 @@  discard block
 block discarded – undo
845 855
 		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
846 856
 		foreach($info as $key => $val)
847 857
 		{
848
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
858
+			if (! is_array($val)) {
859
+			    $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
860
+			}
849 861
 		}
850 862
 
851 863
 		$this->dump($dn,$info);
@@ -857,8 +869,7 @@  discard block
 block discarded – undo
857 869
 		{
858 870
 			dol_syslog(get_class($this)."::updateAttribute successfull", LOG_DEBUG);
859 871
 			return 1;
860
-		}
861
-		else
872
+		} else
862 873
 		{
863 874
 			$this->error=@ldap_error($this->connection);
864 875
 			dol_syslog(get_class($this)."::updateAttribute failed: ".$this->error, LOG_ERR);
@@ -897,7 +908,9 @@  discard block
 block discarded – undo
897 908
 		$dn=$this->convFromOutputCharset($dn,$this->ldapcharset);
898 909
 		foreach($info as $key => $val)
899 910
 		{
900
-			if (! is_array($val)) $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
911
+			if (! is_array($val)) {
912
+			    $info[$key]=$this->convFromOutputCharset($val,$this->ldapcharset);
913
+			}
901 914
 		}
902 915
 
903 916
 		$this->dump($dn,$info);
@@ -909,8 +922,7 @@  discard block
 block discarded – undo
909 922
 		{
910 923
 			dol_syslog(get_class($this)."::deleteAttribute successfull", LOG_DEBUG);
911 924
 			return 1;
912
-		}
913
-		else
925
+		} else
914 926
 		{
915 927
 			$this->error=@ldap_error($this->connection);
916 928
 			dol_syslog(get_class($this)."::deleteAttribute failed: ".$this->error, LOG_ERR);
@@ -1034,17 +1046,14 @@  discard block
 block discarded – undo
1034 1046
 			if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter)
1035 1047
 			{
1036 1048
 				$filter = '('.$this->filter.')';
1037
-			}
1038
-			elseif (((string) $activefilter == 'member') && $this->filter)
1049
+			} elseif (((string) $activefilter == 'member') && $this->filter)
1039 1050
 			{
1040 1051
 				$filter = '('.$this->filtermember.')';
1041
-			}
1042
-			else	// If this->filter is empty, make fiter on * (all)
1052
+			} else	// If this->filter is empty, make fiter on * (all)
1043 1053
 			{
1044 1054
 				$filter = '('.$useridentifier.'=*)';
1045 1055
 			}
1046
-		}
1047
-		else
1056
+		} else
1048 1057
 		{
1049 1058
 			$filter = '('.$useridentifier.'='.$search.')';
1050 1059
 		}
@@ -1056,8 +1065,7 @@  discard block
 block discarded – undo
1056 1065
 			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter. " attributeArray=(".join(',',$attributeArray).")");
1057 1066
 			//var_dump($attributeArray);
1058 1067
 			$this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1059
-		}
1060
-		else
1068
+		} else
1061 1069
 		{
1062 1070
 			// Return list with fields selected by default
1063 1071
 			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter);
@@ -1095,8 +1103,7 @@  discard block
 block discarded – undo
1095 1103
 					{
1096 1104
 						$objectsid = $this->getObjectSid($recordid);
1097 1105
 						$fulllist[$recordid][$attributeArray[$j]]    = $objectsid;
1098
-					}
1099
-					else
1106
+					} else
1100 1107
 					{
1101 1108
 						if(in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1102 1109
 							$valueTab = array();
@@ -1170,8 +1177,7 @@  discard block
 block discarded – undo
1170 1177
 				// Si pas de resultat on cherche dans le domaine
1171 1178
 				$searchDN = $this->domain;
1172 1179
 				$i++;
1173
-			}
1174
-			else
1180
+			} else
1175 1181
 			{
1176 1182
 				$i++;
1177 1183
 				$i++;
@@ -1183,8 +1189,7 @@  discard block
 block discarded – undo
1183 1189
 			$ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
1184 1190
 			$SIDText = $this->binSIDtoText($ldapBinary[0]);
1185 1191
 			return $SIDText;
1186
-		}
1187
-		else
1192
+		} else
1188 1193
 		{
1189 1194
 			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1190 1195
 			return '?';
@@ -1243,8 +1248,7 @@  discard block
 block discarded – undo
1243 1248
 		{
1244 1249
 			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1245 1250
 			return -1;
1246
-		}
1247
-		else
1251
+		} else
1248 1252
 		{
1249 1253
 			ldap_free_result($this->result);
1250 1254
 			return $result;
@@ -1280,11 +1284,13 @@  discard block
 block discarded – undo
1280 1284
 			if ($this->result)
1281 1285
 			{
1282 1286
 				$result = @ldap_get_entries($this->connection, $this->result);
1283
-				if ($result['count'] > 0) dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1284
-				else dol_syslog('Ldap::fetch search returns but found no records');
1287
+				if ($result['count'] > 0) {
1288
+				    dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1289
+				} else {
1290
+				    dol_syslog('Ldap::fetch search returns but found no records');
1291
+				}
1285 1292
 				//var_dump($result);exit;
1286
-			}
1287
-			else
1293
+			} else
1288 1294
 			{
1289 1295
 				$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1290 1296
 				dol_syslog(get_class($this)."::fetch search fails");
@@ -1296,8 +1302,7 @@  discard block
 block discarded – undo
1296 1302
 				// Si pas de resultat on cherche dans le domaine
1297 1303
 				$searchDN = $this->domain;
1298 1304
 				$i++;
1299
-			}
1300
-			else
1305
+			} else
1301 1306
 			{
1302 1307
 				break;
1303 1308
 			}
@@ -1307,8 +1312,7 @@  discard block
 block discarded – undo
1307 1312
 		{
1308 1313
 			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1309 1314
 			return -1;
1310
-		}
1311
-		else
1315
+		} else
1312 1316
 		{
1313 1317
 			$this->name       = $this->convToOutputCharset($result[0][$this->attr_name][0],$this->ldapcharset);
1314 1318
 			$this->firstname  = $this->convToOutputCharset($result[0][$this->attr_firstname][0],$this->ldapcharset);
@@ -1320,15 +1324,18 @@  discard block
 block discarded – undo
1320 1324
 			$this->mobile     = $this->convToOutputCharset($result[0][$this->attr_mobile][0],$this->ldapcharset);
1321 1325
 
1322 1326
 			$this->uacf       = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0],$this->ldapcharset));
1323
-			if (isset($result[0]["pwdlastset"][0]))	// If expiration on password exists
1327
+			if (isset($result[0]["pwdlastset"][0])) {
1328
+			    // If expiration on password exists
1324 1329
 			{
1325 1330
 				$this->pwdlastset = ($result[0]["pwdlastset"][0] != 0)?$this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0],$this->ldapcharset)):0;
1326 1331
 			}
1327
-			else
1332
+			} else
1328 1333
 			{
1329 1334
 				$this->pwdlastset = -1;
1330 1335
 			}
1331
-			if (!$this->name && !$this->login) $this->pwdlastset = -1;
1336
+			if (!$this->name && !$this->login) {
1337
+			    $this->pwdlastset = -1;
1338
+			}
1332 1339
 			$this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0],$this->ldapcharset));
1333 1340
 
1334 1341
 			// FQDN domain
@@ -1433,7 +1440,9 @@  discard block
 block discarded – undo
1433 1440
 				break;
1434 1441
 			}
1435 1442
 		}
1436
-		if (empty($retval)) $retval = "UNKNOWN_TYPE_" . $samtype;
1443
+		if (empty($retval)) {
1444
+		    $retval = "UNKNOWN_TYPE_" . $samtype;
1445
+		}
1437 1446
 
1438 1447
 		return($retval);
1439 1448
 	}
@@ -1466,8 +1475,12 @@  discard block
 block discarded – undo
1466 1475
 	private function convToOutputCharset($str,$pagecodefrom='UTF-8')
1467 1476
 	{
1468 1477
 		global $conf;
1469
-		if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8')  $str=utf8_encode($str);
1470
-		if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1')  $str=utf8_decode($str);
1478
+		if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1479
+		    $str=utf8_encode($str);
1480
+		}
1481
+		if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1482
+		    $str=utf8_decode($str);
1483
+		}
1471 1484
 		return $str;
1472 1485
 	}
1473 1486
 
@@ -1481,8 +1494,12 @@  discard block
 block discarded – undo
1481 1494
 	function convFromOutputCharset($str,$pagecodeto='UTF-8')
1482 1495
 	{
1483 1496
 		global $conf;
1484
-		if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') $str=utf8_decode($str);
1485
-		if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') $str=utf8_encode($str);
1497
+		if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1498
+		    $str=utf8_decode($str);
1499
+		}
1500
+		if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1501
+		    $str=utf8_encode($str);
1502
+		}
1486 1503
 		return $str;
1487 1504
 	}
1488 1505
 
@@ -1497,7 +1514,9 @@  discard block
 block discarded – undo
1497 1514
 	{
1498 1515
 		global $conf;
1499 1516
 
1500
-		if (empty($keygroup)) $keygroup='LDAP_KEY_GROUPS';
1517
+		if (empty($keygroup)) {
1518
+		    $keygroup='LDAP_KEY_GROUPS';
1519
+		}
1501 1520
 
1502 1521
 		$search='('.$conf->global->$keygroup.'=*)';
1503 1522
 		$result = $this->search($this->groups,$search);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/antivir.class.php 3 patches
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -30,73 +30,73 @@  discard block
 block discarded – undo
30 30
  */
31 31
 class AntiVir
32 32
 {
33
-	/**
34
-	 * @var string Error code (or message)
35
-	 */
36
-	public $error='';
37
-
38
-	/**
39
-	 * @var string[] Error codes (or messages)
40
-	 */
41
-	public $errors = array();
42
-
43
-	/**
44
-	 * @var string Used to return message
45
-	 */
46
-	public $output;
47
-
48
-	/**
33
+    /**
34
+     * @var string Error code (or message)
35
+     */
36
+    public $error='';
37
+
38
+    /**
39
+     * @var string[] Error codes (or messages)
40
+     */
41
+    public $errors = array();
42
+
43
+    /**
44
+     * @var string Used to return message
45
+     */
46
+    public $output;
47
+
48
+    /**
49 49
      * @var DoliDB Database handler.
50 50
      */
51 51
     public $db;
52 52
 
53
-	/**
54
-	 *  Constructor
55
-	 *
56
-	 *  @param      DoliDB		$db      Database handler
57
-	 */
58
-	function __construct($db)
59
-	{
60
-		$this->db=$db;
61
-	}
53
+    /**
54
+     *  Constructor
55
+     *
56
+     *  @param      DoliDB		$db      Database handler
57
+     */
58
+    function __construct($db)
59
+    {
60
+        $this->db=$db;
61
+    }
62 62
 
63 63
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
64
-	/**
65
-	 *	Scan a file with antivirus.
66
-	 *  This function runs the command defined in setup. This antivirus command must return 0 if OK.
67
-	 *  Return also true (virus found) if file end with '.virus' (so we can make test safely).
68
-	 *
69
-	 *	@param	string	$file		File to scan
70
-	 *	@return	int					<0 if KO (-98 if error, -99 if virus), 0 if OK
71
-	 */
72
-	function dol_avscan_file($file)
73
-	{
64
+    /**
65
+     *	Scan a file with antivirus.
66
+     *  This function runs the command defined in setup. This antivirus command must return 0 if OK.
67
+     *  Return also true (virus found) if file end with '.virus' (so we can make test safely).
68
+     *
69
+     *	@param	string	$file		File to scan
70
+     *	@return	int					<0 if KO (-98 if error, -99 if virus), 0 if OK
71
+     */
72
+    function dol_avscan_file($file)
73
+    {
74 74
         // phpcs:enable
75
-		global $conf;
75
+        global $conf;
76 76
 
77
-		$return = 0;
77
+        $return = 0;
78 78
 
79
-		if (preg_match('/\.virus$/i', $file))
80
-		{
81
-		    $this->errors[] = 'File has an extension saying file is a virus';
82
-		    return -97;
83
-		}
79
+        if (preg_match('/\.virus$/i', $file))
80
+        {
81
+            $this->errors[] = 'File has an extension saying file is a virus';
82
+            return -97;
83
+        }
84 84
 
85
-		$fullcommand=$this->getCliCommand($file);
86
-		//$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"';
85
+        $fullcommand=$this->getCliCommand($file);
86
+        //$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"';
87 87
         $fullcommand.=' 2>&1';      // This is to get error output
88 88
 
89
-		$output=array();
90
-		$return_var=0;
89
+        $output=array();
90
+        $return_var=0;
91 91
         $safemode=ini_get("safe_mode");
92
-		// Create a clean fullcommand
93
-		dol_syslog("AntiVir::dol_avscan_file Run command=".$fullcommand." with safe_mode ".($safemode?"on":"off"));
94
-		// Run CLI command. If run of Windows, you can get return with echo %ERRORLEVEL%
95
-		$lastline=exec($fullcommand, $output, $return_var);
92
+        // Create a clean fullcommand
93
+        dol_syslog("AntiVir::dol_avscan_file Run command=".$fullcommand." with safe_mode ".($safemode?"on":"off"));
94
+        // Run CLI command. If run of Windows, you can get return with echo %ERRORLEVEL%
95
+        $lastline=exec($fullcommand, $output, $return_var);
96 96
 
97 97
         //print "x".$lastline." - ".join(',',$output)." - ".$return_var."y";exit;
98 98
 
99
-		/*
99
+        /*
100 100
         $outputfile=$conf->admin->dir_temp.'/dol_avscan_file.out.'.session_id();
101 101
 		$handle = fopen($outputfile, 'w');
102 102
 		if ($handle)
@@ -126,62 +126,62 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		*/
128 128
 
129
-		dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',',$output));
129
+        dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',',$output));
130 130
 
131
-		$returncodevirus=1;
132
-		if ($return_var == $returncodevirus)	// Virus found
133
-		{
134
-			$this->errors=$output;
135
-			return -99;
136
-		}
131
+        $returncodevirus=1;
132
+        if ($return_var == $returncodevirus)	// Virus found
133
+        {
134
+            $this->errors=$output;
135
+            return -99;
136
+        }
137 137
 
138
-		if ($return_var > 0)					// If other error
139
-		{
140
-			$this->errors=$output;
141
-			return -98;
142
-		}
138
+        if ($return_var > 0)					// If other error
139
+        {
140
+            $this->errors=$output;
141
+            return -98;
142
+        }
143 143
 
144
-		// If return code = 0
145
-		return 1;
146
-	}
144
+        // If return code = 0
145
+        return 1;
146
+    }
147 147
 
148 148
 
149 149
 
150
-	/**
151
-	 *	Get full Command Line to run
152
-	 *
153
-	 *	@param	string	$file		File to scan
154
-	 *	@return	string				Full command line to run
155
-	 */
156
-	function getCliCommand($file)
157
-	{
158
-		global $conf;
150
+    /**
151
+     *	Get full Command Line to run
152
+     *
153
+     *	@param	string	$file		File to scan
154
+     *	@return	string				Full command line to run
155
+     */
156
+    function getCliCommand($file)
157
+    {
158
+        global $conf;
159 159
 
160
-		$maxreclevel = 5 ; 			// maximal recursion level
161
-		$maxfiles = 1000; 			// maximal number of files to be scanned within archive
162
-		$maxratio = 200; 			// maximal compression ratio
163
-		$bz2archivememlim = 0; 		// limit memory usage for bzip2 (0/1)
164
-		$maxfilesize = 10485760; 	// archived files larger than this value (in bytes) will not be scanned
160
+        $maxreclevel = 5 ; 			// maximal recursion level
161
+        $maxfiles = 1000; 			// maximal number of files to be scanned within archive
162
+        $maxratio = 200; 			// maximal compression ratio
163
+        $bz2archivememlim = 0; 		// limit memory usage for bzip2 (0/1)
164
+        $maxfilesize = 10485760; 	// archived files larger than this value (in bytes) will not be scanned
165 165
 
166
-		$command=$conf->global->MAIN_ANTIVIRUS_COMMAND;
167
-		$param=$conf->global->MAIN_ANTIVIRUS_PARAM;
166
+        $command=$conf->global->MAIN_ANTIVIRUS_COMMAND;
167
+        $param=$conf->global->MAIN_ANTIVIRUS_PARAM;
168 168
 
169
-		$param=preg_replace('/%maxreclevel/',$maxreclevel,$param);
170
-		$param=preg_replace('/%maxfiles/',$maxfiles,$param);
171
-		$param=preg_replace('/%maxratio/',$maxratio,$param);
172
-		$param=preg_replace('/%bz2archivememlim/',$bz2archivememlim,$param);
173
-		$param=preg_replace('/%maxfilesize/',$maxfilesize,$param);
174
-		$param=preg_replace('/%file/',trim($file),$param);
169
+        $param=preg_replace('/%maxreclevel/',$maxreclevel,$param);
170
+        $param=preg_replace('/%maxfiles/',$maxfiles,$param);
171
+        $param=preg_replace('/%maxratio/',$maxratio,$param);
172
+        $param=preg_replace('/%bz2archivememlim/',$bz2archivememlim,$param);
173
+        $param=preg_replace('/%maxfilesize/',$maxfilesize,$param);
174
+        $param=preg_replace('/%file/',trim($file),$param);
175 175
 
176
-		if (! preg_match('/%file/',$conf->global->MAIN_ANTIVIRUS_PARAM))
177
-			$param=$param." ".escapeshellarg(trim($file));
176
+        if (! preg_match('/%file/',$conf->global->MAIN_ANTIVIRUS_PARAM))
177
+            $param=$param." ".escapeshellarg(trim($file));
178 178
 
179
-		if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command. Using escapeshellcmd fails.
179
+        if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command. Using escapeshellcmd fails.
180 180
 
181
-		$ret=$command.' '.$param;
182
-		//$ret=$command.' '.$param.' 2>&1';
181
+        $ret=$command.' '.$param;
182
+        //$ret=$command.' '.$param.' 2>&1';
183 183
         //print "xx".$ret."xx";exit;
184 184
 
185
-		return $ret;
186
-	}
185
+        return $ret;
186
+    }
187 187
 }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 	/**
34 34
 	 * @var string Error code (or message)
35 35
 	 */
36
-	public $error='';
36
+	public $error = '';
37 37
 
38 38
 	/**
39 39
 	 * @var string[] Error codes (or messages)
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 	 */
58 58
 	function __construct($db)
59 59
 	{
60
-		$this->db=$db;
60
+		$this->db = $db;
61 61
 	}
62 62
 
63 63
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -82,17 +82,17 @@  discard block
 block discarded – undo
82 82
 		    return -97;
83 83
 		}
84 84
 
85
-		$fullcommand=$this->getCliCommand($file);
85
+		$fullcommand = $this->getCliCommand($file);
86 86
 		//$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"';
87
-        $fullcommand.=' 2>&1';      // This is to get error output
87
+        $fullcommand .= ' 2>&1'; // This is to get error output
88 88
 
89
-		$output=array();
90
-		$return_var=0;
91
-        $safemode=ini_get("safe_mode");
89
+		$output = array();
90
+		$return_var = 0;
91
+        $safemode = ini_get("safe_mode");
92 92
 		// Create a clean fullcommand
93
-		dol_syslog("AntiVir::dol_avscan_file Run command=".$fullcommand." with safe_mode ".($safemode?"on":"off"));
93
+		dol_syslog("AntiVir::dol_avscan_file Run command=".$fullcommand." with safe_mode ".($safemode ? "on" : "off"));
94 94
 		// Run CLI command. If run of Windows, you can get return with echo %ERRORLEVEL%
95
-		$lastline=exec($fullcommand, $output, $return_var);
95
+		$lastline = exec($fullcommand, $output, $return_var);
96 96
 
97 97
         //print "x".$lastline." - ".join(',',$output)." - ".$return_var."y";exit;
98 98
 
@@ -126,18 +126,18 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		*/
128 128
 
129
-		dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',',$output));
129
+		dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',', $output));
130 130
 
131
-		$returncodevirus=1;
131
+		$returncodevirus = 1;
132 132
 		if ($return_var == $returncodevirus)	// Virus found
133 133
 		{
134
-			$this->errors=$output;
134
+			$this->errors = $output;
135 135
 			return -99;
136 136
 		}
137 137
 
138 138
 		if ($return_var > 0)					// If other error
139 139
 		{
140
-			$this->errors=$output;
140
+			$this->errors = $output;
141 141
 			return -98;
142 142
 		}
143 143
 
@@ -157,28 +157,28 @@  discard block
 block discarded – undo
157 157
 	{
158 158
 		global $conf;
159 159
 
160
-		$maxreclevel = 5 ; 			// maximal recursion level
161
-		$maxfiles = 1000; 			// maximal number of files to be scanned within archive
162
-		$maxratio = 200; 			// maximal compression ratio
163
-		$bz2archivememlim = 0; 		// limit memory usage for bzip2 (0/1)
164
-		$maxfilesize = 10485760; 	// archived files larger than this value (in bytes) will not be scanned
160
+		$maxreclevel = 5; // maximal recursion level
161
+		$maxfiles = 1000; // maximal number of files to be scanned within archive
162
+		$maxratio = 200; // maximal compression ratio
163
+		$bz2archivememlim = 0; // limit memory usage for bzip2 (0/1)
164
+		$maxfilesize = 10485760; // archived files larger than this value (in bytes) will not be scanned
165 165
 
166
-		$command=$conf->global->MAIN_ANTIVIRUS_COMMAND;
167
-		$param=$conf->global->MAIN_ANTIVIRUS_PARAM;
166
+		$command = $conf->global->MAIN_ANTIVIRUS_COMMAND;
167
+		$param = $conf->global->MAIN_ANTIVIRUS_PARAM;
168 168
 
169
-		$param=preg_replace('/%maxreclevel/',$maxreclevel,$param);
170
-		$param=preg_replace('/%maxfiles/',$maxfiles,$param);
171
-		$param=preg_replace('/%maxratio/',$maxratio,$param);
172
-		$param=preg_replace('/%bz2archivememlim/',$bz2archivememlim,$param);
173
-		$param=preg_replace('/%maxfilesize/',$maxfilesize,$param);
174
-		$param=preg_replace('/%file/',trim($file),$param);
169
+		$param = preg_replace('/%maxreclevel/', $maxreclevel, $param);
170
+		$param = preg_replace('/%maxfiles/', $maxfiles, $param);
171
+		$param = preg_replace('/%maxratio/', $maxratio, $param);
172
+		$param = preg_replace('/%bz2archivememlim/', $bz2archivememlim, $param);
173
+		$param = preg_replace('/%maxfilesize/', $maxfilesize, $param);
174
+		$param = preg_replace('/%file/', trim($file), $param);
175 175
 
176
-		if (! preg_match('/%file/',$conf->global->MAIN_ANTIVIRUS_PARAM))
177
-			$param=$param." ".escapeshellarg(trim($file));
176
+		if (!preg_match('/%file/', $conf->global->MAIN_ANTIVIRUS_PARAM))
177
+			$param = $param." ".escapeshellarg(trim($file));
178 178
 
179
-		if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command. Using escapeshellcmd fails.
179
+		if (preg_match("/\s/", $command)) $command = escapeshellarg($command); // Use quotes on command. Using escapeshellcmd fails.
180 180
 
181
-		$ret=$command.' '.$param;
181
+		$ret = $command.' '.$param;
182 182
 		//$ret=$command.' '.$param.' 2>&1';
183 183
         //print "xx".$ret."xx";exit;
184 184
 
Please login to merge, or discard this patch.
Braces   +13 added lines, -5 removed lines patch added patch discarded remove patch
@@ -129,15 +129,19 @@  discard block
 block discarded – undo
129 129
 		dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',',$output));
130 130
 
131 131
 		$returncodevirus=1;
132
-		if ($return_var == $returncodevirus)	// Virus found
132
+		if ($return_var == $returncodevirus) {
133
+		    // Virus found
133 134
 		{
134 135
 			$this->errors=$output;
136
+		}
135 137
 			return -99;
136 138
 		}
137 139
 
138
-		if ($return_var > 0)					// If other error
140
+		if ($return_var > 0) {
141
+		    // If other error
139 142
 		{
140 143
 			$this->errors=$output;
144
+		}
141 145
 			return -98;
142 146
 		}
143 147
 
@@ -173,10 +177,14 @@  discard block
 block discarded – undo
173 177
 		$param=preg_replace('/%maxfilesize/',$maxfilesize,$param);
174 178
 		$param=preg_replace('/%file/',trim($file),$param);
175 179
 
176
-		if (! preg_match('/%file/',$conf->global->MAIN_ANTIVIRUS_PARAM))
177
-			$param=$param." ".escapeshellarg(trim($file));
180
+		if (! preg_match('/%file/',$conf->global->MAIN_ANTIVIRUS_PARAM)) {
181
+					$param=$param." ".escapeshellarg(trim($file));
182
+		}
178 183
 
179
-		if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command. Using escapeshellcmd fails.
184
+		if (preg_match("/\s/",$command)) {
185
+		    $command=escapeshellarg($command);
186
+		}
187
+		// Use quotes on command. Using escapeshellcmd fails.
180 188
 
181 189
 		$ret=$command.' '.$param;
182 190
 		//$ret=$command.' '.$param.' 2>&1';
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/workboardresponse.class.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -25,51 +25,51 @@
 block discarded – undo
25 25
 class WorkboardResponse
26 26
 {
27 27
 
28
-	/**
29
-	 * Image URL to represent the board item
30
-	 * @var string
31
-	 */
32
-	public $img;
28
+    /**
29
+     * Image URL to represent the board item
30
+     * @var string
31
+     */
32
+    public $img;
33 33
 
34
-	/**
35
-	 * Label of the warning
36
-	 * @var string
37
-	 */
38
-	public $label;
34
+    /**
35
+     * Label of the warning
36
+     * @var string
37
+     */
38
+    public $label;
39 39
 
40
-	/**
41
-	 * URL to list to do items
42
-	 * @var string
43
-	 */
44
-	public $url;
40
+    /**
41
+     * URL to list to do items
42
+     * @var string
43
+     */
44
+    public $url;
45 45
 
46
-	/**
47
-	 * (optional) If set, to do late items will link to this url
48
-	 * @var string
49
-	 */
50
-	public $url_late;
46
+    /**
47
+     * (optional) If set, to do late items will link to this url
48
+     * @var string
49
+     */
50
+    public $url_late;
51 51
 
52
-	/**
53
-	 * Delay time to mark an item as late. In number of days.
54
-	 * @var double
55
-	 */
56
-	public $warning_delay;
52
+    /**
53
+     * Delay time to mark an item as late. In number of days.
54
+     * @var double
55
+     */
56
+    public $warning_delay;
57 57
 
58
-	/**
59
-	 * Number of items to do
60
-	 * @var int
61
-	 */
62
-	public $nbtodo = 0;
58
+    /**
59
+     * Number of items to do
60
+     * @var int
61
+     */
62
+    public $nbtodo = 0;
63 63
 
64
-	/**
65
-	 * Number of to do items which are late
66
-	 * @var int
67
-	 */
68
-	public $nbtodolate = 0;
64
+    /**
65
+     * Number of to do items which are late
66
+     * @var int
67
+     */
68
+    public $nbtodolate = 0;
69 69
 
70
-	/**
71
-	 * total price of items
72
-	 * @var int
73
-	 */
74
-	public $total = 0;
70
+    /**
71
+     * total price of items
72
+     * @var int
73
+     */
74
+    public $total = 0;
75 75
 }
Please login to merge, or discard this patch.