Passed
Push — master ( 49af33...3cffbe )
by Alxarafe
21:21
created
dolibarr/htdocs/core/class/html.formticket.class.php 3 patches
Indentation   +7 added lines, -8 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@  discard block
 block discarded – undo
32 32
  * Classe permettant la generation du formulaire d'un nouveau ticket.
33 33
  *
34 34
  * @package Ticket
35
-
36 35
  * \remarks Utilisation: $formticket = new FormTicket($db)
37 36
  * \remarks $formticket->proprietes=1 ou chaine ou tableau de valeurs
38 37
  * \remarks $formticket->show_form() affiche le formulaire
@@ -88,9 +87,9 @@  discard block
 block discarded – undo
88 87
     public $param = array();
89 88
 
90 89
     /**
91
-	 * @var string Error code (or message)
92
-	 */
93
-	public $error;
90
+     * @var string Error code (or message)
91
+     */
92
+    public $error;
94 93
 
95 94
 
96 95
     /**
@@ -153,7 +152,7 @@  discard block
 block discarded – undo
153 152
         print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
154 153
         print '<input type="hidden" name="action" value="' . $this->action . '">';
155 154
         foreach ($this->param as $key => $value) {
156
-        	print '<input type="hidden" name="' . $key . '" value="' . $value . '">';
155
+            print '<input type="hidden" name="' . $key . '" value="' . $value . '">';
157 156
         }
158 157
         print '<input type="hidden" name="fk_user_create" value="' . $this->fk_user_create . '">';
159 158
 
@@ -306,9 +305,9 @@  discard block
 block discarded – undo
306 305
         // Notify thirdparty at creation
307 306
         if (empty($this->ispublic))
308 307
         {
309
-	        print '<tr><td><label for="notify_tiers_at_create">' . $langs->trans("TicketNotifyTiersAtCreation") . '</label></td><td>';
310
-        	print '<input type="checkbox" id="notify_tiers_at_create" name="notify_tiers_at_create"'.($this->withnotifytiersatcreate?' checked="checked"':'').'>';
311
-        	print '</td></tr>';
308
+            print '<tr><td><label for="notify_tiers_at_create">' . $langs->trans("TicketNotifyTiersAtCreation") . '</label></td><td>';
309
+            print '<input type="checkbox" id="notify_tiers_at_create" name="notify_tiers_at_create"'.($this->withnotifytiersatcreate?' checked="checked"':'').'>';
310
+            print '</td></tr>';
312 311
         }
313 312
 
314 313
         // TITLE
Please login to merge, or discard this patch.
Spacing   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -21,11 +21,11 @@  discard block
 block discarded – undo
21 21
  *       \ingroup    ticket
22 22
  *       \brief      Fichier de la classe permettant la generation du formulaire html d'envoi de mail unitaire
23 23
  */
24
-require_once DOL_DOCUMENT_ROOT . "/core/class/html.form.class.php";
25
-require_once DOL_DOCUMENT_ROOT . "/core/class/html.formmail.class.php";
24
+require_once DOL_DOCUMENT_ROOT."/core/class/html.form.class.php";
25
+require_once DOL_DOCUMENT_ROOT."/core/class/html.formmail.class.php";
26 26
 
27 27
 if (!class_exists('FormCompany')) {
28
-    include DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
28
+    include DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
29 29
 }
30 30
 
31 31
 /**
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
         $this->withcreatereadonly = 1;
115 115
         $this->withemail = 0;
116 116
         $this->withref = 0;
117
-        $this->withextrafields = 0;         // Show extrafields or not
117
+        $this->withextrafields = 0; // Show extrafields or not
118 118
         //$this->withtopicreadonly=0;
119 119
     }
120 120
 
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
      * @param  int	 $withdolfichehead			With dol_fiche_head
125 125
      * @return void
126 126
      */
127
-    public function showForm($withdolfichehead=0)
127
+    public function showForm($withdolfichehead = 0)
128 128
     {
129 129
         global $conf, $langs, $user, $hookmanager;
130 130
 
@@ -149,25 +149,25 @@  discard block
 block discarded – undo
149 149
 
150 150
         if ($withdolfichehead) dol_fiche_head(null, 'card', '', 0, '');
151 151
 
152
-        print '<form method="POST" '.($withdolfichehead?'':'style="margin-bottom: 30px;" ').'name="ticket" id="form_create_ticket" enctype="multipart/form-data" action="' . $this->param["returnurl"] . '">';
153
-        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
154
-        print '<input type="hidden" name="action" value="' . $this->action . '">';
152
+        print '<form method="POST" '.($withdolfichehead ? '' : 'style="margin-bottom: 30px;" ').'name="ticket" id="form_create_ticket" enctype="multipart/form-data" action="'.$this->param["returnurl"].'">';
153
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
154
+        print '<input type="hidden" name="action" value="'.$this->action.'">';
155 155
         foreach ($this->param as $key => $value) {
156
-        	print '<input type="hidden" name="' . $key . '" value="' . $value . '">';
156
+        	print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
157 157
         }
158
-        print '<input type="hidden" name="fk_user_create" value="' . $this->fk_user_create . '">';
158
+        print '<input type="hidden" name="fk_user_create" value="'.$this->fk_user_create.'">';
159 159
 
160 160
         print '<table class="border">';
161 161
 
162 162
         if ($this->withref) {
163 163
             // Ref
164 164
             $defaultref = $ticketstat->getDefaultRef();
165
-            print '<tr><td class="titlefield"><span class="fieldrequired">' . $langs->trans("Ref") . '</span></td><td><input size="18" type="text" name="ref" value="' . (GETPOST("ref", 'alpha') ? GETPOST("ref", 'alpha') : $defaultref) . '"></td></tr>';
165
+            print '<tr><td class="titlefield"><span class="fieldrequired">'.$langs->trans("Ref").'</span></td><td><input size="18" type="text" name="ref" value="'.(GETPOST("ref", 'alpha') ? GETPOST("ref", 'alpha') : $defaultref).'"></td></tr>';
166 166
         }
167 167
 
168 168
         // FK_USER_CREATE
169 169
         if ($this->withusercreate > 0 && $this->fk_user_create) {
170
-            print '<tr><td class="titlefield">' . $langs->trans("CreatedBy") . '</td><td>';
170
+            print '<tr><td class="titlefield">'.$langs->trans("CreatedBy").'</td><td>';
171 171
             $langs->load("users");
172 172
             $fuser = new User($this->db);
173 173
 
@@ -185,12 +185,12 @@  discard block
 block discarded – undo
185 185
             // altairis: force company and contact id for external user
186 186
             if (empty($user->socid)) {
187 187
                 // Company
188
-                print '<tr><td class="titlefield">' . $langs->trans("ThirdParty") . '</td><td>';
188
+                print '<tr><td class="titlefield">'.$langs->trans("ThirdParty").'</td><td>';
189 189
                 $events = array();
190 190
                 $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
191 191
                 print $form->select_company($this->withfromsocid, 'socid', '', 1, 1, '', $events, 0, 'minwidth200');
192 192
                 print '</td></tr>';
193
-                if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
193
+                if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
194 194
                     $htmlname = 'socid';
195 195
                     print '<script type="text/javascript">
196 196
                     $(document).ready(function () {
@@ -245,23 +245,23 @@  discard block
 block discarded – undo
245 245
                 }
246 246
 
247 247
                 // Contact and type
248
-                print '<tr><td>' . $langs->trans("Contact") . '</td><td>';
248
+                print '<tr><td>'.$langs->trans("Contact").'</td><td>';
249 249
                 // If no socid, set to -1 to avoid full contacts list
250 250
                 $selectedCompany = ($this->withfromsocid > 0) ? $this->withfromsocid : -1;
251 251
                 $nbofcontacts = $form->select_contacts($selectedCompany, $this->withfromcontactid, 'contactid', 3, '', '', 0, 'minwidth200');
252 252
                 $formcompany->selectTypeContact($ticketstatic, '', 'type', 'external', '', 0, 'maginleftonly');
253 253
                 print '</td></tr>';
254 254
             } else {
255
-                print '<tr><td class="titlefield"><input type="hidden" name="socid" value="' . $user->socid . '"/></td>';
256
-                print '<td><input type="hidden" name="contactid" value="' . $user->contactid . '"/></td>';
255
+                print '<tr><td class="titlefield"><input type="hidden" name="socid" value="'.$user->socid.'"/></td>';
256
+                print '<td><input type="hidden" name="contactid" value="'.$user->contactid.'"/></td>';
257 257
                 print '<td><input type="hidden" name="type" value="Z"/></td></tr>';
258 258
             }
259 259
         }
260 260
 
261 261
         // TITLE
262 262
         if ($this->withemail) {
263
-            print '<tr><td class="titlefield"><label for="email"><span class="fieldrequired">' . $langs->trans("Email") . '</span></label></td><td>';
264
-            print '<input  class="text minwidth200" id="email" name="email" value="' . (GETPOST('email', 'alpha') ? GETPOST('email', 'alpha') : $subject) . '" />';
263
+            print '<tr><td class="titlefield"><label for="email"><span class="fieldrequired">'.$langs->trans("Email").'</span></label></td><td>';
264
+            print '<input  class="text minwidth200" id="email" name="email" value="'.(GETPOST('email', 'alpha') ? GETPOST('email', 'alpha') : $subject).'" />';
265 265
             print '</td></tr>';
266 266
         }
267 267
 
@@ -274,10 +274,10 @@  discard block
 block discarded – undo
274 274
                 $subelement = $regs[2];
275 275
             }
276 276
 
277
-            dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
277
+            dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
278 278
             $classname = ucfirst($subelement);
279 279
             $objectsrc = new $classname($this->db);
280
-            $objectsrc->fetch(GETPOST('originid','int'));
280
+            $objectsrc->fetch(GETPOST('originid', 'int'));
281 281
 
282 282
             if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
283 283
                 $objectsrc->fetch_lines();
@@ -285,58 +285,58 @@  discard block
 block discarded – undo
285 285
 
286 286
             $objectsrc->fetch_thirdparty();
287 287
             $newclassname = $classname;
288
-            print '<tr><td>' . $langs->trans($newclassname) . '</td><td colspan="2"><input name="' . $subelement . 'id" value="' . GETPOST('originid') . '" type="hidden" />' . $objectsrc->getNomUrl(1) . '</td></tr>';
288
+            print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2"><input name="'.$subelement.'id" value="'.GETPOST('originid').'" type="hidden" />'.$objectsrc->getNomUrl(1).'</td></tr>';
289 289
         }
290 290
 
291 291
         // Type
292
-        print '<tr><td class="titlefield"><span class="fieldrequired"><label for="selecttype_code">' . $langs->trans("TicketTypeRequest") . '</span></label></td><td>';
292
+        print '<tr><td class="titlefield"><span class="fieldrequired"><label for="selecttype_code">'.$langs->trans("TicketTypeRequest").'</span></label></td><td>';
293 293
         print $this->selectTypesTickets((GETPOST('type_code') ? GETPOST('type_code') : $this->type_code), 'type_code', '', '2');
294 294
         print '</td></tr>';
295 295
 
296 296
         // Category
297
-        print '<tr><td><span class="fieldrequired"><label for="selectcategory_code">' . $langs->trans("TicketCategory") . '</span></label></td><td>';
297
+        print '<tr><td><span class="fieldrequired"><label for="selectcategory_code">'.$langs->trans("TicketCategory").'</span></label></td><td>';
298 298
         print $this->selectCategoriesTickets((GETPOST('category_code') ? GETPOST('category_code') : $this->category_code), 'category_code', '', '2');
299 299
         print '</td></tr>';
300 300
 
301 301
         // Severity
302
-        print '<tr><td><span class="fieldrequired"><label for="selectseverity_code">' . $langs->trans("TicketSeverity") . '</span></label></td><td>';
302
+        print '<tr><td><span class="fieldrequired"><label for="selectseverity_code">'.$langs->trans("TicketSeverity").'</span></label></td><td>';
303 303
         print $this->selectSeveritiesTickets((GETPOST('severity_code') ? GETPOST('severity_code') : $this->severity_code), 'severity_code', '', '2');
304 304
         print '</td></tr>';
305 305
 
306 306
         // Notify thirdparty at creation
307 307
         if (empty($this->ispublic))
308 308
         {
309
-	        print '<tr><td><label for="notify_tiers_at_create">' . $langs->trans("TicketNotifyTiersAtCreation") . '</label></td><td>';
310
-        	print '<input type="checkbox" id="notify_tiers_at_create" name="notify_tiers_at_create"'.($this->withnotifytiersatcreate?' checked="checked"':'').'>';
309
+	        print '<tr><td><label for="notify_tiers_at_create">'.$langs->trans("TicketNotifyTiersAtCreation").'</label></td><td>';
310
+        	print '<input type="checkbox" id="notify_tiers_at_create" name="notify_tiers_at_create"'.($this->withnotifytiersatcreate ? ' checked="checked"' : '').'>';
311 311
         	print '</td></tr>';
312 312
         }
313 313
 
314 314
         // TITLE
315 315
         if ($this->withtitletopic) {
316
-            print '<tr><td><label for="subject"><span class="fieldrequired">' . $langs->trans("Subject") . '</span></label></td><td>';
316
+            print '<tr><td><label for="subject"><span class="fieldrequired">'.$langs->trans("Subject").'</span></label></td><td>';
317 317
 
318 318
             // Réponse à un ticket : affichage du titre du thread en readonly
319 319
             if ($this->withtopicreadonly) {
320
-                print $langs->trans('SubjectAnswerToTicket') . ' ' . $this->topic_title;
320
+                print $langs->trans('SubjectAnswerToTicket').' '.$this->topic_title;
321 321
                 print '</td></tr>';
322 322
             } else {
323 323
                 if ($this->withthreadid > 0) {
324
-                    $subject = $langs->trans('SubjectAnswerToTicket') . ' ' . $this->withthreadid . ' : ' . $this->topic_title . '';
324
+                    $subject = $langs->trans('SubjectAnswerToTicket').' '.$this->withthreadid.' : '.$this->topic_title.'';
325 325
                 }
326
-                print '<input class="text" size="50" id="subject" name="subject" value="' . (GETPOST('subject', 'alpha') ? GETPOST('subject', 'alpha') : $subject) . '" />';
326
+                print '<input class="text" size="50" id="subject" name="subject" value="'.(GETPOST('subject', 'alpha') ? GETPOST('subject', 'alpha') : $subject).'" />';
327 327
                 print '</td></tr>';
328 328
             }
329 329
         }
330 330
 
331 331
         // MESSAGE
332 332
         $msg = GETPOST('message', 'alpha') ? GETPOST('message', 'alpha') : '';
333
-        print '<tr><td><label for="message"><span class="fieldrequired">' . $langs->trans("Message") . '</span></label></td><td>';
333
+        print '<tr><td><label for="message"><span class="fieldrequired">'.$langs->trans("Message").'</span></label></td><td>';
334 334
 
335 335
         // If public form, display more information
336 336
         if ($this->ispublic) {
337
-            print '<div class="warning">' . ($conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')) . '</div>';
337
+            print '<div class="warning">'.($conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')).'</div>';
338 338
         }
339
-        include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
339
+        include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
340 340
         $uselocalbrowser = true;
341 341
         $doleditor = new DolEditor('message', GETPOST('message', 'alpha'), '100%', 250, 'dolibarr_details', 'In', true, $uselocalbrowser);
342 342
         $doleditor->Create();
@@ -361,33 +361,33 @@  discard block
 block discarded – undo
361 361
             }
362 362
 
363 363
             $out .= '<tr>';
364
-            $out .= '<td width="180">' . $langs->trans("MailFile") . '</td>';
364
+            $out .= '<td width="180">'.$langs->trans("MailFile").'</td>';
365 365
             $out .= '<td colspan="2">';
366 366
             // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
367
-            $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">' . "\n";
367
+            $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
368 368
             $out .= '<script type="text/javascript" language="javascript">';
369 369
             $out .= 'jQuery(document).ready(function () {';
370 370
             $out .= '    jQuery(".removedfile").click(function() {';
371 371
             $out .= '        jQuery(".removedfilehidden").val(jQuery(this).val());';
372 372
             $out .= '    });';
373 373
             $out .= '})';
374
-            $out .= '</script>' . "\n";
374
+            $out .= '</script>'."\n";
375 375
             if (count($listofpaths)) {
376 376
                 foreach ($listofpaths as $key => $val) {
377
-                    $out .= '<div id="attachfile_' . $key . '">';
378
-                    $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key];
377
+                    $out .= '<div id="attachfile_'.$key.'">';
378
+                    $out .= img_mime($listofnames[$key]).' '.$listofnames[$key];
379 379
                     if (!$this->withfilereadonly) {
380
-                        $out .= ' <input type="image" style="border: 0px;" src="' . DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/delete.png" value="' . ($key + 1) . '" class="removedfile" id="removedfile_' . $key . '" name="removedfile_' . $key . '" />';
380
+                        $out .= ' <input type="image" style="border: 0px;" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/delete.png" value="'.($key + 1).'" class="removedfile" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
381 381
                     }
382 382
                     $out .= '<br></div>';
383 383
                 }
384 384
             } else {
385
-                $out .= $langs->trans("NoAttachedFiles") . '<br>';
385
+                $out .= $langs->trans("NoAttachedFiles").'<br>';
386 386
             }
387 387
             if ($this->withfile == 2) { // Can add other files
388
-                $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="' . $langs->trans("Upload") . '" />';
388
+                $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
389 389
                 $out .= ' ';
390
-                $out .= '<input type="submit" class="button" id="addfile" name="addfile" value="' . $langs->trans("MailingAddFile") . '" />';
390
+                $out .= '<input type="submit" class="button" id="addfile" name="addfile" value="'.$langs->trans("MailingAddFile").'" />';
391 391
             }
392 392
             $out .= "</td></tr>\n";
393 393
 
@@ -406,11 +406,11 @@  discard block
 block discarded – undo
406 406
         if ($withdolfichehead) dol_fiche_end();
407 407
 
408 408
         print '<center>';
409
-        print '<input class="button" type="submit" name="add_ticket" value="' . $langs->trans(($this->withthreadid > 0 ? "SendResponse" : "NewTicket")) . '" />';
409
+        print '<input class="button" type="submit" name="add_ticket" value="'.$langs->trans(($this->withthreadid > 0 ? "SendResponse" : "NewTicket")).'" />';
410 410
 
411 411
         if ($this->withcancel) {
412 412
             print " &nbsp; &nbsp; ";
413
-            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"" . $langs->trans("Cancel") . "\">";
413
+            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"".$langs->trans("Cancel")."\">";
414 414
         }
415 415
         print "</center>\n";
416 416
 
@@ -431,13 +431,13 @@  discard block
 block discarded – undo
431 431
      *      @param	string	$morecss	More CSS
432 432
      *      @return void
433 433
      */
434
-    public function selectTypesTickets($selected = '', $htmlname = 'tickettype', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss='')
434
+    public function selectTypesTickets($selected = '', $htmlname = 'tickettype', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss = '')
435 435
     {
436 436
         global $langs, $user;
437 437
 
438 438
         $ticketstat = new Ticket($this->db);
439 439
 
440
-        dol_syslog(get_class($this) . "::select_types_tickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
440
+        dol_syslog(get_class($this)."::select_types_tickets ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
441 441
 
442 442
         $filterarray = array();
443 443
 
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 
448 448
         $ticketstat->loadCacheTypesTickets();
449 449
 
450
-        print '<select id="select' . $htmlname . '" class="flat minwidth100'.($morecss?' '.$morecss:'').'" name="' . $htmlname . '">';
450
+        print '<select id="select'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
451 451
         if ($empty) {
452 452
             print '<option value="">&nbsp;</option>';
453 453
         }
@@ -465,19 +465,19 @@  discard block
 block discarded – undo
465 465
                 }
466 466
 
467 467
                 if ($format == 0) {
468
-                    print '<option value="' . $id . '"';
468
+                    print '<option value="'.$id.'"';
469 469
                 }
470 470
 
471 471
                 if ($format == 1) {
472
-                    print '<option value="' . $arraytypes['code'] . '"';
472
+                    print '<option value="'.$arraytypes['code'].'"';
473 473
                 }
474 474
 
475 475
                 if ($format == 2) {
476
-                    print '<option value="' . $arraytypes['code'] . '"';
476
+                    print '<option value="'.$arraytypes['code'].'"';
477 477
                 }
478 478
 
479 479
                 if ($format == 3) {
480
-                    print '<option value="' . $id . '"';
480
+                    print '<option value="'.$id.'"';
481 481
                 }
482 482
 
483 483
                 // Si selected est text, on compare avec code, sinon avec id
@@ -531,13 +531,13 @@  discard block
 block discarded – undo
531 531
      *      @param	string	$morecss	More CSS
532 532
      *      @return void
533 533
      */
534
-    public function selectCategoriesTickets($selected = '', $htmlname = 'ticketcategory', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss='')
534
+    public function selectCategoriesTickets($selected = '', $htmlname = 'ticketcategory', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss = '')
535 535
     {
536 536
         global $langs, $user;
537 537
 
538 538
         $ticketstat = new Ticket($this->db);
539 539
 
540
-        dol_syslog(get_class($this) . "::selectCategoryTickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
540
+        dol_syslog(get_class($this)."::selectCategoryTickets ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
541 541
 
542 542
         $filterarray = array();
543 543
 
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
 
548 548
         $ticketstat->loadCacheCategoriesTickets();
549 549
 
550
-        print '<select id="select' . $htmlname . '" class="flat minwidth100'.($morecss?' '.$morecss:'').'" name="' . $htmlname . '">';
550
+        print '<select id="select'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
551 551
         if ($empty) {
552 552
             print '<option value="">&nbsp;</option>';
553 553
         }
@@ -565,19 +565,19 @@  discard block
 block discarded – undo
565 565
                 }
566 566
 
567 567
                 if ($format == 0) {
568
-                    print '<option value="' . $id . '"';
568
+                    print '<option value="'.$id.'"';
569 569
                 }
570 570
 
571 571
                 if ($format == 1) {
572
-                    print '<option value="' . $arraycategories['code'] . '"';
572
+                    print '<option value="'.$arraycategories['code'].'"';
573 573
                 }
574 574
 
575 575
                 if ($format == 2) {
576
-                    print '<option value="' . $arraycategories['code'] . '"';
576
+                    print '<option value="'.$arraycategories['code'].'"';
577 577
                 }
578 578
 
579 579
                 if ($format == 3) {
580
-                    print '<option value="' . $id . '"';
580
+                    print '<option value="'.$id.'"';
581 581
                 }
582 582
 
583 583
                 // Si selected est text, on compare avec code, sinon avec id
@@ -632,13 +632,13 @@  discard block
 block discarded – undo
632 632
      *      @param	string	$morecss	More CSS
633 633
      *      @return void
634 634
      */
635
-    public function selectSeveritiesTickets($selected = '', $htmlname = 'ticketseverity', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss='')
635
+    public function selectSeveritiesTickets($selected = '', $htmlname = 'ticketseverity', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0, $morecss = '')
636 636
     {
637 637
         global $langs, $user;
638 638
 
639 639
         $ticketstat = new Ticket($this->db);
640 640
 
641
-        dol_syslog(get_class($this) . "::selectSeveritiesTickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
641
+        dol_syslog(get_class($this)."::selectSeveritiesTickets ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
642 642
 
643 643
         $filterarray = array();
644 644
 
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
 
649 649
         $ticketstat->loadCacheSeveritiesTickets();
650 650
 
651
-        print '<select id="select' . $htmlname . '" class="flat minwidth150'.($morecss?' '.$morecss:'').'" name="' . $htmlname . '">';
651
+        print '<select id="select'.$htmlname.'" class="flat minwidth150'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
652 652
         if ($empty) {
653 653
             print '<option value="">&nbsp;</option>';
654 654
         }
@@ -666,19 +666,19 @@  discard block
 block discarded – undo
666 666
                 }
667 667
 
668 668
                 if ($format == 0) {
669
-                    print '<option value="' . $id . '"';
669
+                    print '<option value="'.$id.'"';
670 670
                 }
671 671
 
672 672
                 if ($format == 1) {
673
-                    print '<option value="' . $arrayseverities['code'] . '"';
673
+                    print '<option value="'.$arrayseverities['code'].'"';
674 674
                 }
675 675
 
676 676
                 if ($format == 2) {
677
-                    print '<option value="' . $arrayseverities['code'] . '"';
677
+                    print '<option value="'.$arrayseverities['code'].'"';
678 678
                 }
679 679
 
680 680
                 if ($format == 3) {
681
-                    print '<option value="' . $id . '"';
681
+                    print '<option value="'.$id.'"';
682 682
                 }
683 683
 
684 684
                 // Si selected est text, on compare avec code, sinon avec id
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
         if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
761 761
             $newlang = $this->param['langsmodels'];
762 762
         }
763
-        if (! empty($newlang)) {
763
+        if (!empty($newlang)) {
764 764
             $outputlangs = new Translate("", $conf);
765 765
             $outputlangs->setDefaultLang($newlang);
766 766
             $outputlangs->load('other');
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
         // Example 1 : Adding jquery code
774 774
         print '<script type="text/javascript" language="javascript">
775 775
 		jQuery(document).ready(function() {
776
-			send_email=' . $send_email . ';
776
+			send_email=' . $send_email.';
777 777
 			if (send_email) {
778 778
 				jQuery(".email_line").show();
779 779
 			} else {
@@ -791,42 +791,42 @@  discard block
 block discarded – undo
791 791
         print '});
792 792
 		</script>';
793 793
 
794
-        print '<form method="post" name="ticket" enctype="multipart/form-data" action="' . $this->param["returnurl"] . '">';
795
-        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
796
-        print '<input type="hidden" name="action" value="' . $this->action . '">';
794
+        print '<form method="post" name="ticket" enctype="multipart/form-data" action="'.$this->param["returnurl"].'">';
795
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
796
+        print '<input type="hidden" name="action" value="'.$this->action.'">';
797 797
         foreach ($this->param as $key => $value) {
798
-            print '<input type="hidden" name="' . $key . '" value="' . $value . '">';
798
+            print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
799 799
         }
800 800
 
801 801
         // Get message template
802
-        $model_id=0;
802
+        $model_id = 0;
803 803
         if (array_key_exists('models_id', $this->param)) {
804
-            $model_id=$this->param["models_id"];
805
-            $arraydefaultmessage=$formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id);
804
+            $model_id = $this->param["models_id"];
805
+            $arraydefaultmessage = $formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id);
806 806
         }
807 807
 
808 808
         $result = $formmail->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
809
-        if ($result<0) {
809
+        if ($result < 0) {
810 810
             setEventMessages($this->error, $this->errors, 'errors');
811 811
         }
812
-        $modelmail_array=array();
812
+        $modelmail_array = array();
813 813
         foreach ($formmail->lines_model as $line) {
814
-            $modelmail_array[$line->id]=$line->label;
814
+            $modelmail_array[$line->id] = $line->label;
815 815
         }
816 816
 
817
-        print '<table class="border"  width="' . $width . '">';
817
+        print '<table class="border"  width="'.$width.'">';
818 818
 
819 819
 
820 820
         // External users can't send message email
821 821
         if ($user->rights->ticket->write && !$user->socid) {
822 822
             print '<tr><td width="30%"></td><td colspan="2">';
823
-            $checkbox_selected = ( GETPOST('send_email') == "1" ? ' checked' : '');
823
+            $checkbox_selected = (GETPOST('send_email') == "1" ? ' checked' : '');
824 824
             print '<input type="checkbox" name="send_email" value="1" id="send_msg_email" '.$checkbox_selected.'/> ';
825
-            print '<label for="send_msg_email">' . $langs->trans('SendMessageByEmail') . '</label>';
825
+            print '<label for="send_msg_email">'.$langs->trans('SendMessageByEmail').'</label>';
826 826
             print '</td></tr>';
827 827
 
828 828
             // Zone to select its email template
829
-            if (count($modelmail_array)>0) {
829
+            if (count($modelmail_array) > 0) {
830 830
                 print '<tr class="email_line"><td></td><td colspan="2"><div style="padding: 3px 0 3px 0">'."\n";
831 831
                 print $langs->trans('SelectMailModel').': '.$formmail->selectarray('modelmailselected', $modelmail_array, $this->param['models_id'], 1);
832 832
                 if ($user->admin) {
@@ -841,32 +841,32 @@  discard block
 block discarded – undo
841 841
             // Substitution array
842 842
             if ($this->withsubstit) {
843 843
                 print '<tr class="email_line"><td></td><td colspan="2">';
844
-                $help="";
844
+                $help = "";
845 845
                 foreach ($this->substit as $key => $val) {
846
-                    $help.=$key.' -> '.$langs->trans($val).'<br>';
846
+                    $help .= $key.' -> '.$langs->trans($val).'<br>';
847 847
                 }
848 848
                 print $form->textwithpicto($langs->trans("TicketMessageSubstitutionReplacedByGenericValues"), $help);
849 849
                 print "</td></tr>";
850 850
             }
851 851
 
852
-            if (! $user->socid) {
852
+            if (!$user->socid) {
853 853
                 print '<tr><td width="30%"></td><td>';
854
-                $checkbox_selected = ( GETPOST('private_message') == "1" ? ' checked' : '');
854
+                $checkbox_selected = (GETPOST('private_message') == "1" ? ' checked' : '');
855 855
                 print '<input type="checkbox" name="private_message" value="1" id="private_message" '.$checkbox_selected.'/> ';
856
-                print '<label for="private_message">' . $langs->trans('MarkMessageAsPrivate') . '</label>';
856
+                print '<label for="private_message">'.$langs->trans('MarkMessageAsPrivate').'</label>';
857 857
                 print '</td><td align="center">';
858 858
                 print $form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help');
859 859
                 print '</td></tr>';
860 860
             }
861 861
 
862 862
 
863
-            print '<tr class="email_line"><td width=20%">' . $langs->trans('Subject') . '</td>';
863
+            print '<tr class="email_line"><td width=20%">'.$langs->trans('Subject').'</td>';
864 864
             $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
865
-            print '<td colspan="2"><input type="text" class="text" size="80" name="subject" value="[' . $label_title . ' - ticket #' . $this->track_id . '] ' . $langs->trans('TicketNewMessage') . '" />';
865
+            print '<td colspan="2"><input type="text" class="text" size="80" name="subject" value="['.$label_title.' - ticket #'.$this->track_id.'] '.$langs->trans('TicketNewMessage').'" />';
866 866
             print '</td></tr>';
867 867
 
868 868
             // Destinataires
869
-            print '<tr class="email_line"><td>' . $langs->trans('MailRecipients') . '</td><td colspan="2">';
869
+            print '<tr class="email_line"><td>'.$langs->trans('MailRecipients').'</td><td colspan="2">';
870 870
             $ticketstat = new Ticket($this->db);
871 871
             $res = $ticketstat->fetch('', '', $this->track_id);
872 872
             if ($res) {
@@ -878,13 +878,13 @@  discard block
 block discarded – undo
878 878
                 if (is_array($contacts) && count($contacts) > 0) {
879 879
                     foreach ($contacts as $key => $info_sendto) {
880 880
                         if ($info_sendto['email'] != '') {
881
-                            $sendto[] = dol_escape_htmltag(trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . "> (" . $info_sendto['libelle'] . ")");
881
+                            $sendto[] = dol_escape_htmltag(trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email']."> (".$info_sendto['libelle'].")");
882 882
                         }
883 883
                     }
884 884
                 }
885 885
 
886 886
                 if ($ticketstat->origin_email && !in_array($this->dao->origin_email, $sendto)) {
887
-                    $sendto[] = $ticketstat->origin_email . "(origin)";
887
+                    $sendto[] = $ticketstat->origin_email."(origin)";
888 888
                 }
889 889
 
890 890
                 if ($ticketstat->fk_soc > 0) {
@@ -892,19 +892,19 @@  discard block
 block discarded – undo
892 892
                     $ticketstat->fetch_thirdparty();
893 893
 
894 894
                     if (is_array($ticketstat->thirdparty->email) && !in_array($ticketstat->thirdparty->email, $sendto)) {
895
-                        $sendto[] = $ticketstat->thirdparty->email . '(' . $langs->trans('Customer') . ')';
895
+                        $sendto[] = $ticketstat->thirdparty->email.'('.$langs->trans('Customer').')';
896 896
                     }
897 897
                 }
898 898
 
899 899
                 if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS) {
900
-                    $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO . '(generic email)';
900
+                    $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO.'(generic email)';
901 901
                 }
902 902
 
903 903
                 // Print recipient list
904 904
                 if (is_array($sendto) && count($sendto) > 0) {
905 905
                     print implode(', ', $sendto);
906 906
                 } else {
907
-                    print '<div class="warning">' . $langs->trans('WarningNoEMailsAdded') . ' ' . $langs->trans('TicketGoIntoContactTab') . '</div>';
907
+                    print '<div class="warning">'.$langs->trans('WarningNoEMailsAdded').' '.$langs->trans('TicketGoIntoContactTab').'</div>';
908 908
                 }
909 909
             }
910 910
             print '</td></tr>';
@@ -914,10 +914,10 @@  discard block
 block discarded – undo
914 914
         // External users can't send message email
915 915
         if ($user->rights->ticket->write && !$user->socid) {
916 916
             $mail_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKET_MESSAGE_MAIL_INTRO;
917
-            print '<tr class="email_line"><td><label for="mail_intro">' . $langs->trans("TicketMessageMailIntro") . '</label>';
917
+            print '<tr class="email_line"><td><label for="mail_intro">'.$langs->trans("TicketMessageMailIntro").'</label>';
918 918
 
919 919
             print '</td><td>';
920
-            include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
920
+            include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
921 921
             $uselocalbrowser = true;
922 922
 
923 923
             $doleditor = new DolEditor('mail_intro', $mail_intro, '100%', 140, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
@@ -929,11 +929,11 @@  discard block
 block discarded – undo
929 929
         }
930 930
 
931 931
         // MESSAGE
932
-        $defaultmessage="";
932
+        $defaultmessage = "";
933 933
         if (is_array($arraydefaultmessage) && count($arraydefaultmessage) > 0 && $arraydefaultmessage->content) {
934
-            $defaultmessage=$arraydefaultmessage->content;
934
+            $defaultmessage = $arraydefaultmessage->content;
935 935
         }
936
-        $defaultmessage=str_replace('\n', "\n", $defaultmessage);
936
+        $defaultmessage = str_replace('\n', "\n", $defaultmessage);
937 937
 
938 938
         // Deal with format differences between message and signature (text / HTML)
939 939
         if (dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__SIGNATURE__'])) {
@@ -941,17 +941,17 @@  discard block
 block discarded – undo
941 941
         } elseif (!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__SIGNATURE__'])) {
942 942
             $defaultmessage = dol_nl2br($defaultmessage);
943 943
         }
944
-        if (isset($_POST["message"]) &&  ! $_POST['modelselected']) {
945
-            $defaultmessage=GETPOST('message');
944
+        if (isset($_POST["message"]) && !$_POST['modelselected']) {
945
+            $defaultmessage = GETPOST('message');
946 946
         } else {
947
-            $defaultmessage=make_substitutions($defaultmessage, $this->substit);
947
+            $defaultmessage = make_substitutions($defaultmessage, $this->substit);
948 948
             // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
949
-            $defaultmessage=preg_replace("/^(<br>)+/", "", $defaultmessage);
950
-            $defaultmessage=preg_replace("/^\n+/", "", $defaultmessage);
949
+            $defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
950
+            $defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
951 951
         }
952 952
 
953
-        print '<tr><td><label for="message"><span class="fieldrequired">' . $langs->trans("Message") . '</span></label></td><td>';
954
-        include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
953
+        print '<tr><td><label for="message"><span class="fieldrequired">'.$langs->trans("Message").'</span></label></td><td>';
954
+        include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
955 955
         $doleditor = new DolEditor('message', $defaultmessage, '100%', 350, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
956 956
         $doleditor->Create();
957 957
         print '</td><td align="center">';
@@ -965,10 +965,10 @@  discard block
 block discarded – undo
965 965
         // External users can't send message email
966 966
         if ($user->rights->ticket->write && !$user->socid) {
967 967
             $mail_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE;
968
-            print '<tr class="email_line"><td><label for="mail_intro">' . $langs->trans("TicketMessageMailSignature") . '</label>';
968
+            print '<tr class="email_line"><td><label for="mail_intro">'.$langs->trans("TicketMessageMailSignature").'</label>';
969 969
 
970 970
             print '</td><td>';
971
-            include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
971
+            include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
972 972
             $doleditor = new DolEditor('mail_signature', $mail_signature, '100%', 150, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
973 973
             $doleditor->Create();
974 974
             print '</td><td align="center">';
@@ -979,33 +979,33 @@  discard block
 block discarded – undo
979 979
         // Attached files
980 980
         if (!empty($this->withfile)) {
981 981
             $out .= '<tr>';
982
-            $out .= '<td width="180">' . $langs->trans("MailFile") . '</td>';
982
+            $out .= '<td width="180">'.$langs->trans("MailFile").'</td>';
983 983
             $out .= '<td colspan="2">';
984 984
             // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
985
-            $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">' . "\n";
985
+            $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
986 986
             $out .= '<script type="text/javascript" language="javascript">';
987 987
             $out .= 'jQuery(document).ready(function () {';
988 988
             $out .= '    jQuery(".removedfile").click(function() {';
989 989
             $out .= '        jQuery(".removedfilehidden").val(jQuery(this).val());';
990 990
             $out .= '    });';
991 991
             $out .= '})';
992
-            $out .= '</script>' . "\n";
992
+            $out .= '</script>'."\n";
993 993
             if (count($listofpaths)) {
994 994
                 foreach ($listofpaths as $key => $val) {
995
-                    $out .= '<div id="attachfile_' . $key . '">';
996
-                    $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key];
995
+                    $out .= '<div id="attachfile_'.$key.'">';
996
+                    $out .= img_mime($listofnames[$key]).' '.$listofnames[$key];
997 997
                     if (!$this->withfilereadonly) {
998
-                        $out .= ' <input type="image" style="border: 0px;" src="' . DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/delete.png" value="' . ($key + 1) . '" class="removedfile" id="removedfile_' . $key . '" name="removedfile_' . $key . '" />';
998
+                        $out .= ' <input type="image" style="border: 0px;" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/delete.png" value="'.($key + 1).'" class="removedfile" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
999 999
                     }
1000 1000
                     $out .= '<br></div>';
1001 1001
                 }
1002 1002
             } else {
1003
-                $out .= $langs->trans("NoAttachedFiles") . '<br>';
1003
+                $out .= $langs->trans("NoAttachedFiles").'<br>';
1004 1004
             }
1005 1005
             if ($this->withfile == 2) { // Can add other files
1006
-                $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="' . $langs->trans("Upload") . '" />';
1006
+                $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
1007 1007
                 $out .= ' ';
1008
-                $out .= '<input type="submit" class="button" id="' . $addfileaction . '" name="' . $addfileaction . '" value="' . $langs->trans("MailingAddFile") . '" />';
1008
+                $out .= '<input type="submit" class="button" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
1009 1009
             }
1010 1010
             $out .= "</td></tr>\n";
1011 1011
 
@@ -1014,11 +1014,11 @@  discard block
 block discarded – undo
1014 1014
 
1015 1015
         print '<tr><td colspan="3">';
1016 1016
         print '<center>';
1017
-        print '<input class="button" type="submit" name="btn_add_message" value="' . $langs->trans("AddMessage") . '" />';
1017
+        print '<input class="button" type="submit" name="btn_add_message" value="'.$langs->trans("AddMessage").'" />';
1018 1018
 
1019 1019
         if ($this->withcancel) {
1020 1020
             print " &nbsp; &nbsp; ";
1021
-            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"" . $langs->trans("Cancel") . "\">";
1021
+            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"".$langs->trans("Cancel")."\">";
1022 1022
         }
1023 1023
         print "</center>\n";
1024 1024
         print '</td></tr>';
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -147,7 +147,9 @@  discard block
 block discarded – undo
147 147
 
148 148
         print "\n<!-- Begin form TICKETSUP -->\n";
149 149
 
150
-        if ($withdolfichehead) dol_fiche_head(null, 'card', '', 0, '');
150
+        if ($withdolfichehead) {
151
+            dol_fiche_head(null, 'card', '', 0, '');
152
+        }
151 153
 
152 154
         print '<form method="POST" '.($withdolfichehead?'':'style="margin-bottom: 30px;" ').'name="ticket" id="form_create_ticket" enctype="multipart/form-data" action="' . $this->param["returnurl"] . '">';
153 155
         print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
@@ -403,7 +405,9 @@  discard block
 block discarded – undo
403 405
 
404 406
         print '</table>';
405 407
 
406
-        if ($withdolfichehead) dol_fiche_end();
408
+        if ($withdolfichehead) {
409
+            dol_fiche_end();
410
+        }
407 411
 
408 412
         print '<center>';
409 413
         print '<input class="button" type="submit" name="add_ticket" value="' . $langs->trans(($this->withthreadid > 0 ? "SendResponse" : "NewTicket")) . '" />';
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/link.class.php 3 patches
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -29,19 +29,19 @@  discard block
 block discarded – undo
29 29
 class Link extends CommonObject
30 30
 {
31 31
     /**
32
-	 * @var string ID to identify managed object
33
-	 */
34
-	public $element = 'link';
32
+     * @var string ID to identify managed object
33
+     */
34
+    public $element = 'link';
35 35
 
36 36
     /**
37
-	 * @var string Name of table without prefix where object is stored
38
-	 */
39
-	public $table_element = 'links';
37
+     * @var string Name of table without prefix where object is stored
38
+     */
39
+    public $table_element = 'links';
40 40
 
41 41
     /**
42
-	 * @var int Entity
43
-	 */
44
-	public $entity;
42
+     * @var int Entity
43
+     */
44
+    public $entity;
45 45
 
46 46
     public $datea;
47 47
     public $url;
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
                 return 1;
344 344
             }
345 345
             else
346
-			{
346
+            {
347 347
                 return 0;
348 348
             }
349 349
         } else {
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -72,11 +72,11 @@  discard block
 block discarded – undo
72 72
      *    @param	User	$user       Object of user that ask creation
73 73
      *    @return   int         		>= 0 if OK, < 0 if KO
74 74
      */
75
-    public function create($user='')
75
+    public function create($user = '')
76 76
     {
77
-        global $langs,$conf;
77
+        global $langs, $conf;
78 78
 
79
-        $error=0;
79
+        $error = 0;
80 80
         $langs->load("errors");
81 81
         // Clean parameters
82 82
         if (empty($this->label)) {
@@ -99,34 +99,34 @@  discard block
 block discarded – undo
99 99
 
100 100
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."links (entity, datea, url, label, objecttype, objectid)";
101 101
         $sql .= " VALUES ('".$conf->entity."', '".$this->db->idate($this->datea)."'";
102
-        $sql .= ", '" . $this->db->escape($this->url) . "'";
103
-        $sql .= ", '" . $this->db->escape($this->label) . "'";
104
-        $sql .= ", '" . $this->db->escape($this->objecttype) . "'";
105
-        $sql .= ", " . $this->objectid . ")";
102
+        $sql .= ", '".$this->db->escape($this->url)."'";
103
+        $sql .= ", '".$this->db->escape($this->label)."'";
104
+        $sql .= ", '".$this->db->escape($this->objecttype)."'";
105
+        $sql .= ", ".$this->objectid.")";
106 106
 
107 107
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
108 108
         $result = $this->db->query($sql);
109 109
         if ($result) {
110
-            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "links");
110
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."links");
111 111
 
112 112
             if ($this->id > 0) {
113 113
                 // Call trigger
114
-                $result=$this->call_trigger('LINK_CREATE',$user);
114
+                $result = $this->call_trigger('LINK_CREATE', $user);
115 115
                 if ($result < 0) $error++;
116 116
                 // End call triggers
117 117
             } else {
118 118
                 $error++;
119 119
             }
120 120
 
121
-            if (! $error)
121
+            if (!$error)
122 122
             {
123
-                dol_syslog(get_class($this)."::Create success id=" . $this->id);
123
+                dol_syslog(get_class($this)."::Create success id=".$this->id);
124 124
                 $this->db->commit();
125 125
                 return $this->id;
126 126
             }
127 127
             else
128 128
             {
129
-                dol_syslog(get_class($this)."::Create echec update " . $this->error, LOG_ERR);
129
+                dol_syslog(get_class($this)."::Create echec update ".$this->error, LOG_ERR);
130 130
                 $this->db->rollback();
131 131
                 return -3;
132 132
             }
@@ -136,13 +136,13 @@  discard block
 block discarded – undo
136 136
             if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
137 137
             {
138 138
 
139
-                $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);
140
-                $result=-1;
139
+                $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name);
140
+                $result = -1;
141 141
             }
142 142
             else
143 143
             {
144
-                $this->error=$this->db->lasterror();
145
-                $result=-2;
144
+                $this->error = $this->db->lasterror();
145
+                $result = -2;
146 146
             }
147 147
             $this->db->rollback();
148 148
             return $result;
@@ -156,15 +156,15 @@  discard block
 block discarded – undo
156 156
      *      @param  int		$call_trigger    			0=no, 1=yes
157 157
      *      @return int  			           			<0 if KO, >=0 if OK
158 158
      */
159
-    public function update($user='', $call_trigger=1)
159
+    public function update($user = '', $call_trigger = 1)
160 160
     {
161
-        global $langs,$conf;
161
+        global $langs, $conf;
162 162
         require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
163 163
 
164 164
         $langs->load("errors");
165
-        $error=0;
165
+        $error = 0;
166 166
 
167
-        dol_syslog(get_class($this)."::Update id = " . $this->id . " call_trigger = " . $call_trigger);
167
+        dol_syslog(get_class($this)."::Update id = ".$this->id." call_trigger = ".$call_trigger);
168 168
 
169 169
         // Check parameters
170 170
         if (empty($this->url))
@@ -174,37 +174,37 @@  discard block
 block discarded – undo
174 174
         }
175 175
 
176 176
         // Clean parameters
177
-        $this->url       = clean_url($this->url,1);
177
+        $this->url       = clean_url($this->url, 1);
178 178
         if (empty($this->label)) $this->label = basename($this->url);
179 179
         $this->label     = trim($this->label);
180 180
 
181 181
 
182 182
         $this->db->begin();
183 183
 
184
-        $sql  = "UPDATE " . MAIN_DB_PREFIX . "links SET ";
185
-        $sql .= "entity = '" . $conf->entity ."'";
186
-        $sql .= ", datea = '" . $this->db->idate(dol_now()) . "'";
187
-        $sql .= ", url = '" . $this->db->escape($this->url) . "'";
188
-        $sql .= ", label = '" . $this->db->escape($this->label) . "'";
189
-        $sql .= ", objecttype = '" . $this->db->escape($this->objecttype) . "'";
190
-        $sql .= ", objectid = " . $this->objectid;
191
-        $sql .= " WHERE rowid = " . $this->id;
184
+        $sql  = "UPDATE ".MAIN_DB_PREFIX."links SET ";
185
+        $sql .= "entity = '".$conf->entity."'";
186
+        $sql .= ", datea = '".$this->db->idate(dol_now())."'";
187
+        $sql .= ", url = '".$this->db->escape($this->url)."'";
188
+        $sql .= ", label = '".$this->db->escape($this->label)."'";
189
+        $sql .= ", objecttype = '".$this->db->escape($this->objecttype)."'";
190
+        $sql .= ", objectid = ".$this->objectid;
191
+        $sql .= " WHERE rowid = ".$this->id;
192 192
 
193
-        dol_syslog(get_class($this)."::update sql = " .$sql);
193
+        dol_syslog(get_class($this)."::update sql = ".$sql);
194 194
         $resql = $this->db->query($sql);
195 195
         if ($resql)
196 196
         {
197 197
             if ($call_trigger)
198 198
             {
199 199
                 // Call trigger
200
-                $result=$this->call_trigger('LINK_MODIFY',$user);
200
+                $result = $this->call_trigger('LINK_MODIFY', $user);
201 201
                 if ($result < 0) $error++;
202 202
                 // End call triggers
203 203
             }
204 204
 
205
-            if (! $error)
205
+            if (!$error)
206 206
             {
207
-                dol_syslog(get_class($this) . "::Update success");
207
+                dol_syslog(get_class($this)."::Update success");
208 208
                 $this->db->commit();
209 209
                 return 1;
210 210
             } else {
@@ -219,12 +219,12 @@  discard block
 block discarded – undo
219 219
             {
220 220
                 // Doublon
221 221
                 $this->error = $langs->trans("ErrorDuplicateField");
222
-                $result =  -1;
222
+                $result = -1;
223 223
             }
224 224
             else
225 225
             {
226
-                $this->error = $langs->trans("Error sql = " . $sql);
227
-                $result =  -2;
226
+                $this->error = $langs->trans("Error sql = ".$sql);
227
+                $result = -2;
228 228
             }
229 229
             $this->db->rollback();
230 230
             return $result;
@@ -241,18 +241,18 @@  discard block
 block discarded – undo
241 241
      *  @param  string  $sortorder  sort order
242 242
      *  @return int                 1 if ok, 0 if no records, -1 if error
243 243
      **/
244
-    public function fetchAll(&$links, $objecttype, $objectid, $sortfield=null, $sortorder=null)
244
+    public function fetchAll(&$links, $objecttype, $objectid, $sortfield = null, $sortorder = null)
245 245
     {
246 246
         global $conf;
247 247
 
248
-        $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM " . MAIN_DB_PREFIX . "links";
249
-        $sql .= " WHERE objecttype = '" . $objecttype . "' AND objectid = " . $objectid;
250
-        if ($conf->entity != 0) $sql .= " AND entity = " . $conf->entity;
248
+        $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM ".MAIN_DB_PREFIX."links";
249
+        $sql .= " WHERE objecttype = '".$objecttype."' AND objectid = ".$objectid;
250
+        if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity;
251 251
         if ($sortfield) {
252 252
             if (empty($sortorder)) {
253 253
                 $sortorder = "ASC";
254 254
             }
255
-            $sql .= " ORDER BY " . $sortfield . " " . $sortorder;
255
+            $sql .= " ORDER BY ".$sortfield." ".$sortorder;
256 256
         }
257 257
 
258 258
         dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
         if ($resql)
261 261
         {
262 262
             $num = $this->db->num_rows($resql);
263
-            dol_syslog(get_class($this)."::fetchAll " . $num . "records", LOG_DEBUG);
263
+            dol_syslog(get_class($this)."::fetchAll ".$num."records", LOG_DEBUG);
264 264
             if ($num > 0)
265 265
             {
266 266
                 while ($obj = $this->db->fetch_object($resql))
@@ -296,9 +296,9 @@  discard block
 block discarded – undo
296 296
     {
297 297
         global $conf;
298 298
 
299
-        $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "links";
300
-        $sql .= " WHERE objecttype = '" . $objecttype . "' AND objectid = " . $objectid;
301
-        if ($conf->entity != 0) $sql .= " AND entity = " . $conf->entity;
299
+        $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."links";
300
+        $sql .= " WHERE objecttype = '".$objecttype."' AND objectid = ".$objectid;
301
+        if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity;
302 302
 
303 303
         $resql = $db->query($sql);
304 304
         if ($resql)
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
      *  @param 	int		$rowid 		Id of link to load
316 316
      *  @return int 				1 if ok, 0 if no record found, -1 if error
317 317
      **/
318
-    public function fetch($rowid=null)
318
+    public function fetch($rowid = null)
319 319
     {
320 320
         global $conf;
321 321
 
@@ -323,15 +323,15 @@  discard block
 block discarded – undo
323 323
             $rowid = $this->id;
324 324
         }
325 325
 
326
-        $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM " . MAIN_DB_PREFIX . "links";
327
-        $sql .= " WHERE rowid = " . $rowid;
328
-        if($conf->entity != 0) $sql .= " AND entity = " . $conf->entity;
326
+        $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM ".MAIN_DB_PREFIX."links";
327
+        $sql .= " WHERE rowid = ".$rowid;
328
+        if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity;
329 329
 
330 330
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
331 331
         $resql = $this->db->query($sql);
332 332
         if ($resql)
333 333
         {
334
-            if($this->db->num_rows($resql) > 0)
334
+            if ($this->db->num_rows($resql) > 0)
335 335
             {
336 336
                 $obj = $this->db->fetch_object($resql);
337 337
                 $this->entity = $obj->entity;
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
                 return 0;
348 348
             }
349 349
         } else {
350
-            $this->error=$this->db->lasterror();
350
+            $this->error = $this->db->lasterror();
351 351
             return -1;
352 352
         }
353 353
     }
@@ -365,24 +365,24 @@  discard block
 block discarded – undo
365 365
         $error = 0;
366 366
 
367 367
         // Call trigger
368
-        $result=$this->call_trigger('LINK_DELETE',$user);
368
+        $result = $this->call_trigger('LINK_DELETE', $user);
369 369
         if ($result < 0) return -1;
370 370
         // End call triggers
371 371
 
372 372
         $this->db->begin();
373 373
 
374 374
         // Remove link
375
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "links";
376
-        $sql.= " WHERE rowid = " . $this->id;
375
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."links";
376
+        $sql .= " WHERE rowid = ".$this->id;
377 377
 
378 378
         dol_syslog(get_class($this)."::delete", LOG_DEBUG);
379
-        if (! $this->db->query($sql))
379
+        if (!$this->db->query($sql))
380 380
         {
381 381
             $error++;
382 382
             $this->error = $this->db->lasterror();
383 383
         }
384 384
 
385
-        if (! $error) {
385
+        if (!$error) {
386 386
             $this->db->commit();
387 387
 
388 388
             return 1;
Please login to merge, or discard this patch.
Braces   +30 added lines, -20 removed lines patch added patch discarded remove patch
@@ -112,7 +112,9 @@  discard block
 block discarded – undo
112 112
             if ($this->id > 0) {
113 113
                 // Call trigger
114 114
                 $result=$this->call_trigger('LINK_CREATE',$user);
115
-                if ($result < 0) $error++;
115
+                if ($result < 0) {
116
+                    $error++;
117
+                }
116 118
                 // End call triggers
117 119
             } else {
118 120
                 $error++;
@@ -123,23 +125,20 @@  discard block
 block discarded – undo
123 125
                 dol_syslog(get_class($this)."::Create success id=" . $this->id);
124 126
                 $this->db->commit();
125 127
                 return $this->id;
126
-            }
127
-            else
128
+            } else
128 129
             {
129 130
                 dol_syslog(get_class($this)."::Create echec update " . $this->error, LOG_ERR);
130 131
                 $this->db->rollback();
131 132
                 return -3;
132 133
             }
133
-        }
134
-        else
134
+        } else
135 135
         {
136 136
             if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
137 137
             {
138 138
 
139 139
                 $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);
140 140
                 $result=-1;
141
-            }
142
-            else
141
+            } else
143 142
             {
144 143
                 $this->error=$this->db->lasterror();
145 144
                 $result=-2;
@@ -175,7 +174,9 @@  discard block
 block discarded – undo
175 174
 
176 175
         // Clean parameters
177 176
         $this->url       = clean_url($this->url,1);
178
-        if (empty($this->label)) $this->label = basename($this->url);
177
+        if (empty($this->label)) {
178
+            $this->label = basename($this->url);
179
+        }
179 180
         $this->label     = trim($this->label);
180 181
 
181 182
 
@@ -198,7 +199,9 @@  discard block
 block discarded – undo
198 199
             {
199 200
                 // Call trigger
200 201
                 $result=$this->call_trigger('LINK_MODIFY',$user);
201
-                if ($result < 0) $error++;
202
+                if ($result < 0) {
203
+                    $error++;
204
+                }
202 205
                 // End call triggers
203 206
             }
204 207
 
@@ -212,16 +215,14 @@  discard block
 block discarded – undo
212 215
                 $this->db->rollback();
213 216
                 return -1;
214 217
             }
215
-        }
216
-        else
218
+        } else
217 219
         {
218 220
             if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
219 221
             {
220 222
                 // Doublon
221 223
                 $this->error = $langs->trans("ErrorDuplicateField");
222 224
                 $result =  -1;
223
-            }
224
-            else
225
+            } else
225 226
             {
226 227
                 $this->error = $langs->trans("Error sql = " . $sql);
227 228
                 $result =  -2;
@@ -247,7 +248,9 @@  discard block
 block discarded – undo
247 248
 
248 249
         $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM " . MAIN_DB_PREFIX . "links";
249 250
         $sql .= " WHERE objecttype = '" . $objecttype . "' AND objectid = " . $objectid;
250
-        if ($conf->entity != 0) $sql .= " AND entity = " . $conf->entity;
251
+        if ($conf->entity != 0) {
252
+            $sql .= " AND entity = " . $conf->entity;
253
+        }
251 254
         if ($sortfield) {
252 255
             if (empty($sortorder)) {
253 256
                 $sortorder = "ASC";
@@ -298,13 +301,17 @@  discard block
 block discarded – undo
298 301
 
299 302
         $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "links";
300 303
         $sql .= " WHERE objecttype = '" . $objecttype . "' AND objectid = " . $objectid;
301
-        if ($conf->entity != 0) $sql .= " AND entity = " . $conf->entity;
304
+        if ($conf->entity != 0) {
305
+            $sql .= " AND entity = " . $conf->entity;
306
+        }
302 307
 
303 308
         $resql = $db->query($sql);
304 309
         if ($resql)
305 310
         {
306 311
             $obj = $db->fetch_object($resql);
307
-            if ($obj) return $obj->nb;
312
+            if ($obj) {
313
+                return $obj->nb;
314
+            }
308 315
         }
309 316
         return -1;
310 317
     }
@@ -325,7 +332,9 @@  discard block
 block discarded – undo
325 332
 
326 333
         $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM " . MAIN_DB_PREFIX . "links";
327 334
         $sql .= " WHERE rowid = " . $rowid;
328
-        if($conf->entity != 0) $sql .= " AND entity = " . $conf->entity;
335
+        if($conf->entity != 0) {
336
+            $sql .= " AND entity = " . $conf->entity;
337
+        }
329 338
 
330 339
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
331 340
         $resql = $this->db->query($sql);
@@ -341,8 +350,7 @@  discard block
 block discarded – undo
341 350
                 $this->objecttype = $obj->objecttype;
342 351
                 $this->objectid = $obj->objectid;
343 352
                 return 1;
344
-            }
345
-            else
353
+            } else
346 354
 			{
347 355
                 return 0;
348 356
             }
@@ -366,7 +374,9 @@  discard block
 block discarded – undo
366 374
 
367 375
         // Call trigger
368 376
         $result=$this->call_trigger('LINK_DELETE',$user);
369
-        if ($result < 0) return -1;
377
+        if ($result < 0) {
378
+            return -1;
379
+        }
370 380
         // End call triggers
371 381
 
372 382
         $this->db->begin();
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/utils.class.php 3 patches
Indentation   +915 added lines, -915 removed lines patch added patch discarded remove patch
@@ -27,857 +27,857 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class Utils
29 29
 {
30
-	/**
30
+    /**
31 31
      * @var DoliDB Database handler.
32 32
      */
33 33
     public $db;
34 34
 
35
-	var $output;   // Used by Cron method to return message
36
-	var $result;   // Used by Cron method to return data
37
-
38
-	/**
39
-	 *	Constructor
40
-	 *
41
-	 *  @param	DoliDB	$db		Database handler
42
-	 */
43
-	function __construct($db)
44
-	{
45
-		$this->db = $db;
46
-	}
47
-
48
-
49
-	/**
50
-	 *  Purge files into directory of data files.
51
-	 *  CAN BE A CRON TASK
52
-	 *
53
-	 *  @param	string		$choice		Choice of purge mode ('tempfiles', '' or 'tempfilesold' to purge temp older than 24h, 'allfiles', 'logfile')
54
-	 *  @return	int						0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
55
-	 */
56
-	function purgeFiles($choice='tempfilesold')
57
-	{
58
-		global $conf, $langs, $dolibarr_main_data_root;
59
-
60
-		$langs->load("admin");
61
-
62
-		dol_syslog("Utils::purgeFiles choice=".$choice, LOG_DEBUG);
63
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
64
-
65
-		$filesarray=array();
66
-		if (empty($choice)) $choice='tempfilesold';
67
-
68
-		if ($choice=='tempfiles' || $choice=='tempfilesold')
69
-		{
70
-			// Delete temporary files
71
-			if ($dolibarr_main_data_root)
72
-			{
73
-				$filesarray=dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1);	// Do not follow symlinks
74
-				if ($choice == 'tempfilesold')
75
-				{
76
-					$now = dol_now();
77
-					foreach($filesarray as $key => $val)
78
-					{
79
-						if ($val['date'] > ($now - (24 * 3600))) unset($filesarray[$key]);	// Discard files not older than 24h
80
-					}
81
-				}
82
-			}
83
-		}
84
-
85
-		if ($choice=='allfiles')
86
-		{
87
-			// Delete all files (except install.lock, do not follow symbolic links)
88
-			if ($dolibarr_main_data_root)
89
-			{
90
-				$filesarray=dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
91
-			}
92
-		}
93
-
94
-		if ($choice=='logfile')
95
-		{
96
-			// Define files log
97
-			if ($dolibarr_main_data_root)
98
-			{
99
-				$filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
100
-			}
101
-
102
-			$filelog='';
103
-			if (! empty($conf->syslog->enabled))
104
-			{
105
-				$filelog=$conf->global->SYSLOG_FILE;
106
-				$filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
107
-
108
-				$alreadyincluded=false;
109
-				foreach ($filesarray as $tmpcursor)
110
-				{
111
-					if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded=true; }
112
-				}
113
-				if (! $alreadyincluded) $filesarray[]=array('fullname'=>$filelog,'type'=>'file');
114
-			}
115
-		}
116
-
117
-		$count=0;
118
-		$countdeleted=0;
119
-		$counterror=0;
120
-		if (count($filesarray))
121
-		{
122
-			foreach($filesarray as $key => $value)
123
-			{
124
-				//print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']."<br>\n";
125
-				if ($filesarray[$key]['type'] == 'dir')
126
-				{
127
-					$startcount=0;
128
-					$tmpcountdeleted=0;
129
-					$result=dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted);
130
-					$count+=$result;
131
-					$countdeleted+=$tmpcountdeleted;
132
-				}
133
-				elseif ($filesarray[$key]['type'] == 'file')
134
-				{
135
-					// If (file that is not logfile) or (if mode is logfile)
136
-					if ($filesarray[$key]['fullname'] != $filelog || $choice=='logfile')
137
-					{
138
-						$result=dol_delete_file($filesarray[$key]['fullname'], 1, 1);
139
-						if ($result)
140
-						{
141
-							$count++;
142
-							$countdeleted++;
143
-						}
144
-						else
145
-						{
146
-							$counterror++;
147
-						}
148
-					}
149
-				}
150
-			}
151
-
152
-			// Update cachenbofdoc
153
-			if (! empty($conf->ecm->enabled) && $choice=='allfiles')
154
-			{
155
-				require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
156
-				$ecmdirstatic = new EcmDirectory($this->db);
157
-				$result = $ecmdirstatic->refreshcachenboffile(1);
158
-			}
159
-		}
160
-
161
-		if ($count > 0)
162
-		{
163
-			$this->output=$langs->trans("PurgeNDirectoriesDeleted", $countdeleted);
164
-			if ($count > $countdeleted) $this->output.='<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
165
-		}
166
-		else $this->output=$langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)':'');
167
-
168
-		//return $count;
169
-		return 0;     // This function can be called by cron so must return 0 if OK
170
-	}
171
-
172
-
173
-	/**
174
-	 *  Make a backup of database
175
-	 *  CAN BE A CRON TASK
176
-	 *
177
-	 *  @param	string		$compression	   'gz' or 'bz' or 'none'
178
-	 *  @param  string      $type              'mysql', 'postgresql', ...
179
-	 *  @param  int         $usedefault        1=Use default backup profile (Set this to 1 when used as cron)
180
-	 *  @param  string      $file              'auto' or filename to build
181
-	 *  @param  int         $keeplastnfiles    Keep only last n files (not used yet)
182
-	 *  @param	int		    $execmethod		   0=Use default method (that is 1 by default), 1=Use the PHP 'exec', 2=Use the 'popen' method
183
-	 *  @return	int						       0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
184
-	 */
185
-	function dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0, $execmethod=0)
186
-	{
187
-		global $db, $conf, $langs, $dolibarr_main_data_root;
188
-		global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
189
-
190
-		$langs->load("admin");
191
-
192
-		dol_syslog("Utils::dumpDatabase type=".$type." compression=".$compression." file=".$file, LOG_DEBUG);
193
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
194
-
195
-		// Check compression parameter
196
-		if (! in_array($compression, array('none', 'gz', 'bz', 'zip')))
197
-		{
198
-			$langs->load("errors");
199
-			$this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
200
-			return -1;
201
-		}
202
-
203
-		// Check type parameter
204
-		if ($type == 'auto') $type = $db->type;
205
-		if (! in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin')))
206
-		{
207
-			$langs->load("errors");
208
-			$this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
209
-			return -1;
210
-		}
211
-
212
-		// Check file parameter
213
-		if ($file == 'auto')
214
-		{
215
-			$prefix='dump';
216
-			$ext='sql';
217
-			if (in_array($type, array('mysql', 'mysqli')))  { $prefix='mysqldump'; $ext='sql'; }
218
-			//if ($label == 'PostgreSQL') { $prefix='pg_dump'; $ext='dump'; }
219
-			if (in_array($type, array('pgsql'))) { $prefix='pg_dump'; $ext='sql'; }
220
-			$file=$prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.strftime("%Y%m%d%H%M").'.'.$ext;
221
-		}
222
-
223
-		$outputdir  = $conf->admin->dir_output.'/backup';
224
-		$result=dol_mkdir($outputdir);
225
-
226
-
227
-		// MYSQL
228
-		if ($type == 'mysql' || $type == 'mysqli')
229
-		{
230
-			$cmddump=$conf->global->SYSTEMTOOLS_MYSQLDUMP;
231
-
232
-
233
-			$outputfile = $outputdir.'/'.$file;
234
-			// for compression format, we add extension
235
-			$compression=$compression ? $compression : 'none';
236
-			if ($compression == 'gz') $outputfile.='.gz';
237
-			if ($compression == 'bz') $outputfile.='.bz2';
238
-			$outputerror = $outputfile.'.err';
239
-			dol_mkdir($conf->admin->dir_output.'/backup');
240
-
241
-			// Parameteres execution
242
-			$command=$cmddump;
243
-			if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
244
-
245
-			//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
246
-			$param=$dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
247
-			$param.=" -u ".$dolibarr_main_db_user;
248
-			if (! empty($dolibarr_main_db_port)) $param.=" -P ".$dolibarr_main_db_port;
249
-			if (! GETPOST("use_transaction"))    $param.=" -l --single-transaction";
250
-			if (GETPOST("disable_fk") || $usedefault) $param.=" -K";
251
-			if (GETPOST("sql_compat") && GETPOST("sql_compat") != 'NONE') $param.=" --compatible=".escapeshellarg(GETPOST("sql_compat","alpha"));
252
-			if (GETPOST("drop_database"))        $param.=" --add-drop-database";
253
-			if (GETPOST("sql_structure") || $usedefault)
254
-			{
255
-				if (GETPOST("drop") || $usedefault)	$param.=" --add-drop-table=TRUE";
256
-				else 							    $param.=" --add-drop-table=FALSE";
257
-			}
258
-			else
259
-			{
260
-				$param.=" -t";
261
-			}
262
-			if (GETPOST("disable-add-locks")) $param.=" --add-locks=FALSE";
263
-			if (GETPOST("sql_data") || $usedefault)
264
-			{
265
-				$param.=" --tables";
266
-				if (GETPOST("showcolumns") || $usedefault)	 $param.=" -c";
267
-				if (GETPOST("extended_ins") || $usedefault) $param.=" -e";
268
-				else $param.=" --skip-extended-insert";
269
-				if (GETPOST("delayed"))	 	 $param.=" --delayed-insert";
270
-				if (GETPOST("sql_ignore"))	 $param.=" --insert-ignore";
271
-				if (GETPOST("hexforbinary") || $usedefault) $param.=" --hex-blob";
272
-			}
273
-			else
274
-			{
275
-				$param.=" -d";    // No row information (no data)
276
-			}
277
-			$param.=" --default-character-set=utf8";    // We always save output into utf8 charset
278
-			$paramcrypted=$param;
279
-			$paramclear=$param;
280
-			if (! empty($dolibarr_main_db_pass))
281
-			{
282
-				$paramcrypted.=' -p"'.preg_replace('/./i','*',$dolibarr_main_db_pass).'"';
283
-				$paramclear.=' -p"'.str_replace(array('"','`'),array('\"','\`'),$dolibarr_main_db_pass).'"';
284
-			}
285
-
286
-			$errormsg='';
287
-			$handle = '';
288
-
289
-			// Start call method to execute dump
290
-			$fullcommandcrypted=$command." ".$paramcrypted." 2>&1";
291
-			$fullcommandclear=$command." ".$paramclear." 2>&1";
292
-			if ($compression == 'none') $handle = fopen($outputfile, 'w');
293
-			if ($compression == 'gz')   $handle = gzopen($outputfile, 'w');
294
-			if ($compression == 'bz')   $handle = bzopen($outputfile, 'w');
295
-
296
-			if ($handle)
297
-			{
298
-				if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
299
-				if (empty($execmethod)) $execmethod=1;
300
-
301
-				$ok=0;
302
-				dol_syslog("Utils::dumpDatabase execmethod=".$execmethod." command:".$fullcommandcrypted, LOG_DEBUG);
303
-
304
-				// TODO Replace with executeCLI function
305
-				if ($execmethod == 1)
306
-				{
307
-					exec($fullcommandclear, $readt, $retval);
308
-					$result = $retval;
309
-
310
-					if ($retval != 0)
311
-					{
312
-						$langs->load("errors");
313
-						dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
314
-						$error = 'Error '.$retval;
315
-						$ok=0;
316
-					}
317
-					else
318
-					{
319
-						$i=0;
320
-						if (!empty($readt))
321
-						foreach($readt as $key=>$read)
322
-						{
323
-							$i++;   // output line number
324
-							if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
325
-							fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
326
-							if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
327
-							elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
328
-						}
329
-					}
330
-				}
331
-				if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
332
-				{
333
-					$handlein = popen($fullcommandclear, 'r');
334
-					$i=0;
335
-					while (!feof($handlein))
336
-					{
337
-						$i++;   // output line number
338
-						$read = fgets($handlein);
339
-						// Exclude warning line we don't want
340
-						if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
341
-						fwrite($handle,$read);
342
-						if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
343
-						elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
344
-					}
345
-					pclose($handlein);
346
-				}
347
-
348
-
349
-				if ($compression == 'none') fclose($handle);
350
-				if ($compression == 'gz')   gzclose($handle);
351
-				if ($compression == 'bz')   bzclose($handle);
352
-
353
-				if (! empty($conf->global->MAIN_UMASK))
354
-					@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
355
-			}
356
-			else
357
-			{
358
-				$langs->load("errors");
359
-				dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
360
-				$errormsg=$langs->trans("ErrorFailedToWriteInDir");
361
-			}
362
-
363
-			// Get errorstring
364
-			if ($compression == 'none') $handle = fopen($outputfile, 'r');
365
-			if ($compression == 'gz')   $handle = gzopen($outputfile, 'r');
366
-			if ($compression == 'bz')   $handle = bzopen($outputfile, 'r');
367
-			if ($handle)
368
-			{
369
-				// Get 2048 first chars of error message.
370
-				$errormsg = fgets($handle,2048);
371
-				// Close file
372
-				if ($compression == 'none') fclose($handle);
373
-				if ($compression == 'gz')   gzclose($handle);
374
-				if ($compression == 'bz')   bzclose($handle);
375
-				if ($ok && preg_match('/^-- MySql/i',$errormsg)) $errormsg='';	// Pas erreur
376
-				else
377
-				{
378
-					// Renommer fichier sortie en fichier erreur
379
-					//print "$outputfile -> $outputerror";
380
-					@dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
381
-					@rename($outputfile,$outputerror);
382
-					// Si safe_mode on et command hors du parametre exec, on a un fichier out vide donc errormsg vide
383
-					if (! $errormsg)
384
-					{
385
-						$langs->load("errors");
386
-						$errormsg=$langs->trans("ErrorFailedToRunExternalCommand");
387
-					}
388
-				}
389
-			}
390
-			// Fin execution commande
391
-
392
-			$this->output = $errormsg;
393
-			$this->error = $errormsg;
394
-			$this->result = array("commandbackuplastdone" => $command." ".$paramcrypted, "commandbackuptorun" => "");
395
-			//if (empty($this->output)) $this->output=$this->result['commandbackuplastdone'];
396
-		}
397
-
398
-		// MYSQL NO BIN
399
-		if ($type == 'mysqlnobin')
400
-		{
401
-			$outputfile = $outputdir.'/'.$file;
402
-			$outputfiletemp = $outputfile.'-TMP.sql';
403
-			// for compression format, we add extension
404
-			$compression=$compression ? $compression : 'none';
405
-			if ($compression == 'gz') $outputfile.='.gz';
406
-			if ($compression == 'bz') $outputfile.='.bz2';
407
-			$outputerror = $outputfile.'.err';
408
-			dol_mkdir($conf->admin->dir_output.'/backup');
409
-
410
-			if ($compression == 'gz' or $compression == 'bz')
411
-			{
412
-				$this->backupTables($outputfiletemp);
413
-				dol_compress_file($outputfiletemp, $outputfile, $compression);
414
-				unlink($outputfiletemp);
415
-			}
416
-			else
417
-			{
418
-				$this->backupTables($outputfile);
419
-			}
420
-
421
-			$this->output = "";
422
-			$this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => "");
423
-		}
424
-
425
-		// POSTGRESQL
426
-		if ($type == 'postgresql' || $type == 'pgsql')
427
-		{
428
-			$cmddump=$conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
429
-
430
-			$outputfile = $outputdir.'/'.$file;
431
-			// for compression format, we add extension
432
-			$compression=$compression ? $compression : 'none';
433
-			if ($compression == 'gz') $outputfile.='.gz';
434
-			if ($compression == 'bz') $outputfile.='.bz2';
435
-			$outputerror = $outputfile.'.err';
436
-			dol_mkdir($conf->admin->dir_output.'/backup');
437
-
438
-			// Parameteres execution
439
-			$command=$cmddump;
440
-			if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
441
-
442
-			//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
443
-			//$param="-F c";
444
-			$param="-F p";
445
-			$param.=" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
446
-			$param.=" -U ".$dolibarr_main_db_user;
447
-			if (! empty($dolibarr_main_db_port)) $param.=" -p ".$dolibarr_main_db_port;
448
-			if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param.="  --disable-dollar-quoting";
449
-			if (GETPOST("drop_database"))        $param.=" -c -C";
450
-			if (GETPOST("sql_structure"))
451
-			{
452
-				if (GETPOST("drop"))			 $param.=" --add-drop-table";
453
-				if (! GETPOST("sql_data"))       $param.=" -s";
454
-			}
455
-			if (GETPOST("sql_data"))
456
-			{
457
-				if (! GETPOST("sql_structure"))	 $param.=" -a";
458
-				if (GETPOST("showcolumns"))	     $param.=" -c";
459
-			}
460
-			$param.=' -f "'.$outputfile.'"';
461
-			//if ($compression == 'none')
462
-			if ($compression == 'gz')   $param.=' -Z 9';
463
-			//if ($compression == 'bz')
464
-			$paramcrypted=$param;
465
-			$paramclear=$param;
466
-			/*if (! empty($dolibarr_main_db_pass))
35
+    var $output;   // Used by Cron method to return message
36
+    var $result;   // Used by Cron method to return data
37
+
38
+    /**
39
+     *	Constructor
40
+     *
41
+     *  @param	DoliDB	$db		Database handler
42
+     */
43
+    function __construct($db)
44
+    {
45
+        $this->db = $db;
46
+    }
47
+
48
+
49
+    /**
50
+     *  Purge files into directory of data files.
51
+     *  CAN BE A CRON TASK
52
+     *
53
+     *  @param	string		$choice		Choice of purge mode ('tempfiles', '' or 'tempfilesold' to purge temp older than 24h, 'allfiles', 'logfile')
54
+     *  @return	int						0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
55
+     */
56
+    function purgeFiles($choice='tempfilesold')
57
+    {
58
+        global $conf, $langs, $dolibarr_main_data_root;
59
+
60
+        $langs->load("admin");
61
+
62
+        dol_syslog("Utils::purgeFiles choice=".$choice, LOG_DEBUG);
63
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
64
+
65
+        $filesarray=array();
66
+        if (empty($choice)) $choice='tempfilesold';
67
+
68
+        if ($choice=='tempfiles' || $choice=='tempfilesold')
69
+        {
70
+            // Delete temporary files
71
+            if ($dolibarr_main_data_root)
72
+            {
73
+                $filesarray=dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1);	// Do not follow symlinks
74
+                if ($choice == 'tempfilesold')
75
+                {
76
+                    $now = dol_now();
77
+                    foreach($filesarray as $key => $val)
78
+                    {
79
+                        if ($val['date'] > ($now - (24 * 3600))) unset($filesarray[$key]);	// Discard files not older than 24h
80
+                    }
81
+                }
82
+            }
83
+        }
84
+
85
+        if ($choice=='allfiles')
86
+        {
87
+            // Delete all files (except install.lock, do not follow symbolic links)
88
+            if ($dolibarr_main_data_root)
89
+            {
90
+                $filesarray=dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
91
+            }
92
+        }
93
+
94
+        if ($choice=='logfile')
95
+        {
96
+            // Define files log
97
+            if ($dolibarr_main_data_root)
98
+            {
99
+                $filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
100
+            }
101
+
102
+            $filelog='';
103
+            if (! empty($conf->syslog->enabled))
104
+            {
105
+                $filelog=$conf->global->SYSLOG_FILE;
106
+                $filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
107
+
108
+                $alreadyincluded=false;
109
+                foreach ($filesarray as $tmpcursor)
110
+                {
111
+                    if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded=true; }
112
+                }
113
+                if (! $alreadyincluded) $filesarray[]=array('fullname'=>$filelog,'type'=>'file');
114
+            }
115
+        }
116
+
117
+        $count=0;
118
+        $countdeleted=0;
119
+        $counterror=0;
120
+        if (count($filesarray))
121
+        {
122
+            foreach($filesarray as $key => $value)
123
+            {
124
+                //print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']."<br>\n";
125
+                if ($filesarray[$key]['type'] == 'dir')
126
+                {
127
+                    $startcount=0;
128
+                    $tmpcountdeleted=0;
129
+                    $result=dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted);
130
+                    $count+=$result;
131
+                    $countdeleted+=$tmpcountdeleted;
132
+                }
133
+                elseif ($filesarray[$key]['type'] == 'file')
134
+                {
135
+                    // If (file that is not logfile) or (if mode is logfile)
136
+                    if ($filesarray[$key]['fullname'] != $filelog || $choice=='logfile')
137
+                    {
138
+                        $result=dol_delete_file($filesarray[$key]['fullname'], 1, 1);
139
+                        if ($result)
140
+                        {
141
+                            $count++;
142
+                            $countdeleted++;
143
+                        }
144
+                        else
145
+                        {
146
+                            $counterror++;
147
+                        }
148
+                    }
149
+                }
150
+            }
151
+
152
+            // Update cachenbofdoc
153
+            if (! empty($conf->ecm->enabled) && $choice=='allfiles')
154
+            {
155
+                require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
156
+                $ecmdirstatic = new EcmDirectory($this->db);
157
+                $result = $ecmdirstatic->refreshcachenboffile(1);
158
+            }
159
+        }
160
+
161
+        if ($count > 0)
162
+        {
163
+            $this->output=$langs->trans("PurgeNDirectoriesDeleted", $countdeleted);
164
+            if ($count > $countdeleted) $this->output.='<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
165
+        }
166
+        else $this->output=$langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)':'');
167
+
168
+        //return $count;
169
+        return 0;     // This function can be called by cron so must return 0 if OK
170
+    }
171
+
172
+
173
+    /**
174
+     *  Make a backup of database
175
+     *  CAN BE A CRON TASK
176
+     *
177
+     *  @param	string		$compression	   'gz' or 'bz' or 'none'
178
+     *  @param  string      $type              'mysql', 'postgresql', ...
179
+     *  @param  int         $usedefault        1=Use default backup profile (Set this to 1 when used as cron)
180
+     *  @param  string      $file              'auto' or filename to build
181
+     *  @param  int         $keeplastnfiles    Keep only last n files (not used yet)
182
+     *  @param	int		    $execmethod		   0=Use default method (that is 1 by default), 1=Use the PHP 'exec', 2=Use the 'popen' method
183
+     *  @return	int						       0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
184
+     */
185
+    function dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0, $execmethod=0)
186
+    {
187
+        global $db, $conf, $langs, $dolibarr_main_data_root;
188
+        global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
189
+
190
+        $langs->load("admin");
191
+
192
+        dol_syslog("Utils::dumpDatabase type=".$type." compression=".$compression." file=".$file, LOG_DEBUG);
193
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
194
+
195
+        // Check compression parameter
196
+        if (! in_array($compression, array('none', 'gz', 'bz', 'zip')))
197
+        {
198
+            $langs->load("errors");
199
+            $this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
200
+            return -1;
201
+        }
202
+
203
+        // Check type parameter
204
+        if ($type == 'auto') $type = $db->type;
205
+        if (! in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin')))
206
+        {
207
+            $langs->load("errors");
208
+            $this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
209
+            return -1;
210
+        }
211
+
212
+        // Check file parameter
213
+        if ($file == 'auto')
214
+        {
215
+            $prefix='dump';
216
+            $ext='sql';
217
+            if (in_array($type, array('mysql', 'mysqli')))  { $prefix='mysqldump'; $ext='sql'; }
218
+            //if ($label == 'PostgreSQL') { $prefix='pg_dump'; $ext='dump'; }
219
+            if (in_array($type, array('pgsql'))) { $prefix='pg_dump'; $ext='sql'; }
220
+            $file=$prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.strftime("%Y%m%d%H%M").'.'.$ext;
221
+        }
222
+
223
+        $outputdir  = $conf->admin->dir_output.'/backup';
224
+        $result=dol_mkdir($outputdir);
225
+
226
+
227
+        // MYSQL
228
+        if ($type == 'mysql' || $type == 'mysqli')
229
+        {
230
+            $cmddump=$conf->global->SYSTEMTOOLS_MYSQLDUMP;
231
+
232
+
233
+            $outputfile = $outputdir.'/'.$file;
234
+            // for compression format, we add extension
235
+            $compression=$compression ? $compression : 'none';
236
+            if ($compression == 'gz') $outputfile.='.gz';
237
+            if ($compression == 'bz') $outputfile.='.bz2';
238
+            $outputerror = $outputfile.'.err';
239
+            dol_mkdir($conf->admin->dir_output.'/backup');
240
+
241
+            // Parameteres execution
242
+            $command=$cmddump;
243
+            if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
244
+
245
+            //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
246
+            $param=$dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
247
+            $param.=" -u ".$dolibarr_main_db_user;
248
+            if (! empty($dolibarr_main_db_port)) $param.=" -P ".$dolibarr_main_db_port;
249
+            if (! GETPOST("use_transaction"))    $param.=" -l --single-transaction";
250
+            if (GETPOST("disable_fk") || $usedefault) $param.=" -K";
251
+            if (GETPOST("sql_compat") && GETPOST("sql_compat") != 'NONE') $param.=" --compatible=".escapeshellarg(GETPOST("sql_compat","alpha"));
252
+            if (GETPOST("drop_database"))        $param.=" --add-drop-database";
253
+            if (GETPOST("sql_structure") || $usedefault)
254
+            {
255
+                if (GETPOST("drop") || $usedefault)	$param.=" --add-drop-table=TRUE";
256
+                else 							    $param.=" --add-drop-table=FALSE";
257
+            }
258
+            else
259
+            {
260
+                $param.=" -t";
261
+            }
262
+            if (GETPOST("disable-add-locks")) $param.=" --add-locks=FALSE";
263
+            if (GETPOST("sql_data") || $usedefault)
264
+            {
265
+                $param.=" --tables";
266
+                if (GETPOST("showcolumns") || $usedefault)	 $param.=" -c";
267
+                if (GETPOST("extended_ins") || $usedefault) $param.=" -e";
268
+                else $param.=" --skip-extended-insert";
269
+                if (GETPOST("delayed"))	 	 $param.=" --delayed-insert";
270
+                if (GETPOST("sql_ignore"))	 $param.=" --insert-ignore";
271
+                if (GETPOST("hexforbinary") || $usedefault) $param.=" --hex-blob";
272
+            }
273
+            else
274
+            {
275
+                $param.=" -d";    // No row information (no data)
276
+            }
277
+            $param.=" --default-character-set=utf8";    // We always save output into utf8 charset
278
+            $paramcrypted=$param;
279
+            $paramclear=$param;
280
+            if (! empty($dolibarr_main_db_pass))
281
+            {
282
+                $paramcrypted.=' -p"'.preg_replace('/./i','*',$dolibarr_main_db_pass).'"';
283
+                $paramclear.=' -p"'.str_replace(array('"','`'),array('\"','\`'),$dolibarr_main_db_pass).'"';
284
+            }
285
+
286
+            $errormsg='';
287
+            $handle = '';
288
+
289
+            // Start call method to execute dump
290
+            $fullcommandcrypted=$command." ".$paramcrypted." 2>&1";
291
+            $fullcommandclear=$command." ".$paramclear." 2>&1";
292
+            if ($compression == 'none') $handle = fopen($outputfile, 'w');
293
+            if ($compression == 'gz')   $handle = gzopen($outputfile, 'w');
294
+            if ($compression == 'bz')   $handle = bzopen($outputfile, 'w');
295
+
296
+            if ($handle)
297
+            {
298
+                if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
299
+                if (empty($execmethod)) $execmethod=1;
300
+
301
+                $ok=0;
302
+                dol_syslog("Utils::dumpDatabase execmethod=".$execmethod." command:".$fullcommandcrypted, LOG_DEBUG);
303
+
304
+                // TODO Replace with executeCLI function
305
+                if ($execmethod == 1)
306
+                {
307
+                    exec($fullcommandclear, $readt, $retval);
308
+                    $result = $retval;
309
+
310
+                    if ($retval != 0)
311
+                    {
312
+                        $langs->load("errors");
313
+                        dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
314
+                        $error = 'Error '.$retval;
315
+                        $ok=0;
316
+                    }
317
+                    else
318
+                    {
319
+                        $i=0;
320
+                        if (!empty($readt))
321
+                        foreach($readt as $key=>$read)
322
+                        {
323
+                            $i++;   // output line number
324
+                            if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
325
+                            fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
326
+                            if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
327
+                            elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
328
+                        }
329
+                    }
330
+                }
331
+                if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
332
+                {
333
+                    $handlein = popen($fullcommandclear, 'r');
334
+                    $i=0;
335
+                    while (!feof($handlein))
336
+                    {
337
+                        $i++;   // output line number
338
+                        $read = fgets($handlein);
339
+                        // Exclude warning line we don't want
340
+                        if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
341
+                        fwrite($handle,$read);
342
+                        if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
343
+                        elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
344
+                    }
345
+                    pclose($handlein);
346
+                }
347
+
348
+
349
+                if ($compression == 'none') fclose($handle);
350
+                if ($compression == 'gz')   gzclose($handle);
351
+                if ($compression == 'bz')   bzclose($handle);
352
+
353
+                if (! empty($conf->global->MAIN_UMASK))
354
+                    @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
355
+            }
356
+            else
357
+            {
358
+                $langs->load("errors");
359
+                dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
360
+                $errormsg=$langs->trans("ErrorFailedToWriteInDir");
361
+            }
362
+
363
+            // Get errorstring
364
+            if ($compression == 'none') $handle = fopen($outputfile, 'r');
365
+            if ($compression == 'gz')   $handle = gzopen($outputfile, 'r');
366
+            if ($compression == 'bz')   $handle = bzopen($outputfile, 'r');
367
+            if ($handle)
368
+            {
369
+                // Get 2048 first chars of error message.
370
+                $errormsg = fgets($handle,2048);
371
+                // Close file
372
+                if ($compression == 'none') fclose($handle);
373
+                if ($compression == 'gz')   gzclose($handle);
374
+                if ($compression == 'bz')   bzclose($handle);
375
+                if ($ok && preg_match('/^-- MySql/i',$errormsg)) $errormsg='';	// Pas erreur
376
+                else
377
+                {
378
+                    // Renommer fichier sortie en fichier erreur
379
+                    //print "$outputfile -> $outputerror";
380
+                    @dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
381
+                    @rename($outputfile,$outputerror);
382
+                    // Si safe_mode on et command hors du parametre exec, on a un fichier out vide donc errormsg vide
383
+                    if (! $errormsg)
384
+                    {
385
+                        $langs->load("errors");
386
+                        $errormsg=$langs->trans("ErrorFailedToRunExternalCommand");
387
+                    }
388
+                }
389
+            }
390
+            // Fin execution commande
391
+
392
+            $this->output = $errormsg;
393
+            $this->error = $errormsg;
394
+            $this->result = array("commandbackuplastdone" => $command." ".$paramcrypted, "commandbackuptorun" => "");
395
+            //if (empty($this->output)) $this->output=$this->result['commandbackuplastdone'];
396
+        }
397
+
398
+        // MYSQL NO BIN
399
+        if ($type == 'mysqlnobin')
400
+        {
401
+            $outputfile = $outputdir.'/'.$file;
402
+            $outputfiletemp = $outputfile.'-TMP.sql';
403
+            // for compression format, we add extension
404
+            $compression=$compression ? $compression : 'none';
405
+            if ($compression == 'gz') $outputfile.='.gz';
406
+            if ($compression == 'bz') $outputfile.='.bz2';
407
+            $outputerror = $outputfile.'.err';
408
+            dol_mkdir($conf->admin->dir_output.'/backup');
409
+
410
+            if ($compression == 'gz' or $compression == 'bz')
411
+            {
412
+                $this->backupTables($outputfiletemp);
413
+                dol_compress_file($outputfiletemp, $outputfile, $compression);
414
+                unlink($outputfiletemp);
415
+            }
416
+            else
417
+            {
418
+                $this->backupTables($outputfile);
419
+            }
420
+
421
+            $this->output = "";
422
+            $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => "");
423
+        }
424
+
425
+        // POSTGRESQL
426
+        if ($type == 'postgresql' || $type == 'pgsql')
427
+        {
428
+            $cmddump=$conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
429
+
430
+            $outputfile = $outputdir.'/'.$file;
431
+            // for compression format, we add extension
432
+            $compression=$compression ? $compression : 'none';
433
+            if ($compression == 'gz') $outputfile.='.gz';
434
+            if ($compression == 'bz') $outputfile.='.bz2';
435
+            $outputerror = $outputfile.'.err';
436
+            dol_mkdir($conf->admin->dir_output.'/backup');
437
+
438
+            // Parameteres execution
439
+            $command=$cmddump;
440
+            if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
441
+
442
+            //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
443
+            //$param="-F c";
444
+            $param="-F p";
445
+            $param.=" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
446
+            $param.=" -U ".$dolibarr_main_db_user;
447
+            if (! empty($dolibarr_main_db_port)) $param.=" -p ".$dolibarr_main_db_port;
448
+            if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param.="  --disable-dollar-quoting";
449
+            if (GETPOST("drop_database"))        $param.=" -c -C";
450
+            if (GETPOST("sql_structure"))
451
+            {
452
+                if (GETPOST("drop"))			 $param.=" --add-drop-table";
453
+                if (! GETPOST("sql_data"))       $param.=" -s";
454
+            }
455
+            if (GETPOST("sql_data"))
456
+            {
457
+                if (! GETPOST("sql_structure"))	 $param.=" -a";
458
+                if (GETPOST("showcolumns"))	     $param.=" -c";
459
+            }
460
+            $param.=' -f "'.$outputfile.'"';
461
+            //if ($compression == 'none')
462
+            if ($compression == 'gz')   $param.=' -Z 9';
463
+            //if ($compression == 'bz')
464
+            $paramcrypted=$param;
465
+            $paramclear=$param;
466
+            /*if (! empty($dolibarr_main_db_pass))
467 467
 			 {
468 468
 			 $paramcrypted.=" -W".preg_replace('/./i','*',$dolibarr_main_db_pass);
469 469
 			 $paramclear.=" -W".$dolibarr_main_db_pass;
470 470
 			 }*/
471
-			$paramcrypted.=" -w ".$dolibarr_main_db_name;
472
-			$paramclear.=" -w ".$dolibarr_main_db_name;
473
-
474
-			$this->output = "";
475
-			$this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => $command." ".$paramcrypted);
476
-		}
477
-
478
-		// Clean old files
479
-		if ($keeplastnfiles > 0)
480
-		{
481
-			$tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
482
-			$i=0;
483
-			foreach($tmpfiles as $key => $val)
484
-			{
485
-				$i++;
486
-				if ($i <= $keeplastnfiles) continue;
487
-				dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
488
-			}
489
-		}
490
-
491
-		return 0;
492
-	}
493
-
494
-
495
-
496
-	/**
497
-	 * Execute a CLI command.
498
-	 *
499
-	 * @param 	string	$command		Command line to execute.
500
-	 * @param 	string	$outputfile		Output file (used only when method is 2). For exemple $conf->admin->dir_temp.'/out.tmp';
501
-	 * @param	int		$execmethod		0=Use default method (that is 1 by default), 1=Use the PHP 'exec', 2=Use the 'popen' method
502
-	 * @return	array					array('result'=>...,'output'=>...,'error'=>...). result = 0 means OK.
503
-	 */
504
-	function executeCLI($command, $outputfile, $execmethod=0)
505
-	{
506
-		global $conf, $langs;
507
-
508
-		$result = 0;
509
-		$output = '';
510
-		$error = '';
511
-
512
-		$command=escapeshellcmd($command);
513
-		$command.=" 2>&1";
514
-
515
-		if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
516
-		if (empty($execmethod)) $execmethod=1;
517
-		//$execmethod=1;
518
-
519
-		dol_syslog("Utils::executeCLI execmethod=".$execmethod." system:".$command, LOG_DEBUG);
520
-		$output_arr=array();
521
-
522
-		if ($execmethod == 1)
523
-		{
524
-			exec($command, $output_arr, $retval);
525
-			$result = $retval;
526
-			if ($retval != 0)
527
-			{
528
-				$langs->load("errors");
529
-				dol_syslog("Utils::executeCLI retval after exec=".$retval, LOG_ERR);
530
-				$error = 'Error '.$retval;
531
-			}
532
-		}
533
-		if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
534
-		{
535
-			$ok=0;
536
-			$handle = fopen($outputfile, 'w+b');
537
-			if ($handle)
538
-			{
539
-				dol_syslog("Utils::executeCLI run command ".$command);
540
-				$handlein = popen($command, 'r');
541
-				while (!feof($handlein))
542
-				{
543
-					$read = fgets($handlein);
544
-					fwrite($handle,$read);
545
-					$output_arr[]=$read;
546
-				}
547
-				pclose($handlein);
548
-				fclose($handle);
549
-			}
550
-			if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
551
-		}
552
-
553
-		// Update with result
554
-		if (is_array($output_arr) && count($output_arr)>0)
555
-		{
556
-			foreach($output_arr as $val)
557
-			{
558
-				$output.=$val.($execmethod == 2 ? '' : "\n");
559
-			}
560
-		}
561
-
562
-		dol_syslog("Utils::executeCLI result=".$result." output=".$output." error=".$error, LOG_DEBUG);
563
-
564
-		return array('result'=>$result, 'output'=>$output, 'error'=>$error);
565
-	}
566
-
567
-	/**
568
-	 * Generate documentation of a Module
569
-	 *
570
-	 * @param 	string	$module		Module name
571
-	 * @return	int					<0 if KO, >0 if OK
572
-	 */
573
-	function generateDoc($module)
574
-	{
575
-		global $conf, $langs;
576
-		global $dirins;
577
-
578
-		$error = 0;
579
-
580
-		$modulelowercase=strtolower($module);
581
-
582
-		// Dir for module
583
-		$dir = $dirins.'/'.$modulelowercase;
584
-		// Zip file to build
585
-		$FILENAMEDOC='';
586
-
587
-		// Load module
588
-		dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
589
-		$class='mod'.$module;
590
-
591
-		if (class_exists($class))
592
-		{
593
-			try {
594
-				$moduleobj = new $class($this->db);
595
-			}
596
-			catch(Exception $e)
597
-			{
598
-				$error++;
599
-				dol_print_error($e->getMessage());
600
-			}
601
-		}
602
-		else
603
-		{
604
-			$error++;
605
-			$langs->load("errors");
606
-			dol_print_error($langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module));
607
-			exit;
608
-		}
609
-
610
-		$arrayversion=explode('.',$moduleobj->version,3);
611
-		if (count($arrayversion))
612
-		{
613
-			$FILENAMEASCII=strtolower($module).'.asciidoc';
614
-			$FILENAMEDOC=strtolower($module).'.html';			// TODO Use/text PDF
615
-
616
-			$dirofmodule = dol_buildpath(strtolower($module), 0).'/doc';
617
-			$dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
618
-			$outputfiledoc = $dirofmodule.'/'.$FILENAMEDOC;
619
-			if ($dirofmodule)
620
-			{
621
-				if (! dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule);
622
-				if (! dol_is_dir($dirofmoduletmp)) dol_mkdir($dirofmoduletmp);
623
-				if (! is_writable($dirofmoduletmp))
624
-				{
625
-					$this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
626
-					return -1;
627
-				}
628
-
629
-				$destfile=$dirofmoduletmp.'/'.$FILENAMEASCII;
630
-
631
-				$fhandle = fopen($destfile, 'w+');
632
-				if ($fhandle)
633
-				{
634
-					$specs=dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
635
-
636
-					$i = 0;
637
-					foreach ($specs as $spec)
638
-					{
639
-						if (preg_match('/notindoc/', $spec['relativename'])) continue;	// Discard file
640
-						if (preg_match('/disabled/', $spec['relativename'])) continue;	// Discard file
641
-
642
-						$pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
643
-						$format='asciidoc';
644
-						if (preg_match('/\.md$/i', $spec['name'])) $format='markdown';
645
-
646
-						$filecursor = @file_get_contents($spec['fullname']);
647
-						if ($filecursor)
648
-						{
649
-							fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
650
-						}
651
-						else
652
-						{
653
-							$this->error = 'Failed to concat content of file '.$spec['fullname'];
654
-							return -1;
655
-						}
656
-
657
-						$i++;
658
-					}
659
-
660
-					fwrite($fhandle, "\n\n\n== DATA SPECIFICATIONS...\n\n");
661
-
662
-					// TODO
663
-					fwrite($fhandle, "TODO...");
664
-
665
-					fclose($fhandle);
666
-				}
667
-
668
-				$conf->global->MODULEBUILDER_ASCIIDOCTOR='asciidoctor';
669
-				if (empty($conf->global->MODULEBUILDER_ASCIIDOCTOR))
670
-				{
671
-					dol_print_error('', 'Module setup not complete');
672
-					exit;
673
-				}
674
-
675
-				$command=$conf->global->MODULEBUILDER_ASCIIDOCTOR.' '.$destfile.' -n -o '.$dirofmodule.'/'.$FILENAMEDOC;
676
-				$outfile=$dirofmoduletmp.'/out.tmp';
677
-
678
-				require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
679
-				$utils = new Utils($db);
680
-				$resarray = $utils->executeCLI($command, $outfile);
681
-				if ($resarray['result'] != '0')
682
-				{
683
-					$this->error = $resarray['error'].' '.$resarray['output'];
684
-				}
685
-				$result = ($resarray['result'] == 0) ? 1 : 0;
686
-			}
687
-			else
688
-			{
689
-				$result = 0;
690
-			}
691
-
692
-			if ($result > 0)
693
-			{
694
-				return 1;
695
-			}
696
-			else
697
-			{
698
-				$error++;
699
-				$langs->load("errors");
700
-				$this->error = $langs->trans("ErrorFailToGenerateFile", $outputfiledoc);
701
-			}
702
-		}
703
-		else
704
-		{
705
-			$error++;
706
-			$langs->load("errors");
707
-			$this->error = $langs->trans("ErrorCheckVersionIsDefined");
708
-		}
709
-
710
-		return -1;
711
-	}
712
-
713
-	/**
714
-	 * This saves syslog files and compresses older ones.
715
-	 * Nb of archive to keep is defined into $conf->global->SYSLOG_FILE_SAVES
716
-	 * CAN BE A CRON TASK
717
-	 *
718
-	 * @return	int						0 if OK, < 0 if KO
719
-	 */
471
+            $paramcrypted.=" -w ".$dolibarr_main_db_name;
472
+            $paramclear.=" -w ".$dolibarr_main_db_name;
473
+
474
+            $this->output = "";
475
+            $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => $command." ".$paramcrypted);
476
+        }
477
+
478
+        // Clean old files
479
+        if ($keeplastnfiles > 0)
480
+        {
481
+            $tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
482
+            $i=0;
483
+            foreach($tmpfiles as $key => $val)
484
+            {
485
+                $i++;
486
+                if ($i <= $keeplastnfiles) continue;
487
+                dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
488
+            }
489
+        }
490
+
491
+        return 0;
492
+    }
493
+
494
+
495
+
496
+    /**
497
+     * Execute a CLI command.
498
+     *
499
+     * @param 	string	$command		Command line to execute.
500
+     * @param 	string	$outputfile		Output file (used only when method is 2). For exemple $conf->admin->dir_temp.'/out.tmp';
501
+     * @param	int		$execmethod		0=Use default method (that is 1 by default), 1=Use the PHP 'exec', 2=Use the 'popen' method
502
+     * @return	array					array('result'=>...,'output'=>...,'error'=>...). result = 0 means OK.
503
+     */
504
+    function executeCLI($command, $outputfile, $execmethod=0)
505
+    {
506
+        global $conf, $langs;
507
+
508
+        $result = 0;
509
+        $output = '';
510
+        $error = '';
511
+
512
+        $command=escapeshellcmd($command);
513
+        $command.=" 2>&1";
514
+
515
+        if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
516
+        if (empty($execmethod)) $execmethod=1;
517
+        //$execmethod=1;
518
+
519
+        dol_syslog("Utils::executeCLI execmethod=".$execmethod." system:".$command, LOG_DEBUG);
520
+        $output_arr=array();
521
+
522
+        if ($execmethod == 1)
523
+        {
524
+            exec($command, $output_arr, $retval);
525
+            $result = $retval;
526
+            if ($retval != 0)
527
+            {
528
+                $langs->load("errors");
529
+                dol_syslog("Utils::executeCLI retval after exec=".$retval, LOG_ERR);
530
+                $error = 'Error '.$retval;
531
+            }
532
+        }
533
+        if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
534
+        {
535
+            $ok=0;
536
+            $handle = fopen($outputfile, 'w+b');
537
+            if ($handle)
538
+            {
539
+                dol_syslog("Utils::executeCLI run command ".$command);
540
+                $handlein = popen($command, 'r');
541
+                while (!feof($handlein))
542
+                {
543
+                    $read = fgets($handlein);
544
+                    fwrite($handle,$read);
545
+                    $output_arr[]=$read;
546
+                }
547
+                pclose($handlein);
548
+                fclose($handle);
549
+            }
550
+            if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
551
+        }
552
+
553
+        // Update with result
554
+        if (is_array($output_arr) && count($output_arr)>0)
555
+        {
556
+            foreach($output_arr as $val)
557
+            {
558
+                $output.=$val.($execmethod == 2 ? '' : "\n");
559
+            }
560
+        }
561
+
562
+        dol_syslog("Utils::executeCLI result=".$result." output=".$output." error=".$error, LOG_DEBUG);
563
+
564
+        return array('result'=>$result, 'output'=>$output, 'error'=>$error);
565
+    }
566
+
567
+    /**
568
+     * Generate documentation of a Module
569
+     *
570
+     * @param 	string	$module		Module name
571
+     * @return	int					<0 if KO, >0 if OK
572
+     */
573
+    function generateDoc($module)
574
+    {
575
+        global $conf, $langs;
576
+        global $dirins;
577
+
578
+        $error = 0;
579
+
580
+        $modulelowercase=strtolower($module);
581
+
582
+        // Dir for module
583
+        $dir = $dirins.'/'.$modulelowercase;
584
+        // Zip file to build
585
+        $FILENAMEDOC='';
586
+
587
+        // Load module
588
+        dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
589
+        $class='mod'.$module;
590
+
591
+        if (class_exists($class))
592
+        {
593
+            try {
594
+                $moduleobj = new $class($this->db);
595
+            }
596
+            catch(Exception $e)
597
+            {
598
+                $error++;
599
+                dol_print_error($e->getMessage());
600
+            }
601
+        }
602
+        else
603
+        {
604
+            $error++;
605
+            $langs->load("errors");
606
+            dol_print_error($langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module));
607
+            exit;
608
+        }
609
+
610
+        $arrayversion=explode('.',$moduleobj->version,3);
611
+        if (count($arrayversion))
612
+        {
613
+            $FILENAMEASCII=strtolower($module).'.asciidoc';
614
+            $FILENAMEDOC=strtolower($module).'.html';			// TODO Use/text PDF
615
+
616
+            $dirofmodule = dol_buildpath(strtolower($module), 0).'/doc';
617
+            $dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
618
+            $outputfiledoc = $dirofmodule.'/'.$FILENAMEDOC;
619
+            if ($dirofmodule)
620
+            {
621
+                if (! dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule);
622
+                if (! dol_is_dir($dirofmoduletmp)) dol_mkdir($dirofmoduletmp);
623
+                if (! is_writable($dirofmoduletmp))
624
+                {
625
+                    $this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
626
+                    return -1;
627
+                }
628
+
629
+                $destfile=$dirofmoduletmp.'/'.$FILENAMEASCII;
630
+
631
+                $fhandle = fopen($destfile, 'w+');
632
+                if ($fhandle)
633
+                {
634
+                    $specs=dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
635
+
636
+                    $i = 0;
637
+                    foreach ($specs as $spec)
638
+                    {
639
+                        if (preg_match('/notindoc/', $spec['relativename'])) continue;	// Discard file
640
+                        if (preg_match('/disabled/', $spec['relativename'])) continue;	// Discard file
641
+
642
+                        $pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
643
+                        $format='asciidoc';
644
+                        if (preg_match('/\.md$/i', $spec['name'])) $format='markdown';
645
+
646
+                        $filecursor = @file_get_contents($spec['fullname']);
647
+                        if ($filecursor)
648
+                        {
649
+                            fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
650
+                        }
651
+                        else
652
+                        {
653
+                            $this->error = 'Failed to concat content of file '.$spec['fullname'];
654
+                            return -1;
655
+                        }
656
+
657
+                        $i++;
658
+                    }
659
+
660
+                    fwrite($fhandle, "\n\n\n== DATA SPECIFICATIONS...\n\n");
661
+
662
+                    // TODO
663
+                    fwrite($fhandle, "TODO...");
664
+
665
+                    fclose($fhandle);
666
+                }
667
+
668
+                $conf->global->MODULEBUILDER_ASCIIDOCTOR='asciidoctor';
669
+                if (empty($conf->global->MODULEBUILDER_ASCIIDOCTOR))
670
+                {
671
+                    dol_print_error('', 'Module setup not complete');
672
+                    exit;
673
+                }
674
+
675
+                $command=$conf->global->MODULEBUILDER_ASCIIDOCTOR.' '.$destfile.' -n -o '.$dirofmodule.'/'.$FILENAMEDOC;
676
+                $outfile=$dirofmoduletmp.'/out.tmp';
677
+
678
+                require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
679
+                $utils = new Utils($db);
680
+                $resarray = $utils->executeCLI($command, $outfile);
681
+                if ($resarray['result'] != '0')
682
+                {
683
+                    $this->error = $resarray['error'].' '.$resarray['output'];
684
+                }
685
+                $result = ($resarray['result'] == 0) ? 1 : 0;
686
+            }
687
+            else
688
+            {
689
+                $result = 0;
690
+            }
691
+
692
+            if ($result > 0)
693
+            {
694
+                return 1;
695
+            }
696
+            else
697
+            {
698
+                $error++;
699
+                $langs->load("errors");
700
+                $this->error = $langs->trans("ErrorFailToGenerateFile", $outputfiledoc);
701
+            }
702
+        }
703
+        else
704
+        {
705
+            $error++;
706
+            $langs->load("errors");
707
+            $this->error = $langs->trans("ErrorCheckVersionIsDefined");
708
+        }
709
+
710
+        return -1;
711
+    }
712
+
713
+    /**
714
+     * This saves syslog files and compresses older ones.
715
+     * Nb of archive to keep is defined into $conf->global->SYSLOG_FILE_SAVES
716
+     * CAN BE A CRON TASK
717
+     *
718
+     * @return	int						0 if OK, < 0 if KO
719
+     */
720 720
     function compressSyslogs()
721 721
     {
722
-		global $conf;
722
+        global $conf;
723
+
724
+        if(empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
725
+            return 0;
726
+        }
727
+
728
+        if(! function_exists('gzopen')) {
729
+            $this->error = 'Support for gzopen not available in this PHP';
730
+            return -1;
731
+        }
732
+
733
+        dol_include_once('/core/lib/files.lib.php');
734
+
735
+        $nbSaves = ! empty($conf->global->SYSLOG_FILE_SAVES) ? intval($conf->global->SYSLOG_FILE_SAVES) : 14;
736
+
737
+        if (empty($conf->global->SYSLOG_FILE)) {
738
+            $mainlogdir = DOL_DATA_ROOT;
739
+            $mainlog = 'dolibarr.log';
740
+        } else {
741
+            $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
742
+            $mainlogdir = dirname($mainlogfull);
743
+            $mainlog = basename($mainlogfull);
744
+        }
745
+
746
+        $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
747
+        $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
723 748
 
724
-		if(empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
725
-			return 0;
726
-		}
749
+        foreach($tabfiles as $file) {
727 750
 
728
-		if(! function_exists('gzopen')) {
729
-			$this->error = 'Support for gzopen not available in this PHP';
730
-			return -1;
731
-		}
751
+            $logname = $file['name'];
752
+            $logpath = $file['path'];
732 753
 
733
-		dol_include_once('/core/lib/files.lib.php');
754
+            if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0)	// If log file exists and is not empty
755
+            {
756
+                // Handle already compressed files to rename them and add +1
734 757
 
735
-		$nbSaves = ! empty($conf->global->SYSLOG_FILE_SAVES) ? intval($conf->global->SYSLOG_FILE_SAVES) : 14;
758
+                $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
736 759
 
737
-		if (empty($conf->global->SYSLOG_FILE)) {
738
-			$mainlogdir = DOL_DATA_ROOT;
739
-			$mainlog = 'dolibarr.log';
740
-		} else {
741
-			$mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
742
-			$mainlogdir = dirname($mainlogfull);
743
-			$mainlog = basename($mainlogfull);
744
-		}
760
+                $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
761
+                $gzfiles = array();
745 762
 
746
-		$tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
747
-		$tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
763
+                foreach($gzfilestmp as $gzfile) {
764
+                    $tabmatches = array();
765
+                    preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
748 766
 
749
-		foreach($tabfiles as $file) {
750
-
751
-			$logname = $file['name'];
752
-			$logpath = $file['path'];
753
-
754
-			if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0)	// If log file exists and is not empty
755
-			{
756
-				// Handle already compressed files to rename them and add +1
757
-
758
-				$filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
759
-
760
-				$gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
761
-				$gzfiles = array();
762
-
763
-				foreach($gzfilestmp as $gzfile) {
764
-					$tabmatches = array();
765
-					preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
766
-
767
-					$numsave = intval($tabmatches[1]);
768
-
769
-					$gzfiles[$numsave] = $gzfile;
770
-				}
771
-
772
-				krsort($gzfiles, SORT_NUMERIC);
773
-
774
-				foreach($gzfiles as $numsave => $dummy) {
775
-					if (dol_is_file($logpath.'/'.$logname.'.'.($numsave+1).'.gz')) {
776
-						return -2;
777
-					}
778
-
779
-					if($numsave >= $nbSaves) {
780
-						dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
781
-					} else {
782
-						dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave+1).'.gz', 0, 1, 0, 0);
783
-					}
784
-				}
785
-
786
-				// Compress current file and recreate it
787
-
788
-				if ($nbSaves > 0) {			// If $nbSaves is 1, we keep 1 archive .gz file, If 2, we keep 2 .gz files
789
-					$gzfilehandle = gzopen($logpath.'/'.$logname.'.1.gz', 'wb9');
790
-
791
-					if (empty($gzfilehandle)) {
792
-						$this->error = 'Failted to open file '.$logpath.'/'.$logname.'.1.gz';
793
-						return -3;
794
-					}
795
-
796
-					$sourcehandle = fopen($logpath.'/'.$logname, 'r');
797
-
798
-					if (empty($sourcehandle)) {
799
-						$this->error = 'Failed to open file '.$logpath.'/'.$logname;
800
-						return -4;
801
-					}
802
-
803
-					while(! feof($sourcehandle)) {
804
-						gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
805
-					}
806
-
807
-					fclose($sourcehandle);
808
-					gzclose($gzfilehandle);
809
-
810
-					@chmod($logpath.'/'.$logname.'.1.gz', octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
811
-				}
812
-
813
-				dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
814
-
815
-				// Create empty file
816
-				$newlog = fopen($logpath.'/'.$logname, 'a+');
817
-				fclose($newlog);
818
-
819
-				//var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
820
-				@chmod($logpath.'/'.$logname, octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
821
-			}
822
-		}
823
-
824
-		$this->output = 'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.' files) done.';
825
-		return 0;
826
-	}
827
-
828
-	/**	Backup the db OR just a table without mysqldump binary, with PHP only (does not require any exec permission)
829
-	 *	Author: David Walsh (http://davidwalsh.name/backup-mysql-database-php)
830
-	 *	Updated and enhanced by Stephen Larroque (lrq3000) and by the many commentators from the blog
831
-	 *	Note about foreign keys constraints: for Dolibarr, since there are a lot of constraints and when imported the tables will be inserted in the dumped order, not in constraints order, then we ABSOLUTELY need to use SET FOREIGN_KEY_CHECKS=0; when importing the sql dump.
832
-	 *	Note2: db2SQL by Howard Yeend can be an alternative, by using SHOW FIELDS FROM and SHOW KEYS FROM we could generate a more precise dump (eg: by getting the type of the field and then precisely outputting the right formatting - in quotes, numeric or null - instead of trying to guess like we are doing now).
833
-	 *
834
-	 *	@param	string	$outputfile		Output file name
835
-	 *	@param	string	$tables			Table name or '*' for all
836
-	 *	@return	int						<0 if KO, >0 if OK
837
-	 */
838
-	function backupTables($outputfile, $tables='*')
839
-	{
840
-		global $db, $langs;
841
-		global $errormsg;
842
-
843
-		// Set to UTF-8
844
-		if (is_a($db, 'DoliDBMysqli')) {
845
-			/** @var DoliDBMysqli $db */
846
-			$db->db->set_charset('utf8');
847
-		} else {
848
-			/** @var DoliDB $db */
849
-			$db->query('SET NAMES utf8');
850
-			$db->query('SET CHARACTER SET utf8');
851
-		}
852
-
853
-		//get all of the tables
854
-		if ($tables == '*')
855
-		{
856
-			$tables = array();
857
-			$result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
858
-			while($row = $db->fetch_row($result))
859
-			{
860
-				$tables[] = $row[0];
861
-			}
862
-		}
863
-		else
864
-		{
865
-			$tables = is_array($tables) ? $tables : explode(',',$tables);
866
-		}
867
-
868
-		//cycle through
869
-		$handle = fopen($outputfile, 'w+');
870
-		if (fwrite($handle, '') === false)
871
-		{
872
-			$langs->load("errors");
873
-			dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
874
-			$errormsg=$langs->trans("ErrorFailedToWriteInDir");
875
-			return -1;
876
-		}
877
-
878
-		// Print headers and global mysql config vars
879
-		$sqlhead = '';
880
-		$sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
767
+                    $numsave = intval($tabmatches[1]);
768
+
769
+                    $gzfiles[$numsave] = $gzfile;
770
+                }
771
+
772
+                krsort($gzfiles, SORT_NUMERIC);
773
+
774
+                foreach($gzfiles as $numsave => $dummy) {
775
+                    if (dol_is_file($logpath.'/'.$logname.'.'.($numsave+1).'.gz')) {
776
+                        return -2;
777
+                    }
778
+
779
+                    if($numsave >= $nbSaves) {
780
+                        dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
781
+                    } else {
782
+                        dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave+1).'.gz', 0, 1, 0, 0);
783
+                    }
784
+                }
785
+
786
+                // Compress current file and recreate it
787
+
788
+                if ($nbSaves > 0) {			// If $nbSaves is 1, we keep 1 archive .gz file, If 2, we keep 2 .gz files
789
+                    $gzfilehandle = gzopen($logpath.'/'.$logname.'.1.gz', 'wb9');
790
+
791
+                    if (empty($gzfilehandle)) {
792
+                        $this->error = 'Failted to open file '.$logpath.'/'.$logname.'.1.gz';
793
+                        return -3;
794
+                    }
795
+
796
+                    $sourcehandle = fopen($logpath.'/'.$logname, 'r');
797
+
798
+                    if (empty($sourcehandle)) {
799
+                        $this->error = 'Failed to open file '.$logpath.'/'.$logname;
800
+                        return -4;
801
+                    }
802
+
803
+                    while(! feof($sourcehandle)) {
804
+                        gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
805
+                    }
806
+
807
+                    fclose($sourcehandle);
808
+                    gzclose($gzfilehandle);
809
+
810
+                    @chmod($logpath.'/'.$logname.'.1.gz', octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
811
+                }
812
+
813
+                dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
814
+
815
+                // Create empty file
816
+                $newlog = fopen($logpath.'/'.$logname, 'a+');
817
+                fclose($newlog);
818
+
819
+                //var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
820
+                @chmod($logpath.'/'.$logname, octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
821
+            }
822
+        }
823
+
824
+        $this->output = 'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.' files) done.';
825
+        return 0;
826
+    }
827
+
828
+    /**	Backup the db OR just a table without mysqldump binary, with PHP only (does not require any exec permission)
829
+     *	Author: David Walsh (http://davidwalsh.name/backup-mysql-database-php)
830
+     *	Updated and enhanced by Stephen Larroque (lrq3000) and by the many commentators from the blog
831
+     *	Note about foreign keys constraints: for Dolibarr, since there are a lot of constraints and when imported the tables will be inserted in the dumped order, not in constraints order, then we ABSOLUTELY need to use SET FOREIGN_KEY_CHECKS=0; when importing the sql dump.
832
+     *	Note2: db2SQL by Howard Yeend can be an alternative, by using SHOW FIELDS FROM and SHOW KEYS FROM we could generate a more precise dump (eg: by getting the type of the field and then precisely outputting the right formatting - in quotes, numeric or null - instead of trying to guess like we are doing now).
833
+     *
834
+     *	@param	string	$outputfile		Output file name
835
+     *	@param	string	$tables			Table name or '*' for all
836
+     *	@return	int						<0 if KO, >0 if OK
837
+     */
838
+    function backupTables($outputfile, $tables='*')
839
+    {
840
+        global $db, $langs;
841
+        global $errormsg;
842
+
843
+        // Set to UTF-8
844
+        if (is_a($db, 'DoliDBMysqli')) {
845
+            /** @var DoliDBMysqli $db */
846
+            $db->db->set_charset('utf8');
847
+        } else {
848
+            /** @var DoliDB $db */
849
+            $db->query('SET NAMES utf8');
850
+            $db->query('SET CHARACTER SET utf8');
851
+        }
852
+
853
+        //get all of the tables
854
+        if ($tables == '*')
855
+        {
856
+            $tables = array();
857
+            $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
858
+            while($row = $db->fetch_row($result))
859
+            {
860
+                $tables[] = $row[0];
861
+            }
862
+        }
863
+        else
864
+        {
865
+            $tables = is_array($tables) ? $tables : explode(',',$tables);
866
+        }
867
+
868
+        //cycle through
869
+        $handle = fopen($outputfile, 'w+');
870
+        if (fwrite($handle, '') === false)
871
+        {
872
+            $langs->load("errors");
873
+            dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
874
+            $errormsg=$langs->trans("ErrorFailedToWriteInDir");
875
+            return -1;
876
+        }
877
+
878
+        // Print headers and global mysql config vars
879
+        $sqlhead = '';
880
+        $sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
881 881
 --
882 882
 -- Host: ".$db->db->host_info."    Database: ".$db->database_name."
883 883
 -- ------------------------------------------------------
@@ -896,77 +896,77 @@  discard block
 block discarded – undo
896 896
 
897 897
 ";
898 898
 
899
-		if (GETPOST("nobin_disable_fk")) $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
900
-		//$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
901
-		if (GETPOST("nobin_use_transaction")) $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
902
-
903
-		fwrite($handle, $sqlhead);
904
-
905
-		$ignore = '';
906
-		if (GETPOST("nobin_sql_ignore")) $ignore = 'IGNORE ';
907
-		$delayed = '';
908
-		if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
909
-
910
-		// Process each table and print their definition + their datas
911
-		foreach($tables as $table)
912
-		{
913
-			// Saving the table structure
914
-			fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
915
-
916
-			if (GETPOST("nobin_drop")) fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
917
-			fwrite($handle,"/*!40101 SET @saved_cs_client     = @@character_set_client */;\n");
918
-			fwrite($handle,"/*!40101 SET character_set_client = utf8 */;\n");
919
-			$resqldrop=$db->query('SHOW CREATE TABLE '.$table);
920
-			$row2 = $db->fetch_row($resqldrop);
921
-			if (empty($row2[1]))
922
-			{
923
-				fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
924
-			}
925
-			else
926
-			{
927
-				fwrite($handle,$row2[1].";\n");
928
-				//fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
929
-
930
-				// Dumping the data (locking the table and disabling the keys check while doing the process)
931
-				fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
932
-				if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
933
-				if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
934
-				else fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
935
-
936
-				$sql='SELECT * FROM '.$table;
937
-				$result = $db->query($sql);
938
-				while($row = $db->fetch_row($result))
939
-				{
940
-					// For each row of data we print a line of INSERT
941
-					fwrite($handle,'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
942
-					$columns = count($row);
943
-					for($j=0; $j<$columns; $j++) {
944
-						// Processing each columns of the row to ensure that we correctly save the value (eg: add quotes for string - in fact we add quotes for everything, it's easier)
945
-						if ($row[$j] == null && !is_string($row[$j])) {
946
-							// IMPORTANT: if the field is NULL we set it NULL
947
-							$row[$j] = 'NULL';
948
-						} elseif(is_string($row[$j]) && $row[$j] == '') {
949
-							// if it's an empty string, we set it as an empty string
950
-							$row[$j] = "''";
951
-						} elseif(is_numeric($row[$j]) && !strcmp($row[$j], $row[$j]+0) ) { // test if it's a numeric type and the numeric version ($nb+0) == string version (eg: if we have 01, it's probably not a number but rather a string, else it would not have any leading 0)
952
-							// if it's a number, we return it as-is
953
-							//	                    $row[$j] = $row[$j];
954
-						} else { // else for all other cases we escape the value and put quotes around
955
-							$row[$j] = addslashes($row[$j]);
956
-							$row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
957
-							$row[$j] = "'".$row[$j]."'";
958
-						}
959
-					}
960
-					fwrite($handle,implode(',', $row).");\n");
961
-				}
962
-				if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
963
-				if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
964
-				fwrite($handle,"\n\n\n");
965
-			}
966
-		}
967
-
968
-		/* Backup Procedure structure*/
969
-		/*
899
+        if (GETPOST("nobin_disable_fk")) $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
900
+        //$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
901
+        if (GETPOST("nobin_use_transaction")) $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
902
+
903
+        fwrite($handle, $sqlhead);
904
+
905
+        $ignore = '';
906
+        if (GETPOST("nobin_sql_ignore")) $ignore = 'IGNORE ';
907
+        $delayed = '';
908
+        if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
909
+
910
+        // Process each table and print their definition + their datas
911
+        foreach($tables as $table)
912
+        {
913
+            // Saving the table structure
914
+            fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
915
+
916
+            if (GETPOST("nobin_drop")) fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
917
+            fwrite($handle,"/*!40101 SET @saved_cs_client     = @@character_set_client */;\n");
918
+            fwrite($handle,"/*!40101 SET character_set_client = utf8 */;\n");
919
+            $resqldrop=$db->query('SHOW CREATE TABLE '.$table);
920
+            $row2 = $db->fetch_row($resqldrop);
921
+            if (empty($row2[1]))
922
+            {
923
+                fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
924
+            }
925
+            else
926
+            {
927
+                fwrite($handle,$row2[1].";\n");
928
+                //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
929
+
930
+                // Dumping the data (locking the table and disabling the keys check while doing the process)
931
+                fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
932
+                if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
933
+                if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
934
+                else fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
935
+
936
+                $sql='SELECT * FROM '.$table;
937
+                $result = $db->query($sql);
938
+                while($row = $db->fetch_row($result))
939
+                {
940
+                    // For each row of data we print a line of INSERT
941
+                    fwrite($handle,'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
942
+                    $columns = count($row);
943
+                    for($j=0; $j<$columns; $j++) {
944
+                        // Processing each columns of the row to ensure that we correctly save the value (eg: add quotes for string - in fact we add quotes for everything, it's easier)
945
+                        if ($row[$j] == null && !is_string($row[$j])) {
946
+                            // IMPORTANT: if the field is NULL we set it NULL
947
+                            $row[$j] = 'NULL';
948
+                        } elseif(is_string($row[$j]) && $row[$j] == '') {
949
+                            // if it's an empty string, we set it as an empty string
950
+                            $row[$j] = "''";
951
+                        } elseif(is_numeric($row[$j]) && !strcmp($row[$j], $row[$j]+0) ) { // test if it's a numeric type and the numeric version ($nb+0) == string version (eg: if we have 01, it's probably not a number but rather a string, else it would not have any leading 0)
952
+                            // if it's a number, we return it as-is
953
+                            //	                    $row[$j] = $row[$j];
954
+                        } else { // else for all other cases we escape the value and put quotes around
955
+                            $row[$j] = addslashes($row[$j]);
956
+                            $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
957
+                            $row[$j] = "'".$row[$j]."'";
958
+                        }
959
+                    }
960
+                    fwrite($handle,implode(',', $row).");\n");
961
+                }
962
+                if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
963
+                if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
964
+                fwrite($handle,"\n\n\n");
965
+            }
966
+        }
967
+
968
+        /* Backup Procedure structure*/
969
+        /*
970 970
 		 $result = $db->query('SHOW PROCEDURE STATUS');
971 971
 		 if ($db->num_rows($result) > 0)
972 972
 		 {
@@ -982,17 +982,17 @@  discard block
 block discarded – undo
982 982
 		 }
983 983
 		 }
984 984
 		 */
985
-		/* Backup Procedure structure*/
985
+        /* Backup Procedure structure*/
986 986
 
987
-		// Write the footer (restore the previous database settings)
988
-		$sqlfooter="\n\n";
989
-		if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
990
-		if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
991
-		$sqlfooter.="\n\n-- Dump completed on ".date('Y-m-d G-i-s');
992
-		fwrite($handle, $sqlfooter);
987
+        // Write the footer (restore the previous database settings)
988
+        $sqlfooter="\n\n";
989
+        if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
990
+        if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
991
+        $sqlfooter.="\n\n-- Dump completed on ".date('Y-m-d G-i-s');
992
+        fwrite($handle, $sqlfooter);
993 993
 
994
-		fclose($handle);
994
+        fclose($handle);
995 995
 
996
-		return 1;
997
-	}
996
+        return 1;
997
+    }
998 998
 }
Please login to merge, or discard this patch.
Spacing   +196 added lines, -196 removed lines patch added patch discarded remove patch
@@ -32,8 +32,8 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public $db;
34 34
 
35
-	var $output;   // Used by Cron method to return message
36
-	var $result;   // Used by Cron method to return data
35
+	var $output; // Used by Cron method to return message
36
+	var $result; // Used by Cron method to return data
37 37
 
38 38
 	/**
39 39
 	 *	Constructor
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 *  @param	string		$choice		Choice of purge mode ('tempfiles', '' or 'tempfilesold' to purge temp older than 24h, 'allfiles', 'logfile')
54 54
 	 *  @return	int						0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
55 55
 	 */
56
-	function purgeFiles($choice='tempfilesold')
56
+	function purgeFiles($choice = 'tempfilesold')
57 57
 	{
58 58
 		global $conf, $langs, $dolibarr_main_data_root;
59 59
 
@@ -62,80 +62,80 @@  discard block
 block discarded – undo
62 62
 		dol_syslog("Utils::purgeFiles choice=".$choice, LOG_DEBUG);
63 63
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
64 64
 
65
-		$filesarray=array();
66
-		if (empty($choice)) $choice='tempfilesold';
65
+		$filesarray = array();
66
+		if (empty($choice)) $choice = 'tempfilesold';
67 67
 
68
-		if ($choice=='tempfiles' || $choice=='tempfilesold')
68
+		if ($choice == 'tempfiles' || $choice == 'tempfilesold')
69 69
 		{
70 70
 			// Delete temporary files
71 71
 			if ($dolibarr_main_data_root)
72 72
 			{
73
-				$filesarray=dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1);	// Do not follow symlinks
73
+				$filesarray = dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1); // Do not follow symlinks
74 74
 				if ($choice == 'tempfilesold')
75 75
 				{
76 76
 					$now = dol_now();
77
-					foreach($filesarray as $key => $val)
77
+					foreach ($filesarray as $key => $val)
78 78
 					{
79
-						if ($val['date'] > ($now - (24 * 3600))) unset($filesarray[$key]);	// Discard files not older than 24h
79
+						if ($val['date'] > ($now - (24 * 3600))) unset($filesarray[$key]); // Discard files not older than 24h
80 80
 					}
81 81
 				}
82 82
 			}
83 83
 		}
84 84
 
85
-		if ($choice=='allfiles')
85
+		if ($choice == 'allfiles')
86 86
 		{
87 87
 			// Delete all files (except install.lock, do not follow symbolic links)
88 88
 			if ($dolibarr_main_data_root)
89 89
 			{
90
-				$filesarray=dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
90
+				$filesarray = dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
91 91
 			}
92 92
 		}
93 93
 
94
-		if ($choice=='logfile')
94
+		if ($choice == 'logfile')
95 95
 		{
96 96
 			// Define files log
97 97
 			if ($dolibarr_main_data_root)
98 98
 			{
99
-				$filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
99
+				$filesarray = dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1);
100 100
 			}
101 101
 
102
-			$filelog='';
103
-			if (! empty($conf->syslog->enabled))
102
+			$filelog = '';
103
+			if (!empty($conf->syslog->enabled))
104 104
 			{
105
-				$filelog=$conf->global->SYSLOG_FILE;
106
-				$filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
105
+				$filelog = $conf->global->SYSLOG_FILE;
106
+				$filelog = preg_replace('/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog);
107 107
 
108
-				$alreadyincluded=false;
108
+				$alreadyincluded = false;
109 109
 				foreach ($filesarray as $tmpcursor)
110 110
 				{
111
-					if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded=true; }
111
+					if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded = true; }
112 112
 				}
113
-				if (! $alreadyincluded) $filesarray[]=array('fullname'=>$filelog,'type'=>'file');
113
+				if (!$alreadyincluded) $filesarray[] = array('fullname'=>$filelog, 'type'=>'file');
114 114
 			}
115 115
 		}
116 116
 
117
-		$count=0;
118
-		$countdeleted=0;
119
-		$counterror=0;
117
+		$count = 0;
118
+		$countdeleted = 0;
119
+		$counterror = 0;
120 120
 		if (count($filesarray))
121 121
 		{
122
-			foreach($filesarray as $key => $value)
122
+			foreach ($filesarray as $key => $value)
123 123
 			{
124 124
 				//print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']."<br>\n";
125 125
 				if ($filesarray[$key]['type'] == 'dir')
126 126
 				{
127
-					$startcount=0;
128
-					$tmpcountdeleted=0;
129
-					$result=dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted);
130
-					$count+=$result;
131
-					$countdeleted+=$tmpcountdeleted;
127
+					$startcount = 0;
128
+					$tmpcountdeleted = 0;
129
+					$result = dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted);
130
+					$count += $result;
131
+					$countdeleted += $tmpcountdeleted;
132 132
 				}
133 133
 				elseif ($filesarray[$key]['type'] == 'file')
134 134
 				{
135 135
 					// If (file that is not logfile) or (if mode is logfile)
136
-					if ($filesarray[$key]['fullname'] != $filelog || $choice=='logfile')
136
+					if ($filesarray[$key]['fullname'] != $filelog || $choice == 'logfile')
137 137
 					{
138
-						$result=dol_delete_file($filesarray[$key]['fullname'], 1, 1);
138
+						$result = dol_delete_file($filesarray[$key]['fullname'], 1, 1);
139 139
 						if ($result)
140 140
 						{
141 141
 							$count++;
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 			}
151 151
 
152 152
 			// Update cachenbofdoc
153
-			if (! empty($conf->ecm->enabled) && $choice=='allfiles')
153
+			if (!empty($conf->ecm->enabled) && $choice == 'allfiles')
154 154
 			{
155 155
 				require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
156 156
 				$ecmdirstatic = new EcmDirectory($this->db);
@@ -160,13 +160,13 @@  discard block
 block discarded – undo
160 160
 
161 161
 		if ($count > 0)
162 162
 		{
163
-			$this->output=$langs->trans("PurgeNDirectoriesDeleted", $countdeleted);
164
-			if ($count > $countdeleted) $this->output.='<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
163
+			$this->output = $langs->trans("PurgeNDirectoriesDeleted", $countdeleted);
164
+			if ($count > $countdeleted) $this->output .= '<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
165 165
 		}
166
-		else $this->output=$langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)':'');
166
+		else $this->output = $langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)' : '');
167 167
 
168 168
 		//return $count;
169
-		return 0;     // This function can be called by cron so must return 0 if OK
169
+		return 0; // This function can be called by cron so must return 0 if OK
170 170
 	}
171 171
 
172 172
 
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 	 *  @param	int		    $execmethod		   0=Use default method (that is 1 by default), 1=Use the PHP 'exec', 2=Use the 'popen' method
183 183
 	 *  @return	int						       0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
184 184
 	 */
185
-	function dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0, $execmethod=0)
185
+	function dumpDatabase($compression = 'none', $type = 'auto', $usedefault = 1, $file = 'auto', $keeplastnfiles = 0, $execmethod = 0)
186 186
 	{
187 187
 		global $db, $conf, $langs, $dolibarr_main_data_root;
188 188
 		global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
@@ -193,112 +193,112 @@  discard block
 block discarded – undo
193 193
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
194 194
 
195 195
 		// Check compression parameter
196
-		if (! in_array($compression, array('none', 'gz', 'bz', 'zip')))
196
+		if (!in_array($compression, array('none', 'gz', 'bz', 'zip')))
197 197
 		{
198 198
 			$langs->load("errors");
199
-			$this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
199
+			$this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
200 200
 			return -1;
201 201
 		}
202 202
 
203 203
 		// Check type parameter
204 204
 		if ($type == 'auto') $type = $db->type;
205
-		if (! in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin')))
205
+		if (!in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin')))
206 206
 		{
207 207
 			$langs->load("errors");
208
-			$this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
208
+			$this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
209 209
 			return -1;
210 210
 		}
211 211
 
212 212
 		// Check file parameter
213 213
 		if ($file == 'auto')
214 214
 		{
215
-			$prefix='dump';
216
-			$ext='sql';
217
-			if (in_array($type, array('mysql', 'mysqli')))  { $prefix='mysqldump'; $ext='sql'; }
215
+			$prefix = 'dump';
216
+			$ext = 'sql';
217
+			if (in_array($type, array('mysql', 'mysqli'))) { $prefix = 'mysqldump'; $ext = 'sql'; }
218 218
 			//if ($label == 'PostgreSQL') { $prefix='pg_dump'; $ext='dump'; }
219
-			if (in_array($type, array('pgsql'))) { $prefix='pg_dump'; $ext='sql'; }
220
-			$file=$prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.strftime("%Y%m%d%H%M").'.'.$ext;
219
+			if (in_array($type, array('pgsql'))) { $prefix = 'pg_dump'; $ext = 'sql'; }
220
+			$file = $prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.strftime("%Y%m%d%H%M").'.'.$ext;
221 221
 		}
222 222
 
223
-		$outputdir  = $conf->admin->dir_output.'/backup';
224
-		$result=dol_mkdir($outputdir);
223
+		$outputdir = $conf->admin->dir_output.'/backup';
224
+		$result = dol_mkdir($outputdir);
225 225
 
226 226
 
227 227
 		// MYSQL
228 228
 		if ($type == 'mysql' || $type == 'mysqli')
229 229
 		{
230
-			$cmddump=$conf->global->SYSTEMTOOLS_MYSQLDUMP;
230
+			$cmddump = $conf->global->SYSTEMTOOLS_MYSQLDUMP;
231 231
 
232 232
 
233 233
 			$outputfile = $outputdir.'/'.$file;
234 234
 			// for compression format, we add extension
235
-			$compression=$compression ? $compression : 'none';
236
-			if ($compression == 'gz') $outputfile.='.gz';
237
-			if ($compression == 'bz') $outputfile.='.bz2';
235
+			$compression = $compression ? $compression : 'none';
236
+			if ($compression == 'gz') $outputfile .= '.gz';
237
+			if ($compression == 'bz') $outputfile .= '.bz2';
238 238
 			$outputerror = $outputfile.'.err';
239 239
 			dol_mkdir($conf->admin->dir_output.'/backup');
240 240
 
241 241
 			// Parameteres execution
242
-			$command=$cmddump;
243
-			if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
242
+			$command = $cmddump;
243
+			if (preg_match("/\s/", $command)) $command = escapeshellarg($command); // Use quotes on command
244 244
 
245 245
 			//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
246
-			$param=$dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
247
-			$param.=" -u ".$dolibarr_main_db_user;
248
-			if (! empty($dolibarr_main_db_port)) $param.=" -P ".$dolibarr_main_db_port;
249
-			if (! GETPOST("use_transaction"))    $param.=" -l --single-transaction";
250
-			if (GETPOST("disable_fk") || $usedefault) $param.=" -K";
251
-			if (GETPOST("sql_compat") && GETPOST("sql_compat") != 'NONE') $param.=" --compatible=".escapeshellarg(GETPOST("sql_compat","alpha"));
252
-			if (GETPOST("drop_database"))        $param.=" --add-drop-database";
246
+			$param = $dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
247
+			$param .= " -u ".$dolibarr_main_db_user;
248
+			if (!empty($dolibarr_main_db_port)) $param .= " -P ".$dolibarr_main_db_port;
249
+			if (!GETPOST("use_transaction"))    $param .= " -l --single-transaction";
250
+			if (GETPOST("disable_fk") || $usedefault) $param .= " -K";
251
+			if (GETPOST("sql_compat") && GETPOST("sql_compat") != 'NONE') $param .= " --compatible=".escapeshellarg(GETPOST("sql_compat", "alpha"));
252
+			if (GETPOST("drop_database"))        $param .= " --add-drop-database";
253 253
 			if (GETPOST("sql_structure") || $usedefault)
254 254
 			{
255
-				if (GETPOST("drop") || $usedefault)	$param.=" --add-drop-table=TRUE";
256
-				else 							    $param.=" --add-drop-table=FALSE";
255
+				if (GETPOST("drop") || $usedefault)	$param .= " --add-drop-table=TRUE";
256
+				else 							    $param .= " --add-drop-table=FALSE";
257 257
 			}
258 258
 			else
259 259
 			{
260
-				$param.=" -t";
260
+				$param .= " -t";
261 261
 			}
262
-			if (GETPOST("disable-add-locks")) $param.=" --add-locks=FALSE";
262
+			if (GETPOST("disable-add-locks")) $param .= " --add-locks=FALSE";
263 263
 			if (GETPOST("sql_data") || $usedefault)
264 264
 			{
265
-				$param.=" --tables";
266
-				if (GETPOST("showcolumns") || $usedefault)	 $param.=" -c";
267
-				if (GETPOST("extended_ins") || $usedefault) $param.=" -e";
268
-				else $param.=" --skip-extended-insert";
269
-				if (GETPOST("delayed"))	 	 $param.=" --delayed-insert";
270
-				if (GETPOST("sql_ignore"))	 $param.=" --insert-ignore";
271
-				if (GETPOST("hexforbinary") || $usedefault) $param.=" --hex-blob";
265
+				$param .= " --tables";
266
+				if (GETPOST("showcolumns") || $usedefault)	 $param .= " -c";
267
+				if (GETPOST("extended_ins") || $usedefault) $param .= " -e";
268
+				else $param .= " --skip-extended-insert";
269
+				if (GETPOST("delayed"))	 	 $param .= " --delayed-insert";
270
+				if (GETPOST("sql_ignore"))	 $param .= " --insert-ignore";
271
+				if (GETPOST("hexforbinary") || $usedefault) $param .= " --hex-blob";
272 272
 			}
273 273
 			else
274 274
 			{
275
-				$param.=" -d";    // No row information (no data)
275
+				$param .= " -d"; // No row information (no data)
276 276
 			}
277
-			$param.=" --default-character-set=utf8";    // We always save output into utf8 charset
278
-			$paramcrypted=$param;
279
-			$paramclear=$param;
280
-			if (! empty($dolibarr_main_db_pass))
277
+			$param .= " --default-character-set=utf8"; // We always save output into utf8 charset
278
+			$paramcrypted = $param;
279
+			$paramclear = $param;
280
+			if (!empty($dolibarr_main_db_pass))
281 281
 			{
282
-				$paramcrypted.=' -p"'.preg_replace('/./i','*',$dolibarr_main_db_pass).'"';
283
-				$paramclear.=' -p"'.str_replace(array('"','`'),array('\"','\`'),$dolibarr_main_db_pass).'"';
282
+				$paramcrypted .= ' -p"'.preg_replace('/./i', '*', $dolibarr_main_db_pass).'"';
283
+				$paramclear .= ' -p"'.str_replace(array('"', '`'), array('\"', '\`'), $dolibarr_main_db_pass).'"';
284 284
 			}
285 285
 
286
-			$errormsg='';
286
+			$errormsg = '';
287 287
 			$handle = '';
288 288
 
289 289
 			// Start call method to execute dump
290
-			$fullcommandcrypted=$command." ".$paramcrypted." 2>&1";
291
-			$fullcommandclear=$command." ".$paramclear." 2>&1";
290
+			$fullcommandcrypted = $command." ".$paramcrypted." 2>&1";
291
+			$fullcommandclear = $command." ".$paramclear." 2>&1";
292 292
 			if ($compression == 'none') $handle = fopen($outputfile, 'w');
293 293
 			if ($compression == 'gz')   $handle = gzopen($outputfile, 'w');
294 294
 			if ($compression == 'bz')   $handle = bzopen($outputfile, 'w');
295 295
 
296 296
 			if ($handle)
297 297
 			{
298
-				if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
299
-				if (empty($execmethod)) $execmethod=1;
298
+				if (!empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod = $conf->global->MAIN_EXEC_USE_POPEN;
299
+				if (empty($execmethod)) $execmethod = 1;
300 300
 
301
-				$ok=0;
301
+				$ok = 0;
302 302
 				dol_syslog("Utils::dumpDatabase execmethod=".$execmethod." command:".$fullcommandcrypted, LOG_DEBUG);
303 303
 
304 304
 				// TODO Replace with executeCLI function
@@ -312,35 +312,35 @@  discard block
 block discarded – undo
312 312
 						$langs->load("errors");
313 313
 						dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
314 314
 						$error = 'Error '.$retval;
315
-						$ok=0;
315
+						$ok = 0;
316 316
 					}
317 317
 					else
318 318
 					{
319
-						$i=0;
319
+						$i = 0;
320 320
 						if (!empty($readt))
321
-						foreach($readt as $key=>$read)
321
+						foreach ($readt as $key=>$read)
322 322
 						{
323
-							$i++;   // output line number
323
+							$i++; // output line number
324 324
 							if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
325 325
 							fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
326
-							if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
327
-							elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
326
+							if (preg_match('/'.preg_quote('-- Dump completed').'/i', $read)) $ok = 1;
327
+							elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i', $read)) $ok = 1;
328 328
 						}
329 329
 					}
330 330
 				}
331 331
 				if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
332 332
 				{
333 333
 					$handlein = popen($fullcommandclear, 'r');
334
-					$i=0;
334
+					$i = 0;
335 335
 					while (!feof($handlein))
336 336
 					{
337
-						$i++;   // output line number
337
+						$i++; // output line number
338 338
 						$read = fgets($handlein);
339 339
 						// Exclude warning line we don't want
340 340
 						if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
341
-						fwrite($handle,$read);
342
-						if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
343
-						elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
341
+						fwrite($handle, $read);
342
+						if (preg_match('/'.preg_quote('-- Dump completed').'/i', $read)) $ok = 1;
343
+						elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i', $read)) $ok = 1;
344 344
 					}
345 345
 					pclose($handlein);
346 346
 				}
@@ -350,14 +350,14 @@  discard block
 block discarded – undo
350 350
 				if ($compression == 'gz')   gzclose($handle);
351 351
 				if ($compression == 'bz')   bzclose($handle);
352 352
 
353
-				if (! empty($conf->global->MAIN_UMASK))
353
+				if (!empty($conf->global->MAIN_UMASK))
354 354
 					@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
355 355
 			}
356 356
 			else
357 357
 			{
358 358
 				$langs->load("errors");
359
-				dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
360
-				$errormsg=$langs->trans("ErrorFailedToWriteInDir");
359
+				dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
360
+				$errormsg = $langs->trans("ErrorFailedToWriteInDir");
361 361
 			}
362 362
 
363 363
 			// Get errorstring
@@ -367,23 +367,23 @@  discard block
 block discarded – undo
367 367
 			if ($handle)
368 368
 			{
369 369
 				// Get 2048 first chars of error message.
370
-				$errormsg = fgets($handle,2048);
370
+				$errormsg = fgets($handle, 2048);
371 371
 				// Close file
372 372
 				if ($compression == 'none') fclose($handle);
373 373
 				if ($compression == 'gz')   gzclose($handle);
374 374
 				if ($compression == 'bz')   bzclose($handle);
375
-				if ($ok && preg_match('/^-- MySql/i',$errormsg)) $errormsg='';	// Pas erreur
375
+				if ($ok && preg_match('/^-- MySql/i', $errormsg)) $errormsg = ''; // Pas erreur
376 376
 				else
377 377
 				{
378 378
 					// Renommer fichier sortie en fichier erreur
379 379
 					//print "$outputfile -> $outputerror";
380 380
 					@dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
381
-					@rename($outputfile,$outputerror);
381
+					@rename($outputfile, $outputerror);
382 382
 					// Si safe_mode on et command hors du parametre exec, on a un fichier out vide donc errormsg vide
383
-					if (! $errormsg)
383
+					if (!$errormsg)
384 384
 					{
385 385
 						$langs->load("errors");
386
-						$errormsg=$langs->trans("ErrorFailedToRunExternalCommand");
386
+						$errormsg = $langs->trans("ErrorFailedToRunExternalCommand");
387 387
 					}
388 388
 				}
389 389
 			}
@@ -401,9 +401,9 @@  discard block
 block discarded – undo
401 401
 			$outputfile = $outputdir.'/'.$file;
402 402
 			$outputfiletemp = $outputfile.'-TMP.sql';
403 403
 			// for compression format, we add extension
404
-			$compression=$compression ? $compression : 'none';
405
-			if ($compression == 'gz') $outputfile.='.gz';
406
-			if ($compression == 'bz') $outputfile.='.bz2';
404
+			$compression = $compression ? $compression : 'none';
405
+			if ($compression == 'gz') $outputfile .= '.gz';
406
+			if ($compression == 'bz') $outputfile .= '.bz2';
407 407
 			$outputerror = $outputfile.'.err';
408 408
 			dol_mkdir($conf->admin->dir_output.'/backup');
409 409
 
@@ -425,51 +425,51 @@  discard block
 block discarded – undo
425 425
 		// POSTGRESQL
426 426
 		if ($type == 'postgresql' || $type == 'pgsql')
427 427
 		{
428
-			$cmddump=$conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
428
+			$cmddump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
429 429
 
430 430
 			$outputfile = $outputdir.'/'.$file;
431 431
 			// for compression format, we add extension
432
-			$compression=$compression ? $compression : 'none';
433
-			if ($compression == 'gz') $outputfile.='.gz';
434
-			if ($compression == 'bz') $outputfile.='.bz2';
432
+			$compression = $compression ? $compression : 'none';
433
+			if ($compression == 'gz') $outputfile .= '.gz';
434
+			if ($compression == 'bz') $outputfile .= '.bz2';
435 435
 			$outputerror = $outputfile.'.err';
436 436
 			dol_mkdir($conf->admin->dir_output.'/backup');
437 437
 
438 438
 			// Parameteres execution
439
-			$command=$cmddump;
440
-			if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
439
+			$command = $cmddump;
440
+			if (preg_match("/\s/", $command)) $command = escapeshellarg($command); // Use quotes on command
441 441
 
442 442
 			//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
443 443
 			//$param="-F c";
444
-			$param="-F p";
445
-			$param.=" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
446
-			$param.=" -U ".$dolibarr_main_db_user;
447
-			if (! empty($dolibarr_main_db_port)) $param.=" -p ".$dolibarr_main_db_port;
448
-			if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param.="  --disable-dollar-quoting";
449
-			if (GETPOST("drop_database"))        $param.=" -c -C";
444
+			$param = "-F p";
445
+			$param .= " --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
446
+			$param .= " -U ".$dolibarr_main_db_user;
447
+			if (!empty($dolibarr_main_db_port)) $param .= " -p ".$dolibarr_main_db_port;
448
+			if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param .= "  --disable-dollar-quoting";
449
+			if (GETPOST("drop_database"))        $param .= " -c -C";
450 450
 			if (GETPOST("sql_structure"))
451 451
 			{
452
-				if (GETPOST("drop"))			 $param.=" --add-drop-table";
453
-				if (! GETPOST("sql_data"))       $param.=" -s";
452
+				if (GETPOST("drop"))			 $param .= " --add-drop-table";
453
+				if (!GETPOST("sql_data"))       $param .= " -s";
454 454
 			}
455 455
 			if (GETPOST("sql_data"))
456 456
 			{
457
-				if (! GETPOST("sql_structure"))	 $param.=" -a";
458
-				if (GETPOST("showcolumns"))	     $param.=" -c";
457
+				if (!GETPOST("sql_structure"))	 $param .= " -a";
458
+				if (GETPOST("showcolumns"))	     $param .= " -c";
459 459
 			}
460
-			$param.=' -f "'.$outputfile.'"';
460
+			$param .= ' -f "'.$outputfile.'"';
461 461
 			//if ($compression == 'none')
462
-			if ($compression == 'gz')   $param.=' -Z 9';
462
+			if ($compression == 'gz')   $param .= ' -Z 9';
463 463
 			//if ($compression == 'bz')
464
-			$paramcrypted=$param;
465
-			$paramclear=$param;
464
+			$paramcrypted = $param;
465
+			$paramclear = $param;
466 466
 			/*if (! empty($dolibarr_main_db_pass))
467 467
 			 {
468 468
 			 $paramcrypted.=" -W".preg_replace('/./i','*',$dolibarr_main_db_pass);
469 469
 			 $paramclear.=" -W".$dolibarr_main_db_pass;
470 470
 			 }*/
471
-			$paramcrypted.=" -w ".$dolibarr_main_db_name;
472
-			$paramclear.=" -w ".$dolibarr_main_db_name;
471
+			$paramcrypted .= " -w ".$dolibarr_main_db_name;
472
+			$paramclear .= " -w ".$dolibarr_main_db_name;
473 473
 
474 474
 			$this->output = "";
475 475
 			$this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => $command." ".$paramcrypted);
@@ -479,8 +479,8 @@  discard block
 block discarded – undo
479 479
 		if ($keeplastnfiles > 0)
480 480
 		{
481 481
 			$tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
482
-			$i=0;
483
-			foreach($tmpfiles as $key => $val)
482
+			$i = 0;
483
+			foreach ($tmpfiles as $key => $val)
484 484
 			{
485 485
 				$i++;
486 486
 				if ($i <= $keeplastnfiles) continue;
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 	 * @param	int		$execmethod		0=Use default method (that is 1 by default), 1=Use the PHP 'exec', 2=Use the 'popen' method
502 502
 	 * @return	array					array('result'=>...,'output'=>...,'error'=>...). result = 0 means OK.
503 503
 	 */
504
-	function executeCLI($command, $outputfile, $execmethod=0)
504
+	function executeCLI($command, $outputfile, $execmethod = 0)
505 505
 	{
506 506
 		global $conf, $langs;
507 507
 
@@ -509,15 +509,15 @@  discard block
 block discarded – undo
509 509
 		$output = '';
510 510
 		$error = '';
511 511
 
512
-		$command=escapeshellcmd($command);
513
-		$command.=" 2>&1";
512
+		$command = escapeshellcmd($command);
513
+		$command .= " 2>&1";
514 514
 
515
-		if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
516
-		if (empty($execmethod)) $execmethod=1;
515
+		if (!empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod = $conf->global->MAIN_EXEC_USE_POPEN;
516
+		if (empty($execmethod)) $execmethod = 1;
517 517
 		//$execmethod=1;
518 518
 
519 519
 		dol_syslog("Utils::executeCLI execmethod=".$execmethod." system:".$command, LOG_DEBUG);
520
-		$output_arr=array();
520
+		$output_arr = array();
521 521
 
522 522
 		if ($execmethod == 1)
523 523
 		{
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 		}
533 533
 		if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
534 534
 		{
535
-			$ok=0;
535
+			$ok = 0;
536 536
 			$handle = fopen($outputfile, 'w+b');
537 537
 			if ($handle)
538 538
 			{
@@ -541,21 +541,21 @@  discard block
 block discarded – undo
541 541
 				while (!feof($handlein))
542 542
 				{
543 543
 					$read = fgets($handlein);
544
-					fwrite($handle,$read);
545
-					$output_arr[]=$read;
544
+					fwrite($handle, $read);
545
+					$output_arr[] = $read;
546 546
 				}
547 547
 				pclose($handlein);
548 548
 				fclose($handle);
549 549
 			}
550
-			if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
550
+			if (!empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
551 551
 		}
552 552
 
553 553
 		// Update with result
554
-		if (is_array($output_arr) && count($output_arr)>0)
554
+		if (is_array($output_arr) && count($output_arr) > 0)
555 555
 		{
556
-			foreach($output_arr as $val)
556
+			foreach ($output_arr as $val)
557 557
 			{
558
-				$output.=$val.($execmethod == 2 ? '' : "\n");
558
+				$output .= $val.($execmethod == 2 ? '' : "\n");
559 559
 			}
560 560
 		}
561 561
 
@@ -577,23 +577,23 @@  discard block
 block discarded – undo
577 577
 
578 578
 		$error = 0;
579 579
 
580
-		$modulelowercase=strtolower($module);
580
+		$modulelowercase = strtolower($module);
581 581
 
582 582
 		// Dir for module
583 583
 		$dir = $dirins.'/'.$modulelowercase;
584 584
 		// Zip file to build
585
-		$FILENAMEDOC='';
585
+		$FILENAMEDOC = '';
586 586
 
587 587
 		// Load module
588 588
 		dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
589
-		$class='mod'.$module;
589
+		$class = 'mod'.$module;
590 590
 
591 591
 		if (class_exists($class))
592 592
 		{
593 593
 			try {
594 594
 				$moduleobj = new $class($this->db);
595 595
 			}
596
-			catch(Exception $e)
596
+			catch (Exception $e)
597 597
 			{
598 598
 				$error++;
599 599
 				dol_print_error($e->getMessage());
@@ -607,41 +607,41 @@  discard block
 block discarded – undo
607 607
 			exit;
608 608
 		}
609 609
 
610
-		$arrayversion=explode('.',$moduleobj->version,3);
610
+		$arrayversion = explode('.', $moduleobj->version, 3);
611 611
 		if (count($arrayversion))
612 612
 		{
613
-			$FILENAMEASCII=strtolower($module).'.asciidoc';
614
-			$FILENAMEDOC=strtolower($module).'.html';			// TODO Use/text PDF
613
+			$FILENAMEASCII = strtolower($module).'.asciidoc';
614
+			$FILENAMEDOC = strtolower($module).'.html'; // TODO Use/text PDF
615 615
 
616 616
 			$dirofmodule = dol_buildpath(strtolower($module), 0).'/doc';
617 617
 			$dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
618 618
 			$outputfiledoc = $dirofmodule.'/'.$FILENAMEDOC;
619 619
 			if ($dirofmodule)
620 620
 			{
621
-				if (! dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule);
622
-				if (! dol_is_dir($dirofmoduletmp)) dol_mkdir($dirofmoduletmp);
623
-				if (! is_writable($dirofmoduletmp))
621
+				if (!dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule);
622
+				if (!dol_is_dir($dirofmoduletmp)) dol_mkdir($dirofmoduletmp);
623
+				if (!is_writable($dirofmoduletmp))
624 624
 				{
625 625
 					$this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
626 626
 					return -1;
627 627
 				}
628 628
 
629
-				$destfile=$dirofmoduletmp.'/'.$FILENAMEASCII;
629
+				$destfile = $dirofmoduletmp.'/'.$FILENAMEASCII;
630 630
 
631 631
 				$fhandle = fopen($destfile, 'w+');
632 632
 				if ($fhandle)
633 633
 				{
634
-					$specs=dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
634
+					$specs = dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
635 635
 
636 636
 					$i = 0;
637 637
 					foreach ($specs as $spec)
638 638
 					{
639
-						if (preg_match('/notindoc/', $spec['relativename'])) continue;	// Discard file
640
-						if (preg_match('/disabled/', $spec['relativename'])) continue;	// Discard file
639
+						if (preg_match('/notindoc/', $spec['relativename'])) continue; // Discard file
640
+						if (preg_match('/disabled/', $spec['relativename'])) continue; // Discard file
641 641
 
642 642
 						$pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
643
-						$format='asciidoc';
644
-						if (preg_match('/\.md$/i', $spec['name'])) $format='markdown';
643
+						$format = 'asciidoc';
644
+						if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown';
645 645
 
646 646
 						$filecursor = @file_get_contents($spec['fullname']);
647 647
 						if ($filecursor)
@@ -665,15 +665,15 @@  discard block
 block discarded – undo
665 665
 					fclose($fhandle);
666 666
 				}
667 667
 
668
-				$conf->global->MODULEBUILDER_ASCIIDOCTOR='asciidoctor';
668
+				$conf->global->MODULEBUILDER_ASCIIDOCTOR = 'asciidoctor';
669 669
 				if (empty($conf->global->MODULEBUILDER_ASCIIDOCTOR))
670 670
 				{
671 671
 					dol_print_error('', 'Module setup not complete');
672 672
 					exit;
673 673
 				}
674 674
 
675
-				$command=$conf->global->MODULEBUILDER_ASCIIDOCTOR.' '.$destfile.' -n -o '.$dirofmodule.'/'.$FILENAMEDOC;
676
-				$outfile=$dirofmoduletmp.'/out.tmp';
675
+				$command = $conf->global->MODULEBUILDER_ASCIIDOCTOR.' '.$destfile.' -n -o '.$dirofmodule.'/'.$FILENAMEDOC;
676
+				$outfile = $dirofmoduletmp.'/out.tmp';
677 677
 
678 678
 				require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
679 679
 				$utils = new Utils($db);
@@ -721,18 +721,18 @@  discard block
 block discarded – undo
721 721
     {
722 722
 		global $conf;
723 723
 
724
-		if(empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
724
+		if (empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
725 725
 			return 0;
726 726
 		}
727 727
 
728
-		if(! function_exists('gzopen')) {
728
+		if (!function_exists('gzopen')) {
729 729
 			$this->error = 'Support for gzopen not available in this PHP';
730 730
 			return -1;
731 731
 		}
732 732
 
733 733
 		dol_include_once('/core/lib/files.lib.php');
734 734
 
735
-		$nbSaves = ! empty($conf->global->SYSLOG_FILE_SAVES) ? intval($conf->global->SYSLOG_FILE_SAVES) : 14;
735
+		$nbSaves = !empty($conf->global->SYSLOG_FILE_SAVES) ? intval($conf->global->SYSLOG_FILE_SAVES) : 14;
736 736
 
737 737
 		if (empty($conf->global->SYSLOG_FILE)) {
738 738
 			$mainlogdir = DOL_DATA_ROOT;
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
 		$tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
747 747
 		$tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
748 748
 
749
-		foreach($tabfiles as $file) {
749
+		foreach ($tabfiles as $file) {
750 750
 
751 751
 			$logname = $file['name'];
752 752
 			$logpath = $file['path'];
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
 				$gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
761 761
 				$gzfiles = array();
762 762
 
763
-				foreach($gzfilestmp as $gzfile) {
763
+				foreach ($gzfilestmp as $gzfile) {
764 764
 					$tabmatches = array();
765 765
 					preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
766 766
 
@@ -771,15 +771,15 @@  discard block
 block discarded – undo
771 771
 
772 772
 				krsort($gzfiles, SORT_NUMERIC);
773 773
 
774
-				foreach($gzfiles as $numsave => $dummy) {
775
-					if (dol_is_file($logpath.'/'.$logname.'.'.($numsave+1).'.gz')) {
774
+				foreach ($gzfiles as $numsave => $dummy) {
775
+					if (dol_is_file($logpath.'/'.$logname.'.'.($numsave + 1).'.gz')) {
776 776
 						return -2;
777 777
 					}
778 778
 
779
-					if($numsave >= $nbSaves) {
779
+					if ($numsave >= $nbSaves) {
780 780
 						dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
781 781
 					} else {
782
-						dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave+1).'.gz', 0, 1, 0, 0);
782
+						dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave + 1).'.gz', 0, 1, 0, 0);
783 783
 					}
784 784
 				}
785 785
 
@@ -800,14 +800,14 @@  discard block
 block discarded – undo
800 800
 						return -4;
801 801
 					}
802 802
 
803
-					while(! feof($sourcehandle)) {
803
+					while (!feof($sourcehandle)) {
804 804
 						gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
805 805
 					}
806 806
 
807 807
 					fclose($sourcehandle);
808 808
 					gzclose($gzfilehandle);
809 809
 
810
-					@chmod($logpath.'/'.$logname.'.1.gz', octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
810
+					@chmod($logpath.'/'.$logname.'.1.gz', octdec(empty($conf->global->MAIN_UMASK) ? '0664' : $conf->global->MAIN_UMASK));
811 811
 				}
812 812
 
813 813
 				dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
@@ -817,7 +817,7 @@  discard block
 block discarded – undo
817 817
 				fclose($newlog);
818 818
 
819 819
 				//var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
820
-				@chmod($logpath.'/'.$logname, octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
820
+				@chmod($logpath.'/'.$logname, octdec(empty($conf->global->MAIN_UMASK) ? '0664' : $conf->global->MAIN_UMASK));
821 821
 			}
822 822
 		}
823 823
 
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 	 *	@param	string	$tables			Table name or '*' for all
836 836
 	 *	@return	int						<0 if KO, >0 if OK
837 837
 	 */
838
-	function backupTables($outputfile, $tables='*')
838
+	function backupTables($outputfile, $tables = '*')
839 839
 	{
840 840
 		global $db, $langs;
841 841
 		global $errormsg;
@@ -855,14 +855,14 @@  discard block
 block discarded – undo
855 855
 		{
856 856
 			$tables = array();
857 857
 			$result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
858
-			while($row = $db->fetch_row($result))
858
+			while ($row = $db->fetch_row($result))
859 859
 			{
860 860
 				$tables[] = $row[0];
861 861
 			}
862 862
 		}
863 863
 		else
864 864
 		{
865
-			$tables = is_array($tables) ? $tables : explode(',',$tables);
865
+			$tables = is_array($tables) ? $tables : explode(',', $tables);
866 866
 		}
867 867
 
868 868
 		//cycle through
@@ -870,8 +870,8 @@  discard block
 block discarded – undo
870 870
 		if (fwrite($handle, '') === false)
871 871
 		{
872 872
 			$langs->load("errors");
873
-			dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
874
-			$errormsg=$langs->trans("ErrorFailedToWriteInDir");
873
+			dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
874
+			$errormsg = $langs->trans("ErrorFailedToWriteInDir");
875 875
 			return -1;
876 876
 		}
877 877
 
@@ -908,15 +908,15 @@  discard block
 block discarded – undo
908 908
 		if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
909 909
 
910 910
 		// Process each table and print their definition + their datas
911
-		foreach($tables as $table)
911
+		foreach ($tables as $table)
912 912
 		{
913 913
 			// Saving the table structure
914 914
 			fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
915 915
 
916
-			if (GETPOST("nobin_drop")) fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
917
-			fwrite($handle,"/*!40101 SET @saved_cs_client     = @@character_set_client */;\n");
918
-			fwrite($handle,"/*!40101 SET character_set_client = utf8 */;\n");
919
-			$resqldrop=$db->query('SHOW CREATE TABLE '.$table);
916
+			if (GETPOST("nobin_drop")) fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
917
+			fwrite($handle, "/*!40101 SET @saved_cs_client     = @@character_set_client */;\n");
918
+			fwrite($handle, "/*!40101 SET character_set_client = utf8 */;\n");
919
+			$resqldrop = $db->query('SHOW CREATE TABLE '.$table);
920 920
 			$row2 = $db->fetch_row($resqldrop);
921 921
 			if (empty($row2[1]))
922 922
 			{
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 			}
925 925
 			else
926 926
 			{
927
-				fwrite($handle,$row2[1].";\n");
927
+				fwrite($handle, $row2[1].";\n");
928 928
 				//fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
929 929
 
930 930
 				// Dumping the data (locking the table and disabling the keys check while doing the process)
@@ -933,22 +933,22 @@  discard block
 block discarded – undo
933 933
 				if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
934 934
 				else fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
935 935
 
936
-				$sql='SELECT * FROM '.$table;
936
+				$sql = 'SELECT * FROM '.$table;
937 937
 				$result = $db->query($sql);
938
-				while($row = $db->fetch_row($result))
938
+				while ($row = $db->fetch_row($result))
939 939
 				{
940 940
 					// For each row of data we print a line of INSERT
941
-					fwrite($handle,'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
941
+					fwrite($handle, 'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
942 942
 					$columns = count($row);
943
-					for($j=0; $j<$columns; $j++) {
943
+					for ($j = 0; $j < $columns; $j++) {
944 944
 						// Processing each columns of the row to ensure that we correctly save the value (eg: add quotes for string - in fact we add quotes for everything, it's easier)
945 945
 						if ($row[$j] == null && !is_string($row[$j])) {
946 946
 							// IMPORTANT: if the field is NULL we set it NULL
947 947
 							$row[$j] = 'NULL';
948
-						} elseif(is_string($row[$j]) && $row[$j] == '') {
948
+						} elseif (is_string($row[$j]) && $row[$j] == '') {
949 949
 							// if it's an empty string, we set it as an empty string
950 950
 							$row[$j] = "''";
951
-						} elseif(is_numeric($row[$j]) && !strcmp($row[$j], $row[$j]+0) ) { // test if it's a numeric type and the numeric version ($nb+0) == string version (eg: if we have 01, it's probably not a number but rather a string, else it would not have any leading 0)
951
+						} elseif (is_numeric($row[$j]) && !strcmp($row[$j], $row[$j] + 0)) { // test if it's a numeric type and the numeric version ($nb+0) == string version (eg: if we have 01, it's probably not a number but rather a string, else it would not have any leading 0)
952 952
 							// if it's a number, we return it as-is
953 953
 							//	                    $row[$j] = $row[$j];
954 954
 						} else { // else for all other cases we escape the value and put quotes around
@@ -957,11 +957,11 @@  discard block
 block discarded – undo
957 957
 							$row[$j] = "'".$row[$j]."'";
958 958
 						}
959 959
 					}
960
-					fwrite($handle,implode(',', $row).");\n");
960
+					fwrite($handle, implode(',', $row).");\n");
961 961
 				}
962 962
 				if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
963 963
 				if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
964
-				fwrite($handle,"\n\n\n");
964
+				fwrite($handle, "\n\n\n");
965 965
 			}
966 966
 		}
967 967
 
@@ -985,10 +985,10 @@  discard block
 block discarded – undo
985 985
 		/* Backup Procedure structure*/
986 986
 
987 987
 		// Write the footer (restore the previous database settings)
988
-		$sqlfooter="\n\n";
988
+		$sqlfooter = "\n\n";
989 989
 		if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
990 990
 		if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
991
-		$sqlfooter.="\n\n-- Dump completed on ".date('Y-m-d G-i-s');
991
+		$sqlfooter .= "\n\n-- Dump completed on ".date('Y-m-d G-i-s');
992 992
 		fwrite($handle, $sqlfooter);
993 993
 
994 994
 		fclose($handle);
Please login to merge, or discard this patch.
Braces   +270 added lines, -116 removed lines patch added patch discarded remove patch
@@ -63,7 +63,9 @@  discard block
 block discarded – undo
63 63
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
64 64
 
65 65
 		$filesarray=array();
66
-		if (empty($choice)) $choice='tempfilesold';
66
+		if (empty($choice)) {
67
+		    $choice='tempfilesold';
68
+		}
67 69
 
68 70
 		if ($choice=='tempfiles' || $choice=='tempfilesold')
69 71
 		{
@@ -76,7 +78,10 @@  discard block
 block discarded – undo
76 78
 					$now = dol_now();
77 79
 					foreach($filesarray as $key => $val)
78 80
 					{
79
-						if ($val['date'] > ($now - (24 * 3600))) unset($filesarray[$key]);	// Discard files not older than 24h
81
+						if ($val['date'] > ($now - (24 * 3600))) {
82
+						    unset($filesarray[$key]);
83
+						}
84
+						// Discard files not older than 24h
80 85
 					}
81 86
 				}
82 87
 			}
@@ -110,7 +115,9 @@  discard block
 block discarded – undo
110 115
 				{
111 116
 					if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded=true; }
112 117
 				}
113
-				if (! $alreadyincluded) $filesarray[]=array('fullname'=>$filelog,'type'=>'file');
118
+				if (! $alreadyincluded) {
119
+				    $filesarray[]=array('fullname'=>$filelog,'type'=>'file');
120
+				}
114 121
 			}
115 122
 		}
116 123
 
@@ -129,8 +136,7 @@  discard block
 block discarded – undo
129 136
 					$result=dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted);
130 137
 					$count+=$result;
131 138
 					$countdeleted+=$tmpcountdeleted;
132
-				}
133
-				elseif ($filesarray[$key]['type'] == 'file')
139
+				} elseif ($filesarray[$key]['type'] == 'file')
134 140
 				{
135 141
 					// If (file that is not logfile) or (if mode is logfile)
136 142
 					if ($filesarray[$key]['fullname'] != $filelog || $choice=='logfile')
@@ -140,8 +146,7 @@  discard block
 block discarded – undo
140 146
 						{
141 147
 							$count++;
142 148
 							$countdeleted++;
143
-						}
144
-						else
149
+						} else
145 150
 						{
146 151
 							$counterror++;
147 152
 						}
@@ -161,9 +166,12 @@  discard block
 block discarded – undo
161 166
 		if ($count > 0)
162 167
 		{
163 168
 			$this->output=$langs->trans("PurgeNDirectoriesDeleted", $countdeleted);
164
-			if ($count > $countdeleted) $this->output.='<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
169
+			if ($count > $countdeleted) {
170
+			    $this->output.='<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
171
+			}
172
+		} else {
173
+		    $this->output=$langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)':'');
165 174
 		}
166
-		else $this->output=$langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)':'');
167 175
 
168 176
 		//return $count;
169 177
 		return 0;     // This function can be called by cron so must return 0 if OK
@@ -201,7 +209,9 @@  discard block
 block discarded – undo
201 209
 		}
202 210
 
203 211
 		// Check type parameter
204
-		if ($type == 'auto') $type = $db->type;
212
+		if ($type == 'auto') {
213
+		    $type = $db->type;
214
+		}
205 215
 		if (! in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin')))
206 216
 		{
207 217
 			$langs->load("errors");
@@ -233,44 +243,75 @@  discard block
 block discarded – undo
233 243
 			$outputfile = $outputdir.'/'.$file;
234 244
 			// for compression format, we add extension
235 245
 			$compression=$compression ? $compression : 'none';
236
-			if ($compression == 'gz') $outputfile.='.gz';
237
-			if ($compression == 'bz') $outputfile.='.bz2';
246
+			if ($compression == 'gz') {
247
+			    $outputfile.='.gz';
248
+			}
249
+			if ($compression == 'bz') {
250
+			    $outputfile.='.bz2';
251
+			}
238 252
 			$outputerror = $outputfile.'.err';
239 253
 			dol_mkdir($conf->admin->dir_output.'/backup');
240 254
 
241 255
 			// Parameteres execution
242 256
 			$command=$cmddump;
243
-			if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
257
+			if (preg_match("/\s/",$command)) {
258
+			    $command=escapeshellarg($command);
259
+			}
260
+			// Use quotes on command
244 261
 
245 262
 			//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
246 263
 			$param=$dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
247 264
 			$param.=" -u ".$dolibarr_main_db_user;
248
-			if (! empty($dolibarr_main_db_port)) $param.=" -P ".$dolibarr_main_db_port;
249
-			if (! GETPOST("use_transaction"))    $param.=" -l --single-transaction";
250
-			if (GETPOST("disable_fk") || $usedefault) $param.=" -K";
251
-			if (GETPOST("sql_compat") && GETPOST("sql_compat") != 'NONE') $param.=" --compatible=".escapeshellarg(GETPOST("sql_compat","alpha"));
252
-			if (GETPOST("drop_database"))        $param.=" --add-drop-database";
265
+			if (! empty($dolibarr_main_db_port)) {
266
+			    $param.=" -P ".$dolibarr_main_db_port;
267
+			}
268
+			if (! GETPOST("use_transaction")) {
269
+			    $param.=" -l --single-transaction";
270
+			}
271
+			if (GETPOST("disable_fk") || $usedefault) {
272
+			    $param.=" -K";
273
+			}
274
+			if (GETPOST("sql_compat") && GETPOST("sql_compat") != 'NONE') {
275
+			    $param.=" --compatible=".escapeshellarg(GETPOST("sql_compat","alpha"));
276
+			}
277
+			if (GETPOST("drop_database")) {
278
+			    $param.=" --add-drop-database";
279
+			}
253 280
 			if (GETPOST("sql_structure") || $usedefault)
254 281
 			{
255
-				if (GETPOST("drop") || $usedefault)	$param.=" --add-drop-table=TRUE";
256
-				else 							    $param.=" --add-drop-table=FALSE";
257
-			}
258
-			else
282
+				if (GETPOST("drop") || $usedefault) {
283
+				    $param.=" --add-drop-table=TRUE";
284
+				} else {
285
+				    $param.=" --add-drop-table=FALSE";
286
+				}
287
+			} else
259 288
 			{
260 289
 				$param.=" -t";
261 290
 			}
262
-			if (GETPOST("disable-add-locks")) $param.=" --add-locks=FALSE";
291
+			if (GETPOST("disable-add-locks")) {
292
+			    $param.=" --add-locks=FALSE";
293
+			}
263 294
 			if (GETPOST("sql_data") || $usedefault)
264 295
 			{
265 296
 				$param.=" --tables";
266
-				if (GETPOST("showcolumns") || $usedefault)	 $param.=" -c";
267
-				if (GETPOST("extended_ins") || $usedefault) $param.=" -e";
268
-				else $param.=" --skip-extended-insert";
269
-				if (GETPOST("delayed"))	 	 $param.=" --delayed-insert";
270
-				if (GETPOST("sql_ignore"))	 $param.=" --insert-ignore";
271
-				if (GETPOST("hexforbinary") || $usedefault) $param.=" --hex-blob";
272
-			}
273
-			else
297
+				if (GETPOST("showcolumns") || $usedefault) {
298
+				    $param.=" -c";
299
+				}
300
+				if (GETPOST("extended_ins") || $usedefault) {
301
+				    $param.=" -e";
302
+				} else {
303
+				    $param.=" --skip-extended-insert";
304
+				}
305
+				if (GETPOST("delayed")) {
306
+				    $param.=" --delayed-insert";
307
+				}
308
+				if (GETPOST("sql_ignore")) {
309
+				    $param.=" --insert-ignore";
310
+				}
311
+				if (GETPOST("hexforbinary") || $usedefault) {
312
+				    $param.=" --hex-blob";
313
+				}
314
+			} else
274 315
 			{
275 316
 				$param.=" -d";    // No row information (no data)
276 317
 			}
@@ -289,14 +330,24 @@  discard block
 block discarded – undo
289 330
 			// Start call method to execute dump
290 331
 			$fullcommandcrypted=$command." ".$paramcrypted." 2>&1";
291 332
 			$fullcommandclear=$command." ".$paramclear." 2>&1";
292
-			if ($compression == 'none') $handle = fopen($outputfile, 'w');
293
-			if ($compression == 'gz')   $handle = gzopen($outputfile, 'w');
294
-			if ($compression == 'bz')   $handle = bzopen($outputfile, 'w');
333
+			if ($compression == 'none') {
334
+			    $handle = fopen($outputfile, 'w');
335
+			}
336
+			if ($compression == 'gz') {
337
+			    $handle = gzopen($outputfile, 'w');
338
+			}
339
+			if ($compression == 'bz') {
340
+			    $handle = bzopen($outputfile, 'w');
341
+			}
295 342
 
296 343
 			if ($handle)
297 344
 			{
298
-				if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
299
-				if (empty($execmethod)) $execmethod=1;
345
+				if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) {
346
+				    $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
347
+				}
348
+				if (empty($execmethod)) {
349
+				    $execmethod=1;
350
+				}
300 351
 
301 352
 				$ok=0;
302 353
 				dol_syslog("Utils::dumpDatabase execmethod=".$execmethod." command:".$fullcommandcrypted, LOG_DEBUG);
@@ -313,47 +364,66 @@  discard block
 block discarded – undo
313 364
 						dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
314 365
 						$error = 'Error '.$retval;
315 366
 						$ok=0;
316
-					}
317
-					else
367
+					} else
318 368
 					{
319 369
 						$i=0;
320
-						if (!empty($readt))
321
-						foreach($readt as $key=>$read)
370
+						if (!empty($readt)) {
371
+												foreach($readt as $key=>$read)
322 372
 						{
323
-							$i++;   // output line number
324
-							if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
373
+							$i++;
374
+						}
375
+						// output line number
376
+							if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
377
+							    continue;
378
+							}
325 379
 							fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
326
-							if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
327
-							elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
380
+							if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) {
381
+							    $ok=1;
382
+							} elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) {
383
+							    $ok=1;
384
+							}
328 385
 						}
329 386
 					}
330 387
 				}
331
-				if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
388
+				if ($execmethod == 2) {
389
+				    // With this method, there is no way to get the return code, only output
332 390
 				{
333 391
 					$handlein = popen($fullcommandclear, 'r');
392
+				}
334 393
 					$i=0;
335 394
 					while (!feof($handlein))
336 395
 					{
337 396
 						$i++;   // output line number
338 397
 						$read = fgets($handlein);
339 398
 						// Exclude warning line we don't want
340
-						if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue;
399
+						if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
400
+						    continue;
401
+						}
341 402
 						fwrite($handle,$read);
342
-						if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1;
343
-						elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
403
+						if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) {
404
+						    $ok=1;
405
+						} elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) {
406
+						    $ok=1;
407
+						}
344 408
 					}
345 409
 					pclose($handlein);
346 410
 				}
347 411
 
348 412
 
349
-				if ($compression == 'none') fclose($handle);
350
-				if ($compression == 'gz')   gzclose($handle);
351
-				if ($compression == 'bz')   bzclose($handle);
413
+				if ($compression == 'none') {
414
+				    fclose($handle);
415
+				}
416
+				if ($compression == 'gz') {
417
+				    gzclose($handle);
418
+				}
419
+				if ($compression == 'bz') {
420
+				    bzclose($handle);
421
+				}
352 422
 
353
-				if (! empty($conf->global->MAIN_UMASK))
354
-					@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
355
-			}
356
-			else
423
+				if (! empty($conf->global->MAIN_UMASK)) {
424
+									@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
425
+				}
426
+			} else
357 427
 			{
358 428
 				$langs->load("errors");
359 429
 				dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
@@ -361,18 +431,33 @@  discard block
 block discarded – undo
361 431
 			}
362 432
 
363 433
 			// Get errorstring
364
-			if ($compression == 'none') $handle = fopen($outputfile, 'r');
365
-			if ($compression == 'gz')   $handle = gzopen($outputfile, 'r');
366
-			if ($compression == 'bz')   $handle = bzopen($outputfile, 'r');
434
+			if ($compression == 'none') {
435
+			    $handle = fopen($outputfile, 'r');
436
+			}
437
+			if ($compression == 'gz') {
438
+			    $handle = gzopen($outputfile, 'r');
439
+			}
440
+			if ($compression == 'bz') {
441
+			    $handle = bzopen($outputfile, 'r');
442
+			}
367 443
 			if ($handle)
368 444
 			{
369 445
 				// Get 2048 first chars of error message.
370 446
 				$errormsg = fgets($handle,2048);
371 447
 				// Close file
372
-				if ($compression == 'none') fclose($handle);
373
-				if ($compression == 'gz')   gzclose($handle);
374
-				if ($compression == 'bz')   bzclose($handle);
375
-				if ($ok && preg_match('/^-- MySql/i',$errormsg)) $errormsg='';	// Pas erreur
448
+				if ($compression == 'none') {
449
+				    fclose($handle);
450
+				}
451
+				if ($compression == 'gz') {
452
+				    gzclose($handle);
453
+				}
454
+				if ($compression == 'bz') {
455
+				    bzclose($handle);
456
+				}
457
+				if ($ok && preg_match('/^-- MySql/i',$errormsg)) {
458
+				    $errormsg='';
459
+				}
460
+				// Pas erreur
376 461
 				else
377 462
 				{
378 463
 					// Renommer fichier sortie en fichier erreur
@@ -402,8 +487,12 @@  discard block
 block discarded – undo
402 487
 			$outputfiletemp = $outputfile.'-TMP.sql';
403 488
 			// for compression format, we add extension
404 489
 			$compression=$compression ? $compression : 'none';
405
-			if ($compression == 'gz') $outputfile.='.gz';
406
-			if ($compression == 'bz') $outputfile.='.bz2';
490
+			if ($compression == 'gz') {
491
+			    $outputfile.='.gz';
492
+			}
493
+			if ($compression == 'bz') {
494
+			    $outputfile.='.bz2';
495
+			}
407 496
 			$outputerror = $outputfile.'.err';
408 497
 			dol_mkdir($conf->admin->dir_output.'/backup');
409 498
 
@@ -412,8 +501,7 @@  discard block
 block discarded – undo
412 501
 				$this->backupTables($outputfiletemp);
413 502
 				dol_compress_file($outputfiletemp, $outputfile, $compression);
414 503
 				unlink($outputfiletemp);
415
-			}
416
-			else
504
+			} else
417 505
 			{
418 506
 				$this->backupTables($outputfile);
419 507
 			}
@@ -430,36 +518,59 @@  discard block
 block discarded – undo
430 518
 			$outputfile = $outputdir.'/'.$file;
431 519
 			// for compression format, we add extension
432 520
 			$compression=$compression ? $compression : 'none';
433
-			if ($compression == 'gz') $outputfile.='.gz';
434
-			if ($compression == 'bz') $outputfile.='.bz2';
521
+			if ($compression == 'gz') {
522
+			    $outputfile.='.gz';
523
+			}
524
+			if ($compression == 'bz') {
525
+			    $outputfile.='.bz2';
526
+			}
435 527
 			$outputerror = $outputfile.'.err';
436 528
 			dol_mkdir($conf->admin->dir_output.'/backup');
437 529
 
438 530
 			// Parameteres execution
439 531
 			$command=$cmddump;
440
-			if (preg_match("/\s/",$command)) $command=escapeshellarg($command);	// Use quotes on command
532
+			if (preg_match("/\s/",$command)) {
533
+			    $command=escapeshellarg($command);
534
+			}
535
+			// Use quotes on command
441 536
 
442 537
 			//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
443 538
 			//$param="-F c";
444 539
 			$param="-F p";
445 540
 			$param.=" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
446 541
 			$param.=" -U ".$dolibarr_main_db_user;
447
-			if (! empty($dolibarr_main_db_port)) $param.=" -p ".$dolibarr_main_db_port;
448
-			if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param.="  --disable-dollar-quoting";
449
-			if (GETPOST("drop_database"))        $param.=" -c -C";
542
+			if (! empty($dolibarr_main_db_port)) {
543
+			    $param.=" -p ".$dolibarr_main_db_port;
544
+			}
545
+			if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') {
546
+			    $param.="  --disable-dollar-quoting";
547
+			}
548
+			if (GETPOST("drop_database")) {
549
+			    $param.=" -c -C";
550
+			}
450 551
 			if (GETPOST("sql_structure"))
451 552
 			{
452
-				if (GETPOST("drop"))			 $param.=" --add-drop-table";
453
-				if (! GETPOST("sql_data"))       $param.=" -s";
553
+				if (GETPOST("drop")) {
554
+				    $param.=" --add-drop-table";
555
+				}
556
+				if (! GETPOST("sql_data")) {
557
+				    $param.=" -s";
558
+				}
454 559
 			}
455 560
 			if (GETPOST("sql_data"))
456 561
 			{
457
-				if (! GETPOST("sql_structure"))	 $param.=" -a";
458
-				if (GETPOST("showcolumns"))	     $param.=" -c";
562
+				if (! GETPOST("sql_structure")) {
563
+				    $param.=" -a";
564
+				}
565
+				if (GETPOST("showcolumns")) {
566
+				    $param.=" -c";
567
+				}
459 568
 			}
460 569
 			$param.=' -f "'.$outputfile.'"';
461 570
 			//if ($compression == 'none')
462
-			if ($compression == 'gz')   $param.=' -Z 9';
571
+			if ($compression == 'gz') {
572
+			    $param.=' -Z 9';
573
+			}
463 574
 			//if ($compression == 'bz')
464 575
 			$paramcrypted=$param;
465 576
 			$paramclear=$param;
@@ -483,7 +594,9 @@  discard block
 block discarded – undo
483 594
 			foreach($tmpfiles as $key => $val)
484 595
 			{
485 596
 				$i++;
486
-				if ($i <= $keeplastnfiles) continue;
597
+				if ($i <= $keeplastnfiles) {
598
+				    continue;
599
+				}
487 600
 				dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
488 601
 			}
489 602
 		}
@@ -512,8 +625,12 @@  discard block
 block discarded – undo
512 625
 		$command=escapeshellcmd($command);
513 626
 		$command.=" 2>&1";
514 627
 
515
-		if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
516
-		if (empty($execmethod)) $execmethod=1;
628
+		if (! empty($conf->global->MAIN_EXEC_USE_POPEN)) {
629
+		    $execmethod=$conf->global->MAIN_EXEC_USE_POPEN;
630
+		}
631
+		if (empty($execmethod)) {
632
+		    $execmethod=1;
633
+		}
517 634
 		//$execmethod=1;
518 635
 
519 636
 		dol_syslog("Utils::executeCLI execmethod=".$execmethod." system:".$command, LOG_DEBUG);
@@ -530,9 +647,11 @@  discard block
 block discarded – undo
530 647
 				$error = 'Error '.$retval;
531 648
 			}
532 649
 		}
533
-		if ($execmethod == 2)	// With this method, there is no way to get the return code, only output
650
+		if ($execmethod == 2) {
651
+		    // With this method, there is no way to get the return code, only output
534 652
 		{
535 653
 			$ok=0;
654
+		}
536 655
 			$handle = fopen($outputfile, 'w+b');
537 656
 			if ($handle)
538 657
 			{
@@ -547,7 +666,9 @@  discard block
 block discarded – undo
547 666
 				pclose($handlein);
548 667
 				fclose($handle);
549 668
 			}
550
-			if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
669
+			if (! empty($conf->global->MAIN_UMASK)) {
670
+			    @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
671
+			}
551 672
 		}
552 673
 
553 674
 		// Update with result
@@ -592,14 +713,12 @@  discard block
 block discarded – undo
592 713
 		{
593 714
 			try {
594 715
 				$moduleobj = new $class($this->db);
595
-			}
596
-			catch(Exception $e)
716
+			} catch(Exception $e)
597 717
 			{
598 718
 				$error++;
599 719
 				dol_print_error($e->getMessage());
600 720
 			}
601
-		}
602
-		else
721
+		} else
603 722
 		{
604 723
 			$error++;
605 724
 			$langs->load("errors");
@@ -618,8 +737,12 @@  discard block
 block discarded – undo
618 737
 			$outputfiledoc = $dirofmodule.'/'.$FILENAMEDOC;
619 738
 			if ($dirofmodule)
620 739
 			{
621
-				if (! dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule);
622
-				if (! dol_is_dir($dirofmoduletmp)) dol_mkdir($dirofmoduletmp);
740
+				if (! dol_is_dir($dirofmodule)) {
741
+				    dol_mkdir($dirofmodule);
742
+				}
743
+				if (! dol_is_dir($dirofmoduletmp)) {
744
+				    dol_mkdir($dirofmoduletmp);
745
+				}
623 746
 				if (! is_writable($dirofmoduletmp))
624 747
 				{
625 748
 					$this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
@@ -636,19 +759,26 @@  discard block
 block discarded – undo
636 759
 					$i = 0;
637 760
 					foreach ($specs as $spec)
638 761
 					{
639
-						if (preg_match('/notindoc/', $spec['relativename'])) continue;	// Discard file
640
-						if (preg_match('/disabled/', $spec['relativename'])) continue;	// Discard file
762
+						if (preg_match('/notindoc/', $spec['relativename'])) {
763
+						    continue;
764
+						}
765
+						// Discard file
766
+						if (preg_match('/disabled/', $spec['relativename'])) {
767
+						    continue;
768
+						}
769
+						// Discard file
641 770
 
642 771
 						$pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
643 772
 						$format='asciidoc';
644
-						if (preg_match('/\.md$/i', $spec['name'])) $format='markdown';
773
+						if (preg_match('/\.md$/i', $spec['name'])) {
774
+						    $format='markdown';
775
+						}
645 776
 
646 777
 						$filecursor = @file_get_contents($spec['fullname']);
647 778
 						if ($filecursor)
648 779
 						{
649 780
 							fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
650
-						}
651
-						else
781
+						} else
652 782
 						{
653 783
 							$this->error = 'Failed to concat content of file '.$spec['fullname'];
654 784
 							return -1;
@@ -683,8 +813,7 @@  discard block
 block discarded – undo
683 813
 					$this->error = $resarray['error'].' '.$resarray['output'];
684 814
 				}
685 815
 				$result = ($resarray['result'] == 0) ? 1 : 0;
686
-			}
687
-			else
816
+			} else
688 817
 			{
689 818
 				$result = 0;
690 819
 			}
@@ -692,15 +821,13 @@  discard block
 block discarded – undo
692 821
 			if ($result > 0)
693 822
 			{
694 823
 				return 1;
695
-			}
696
-			else
824
+			} else
697 825
 			{
698 826
 				$error++;
699 827
 				$langs->load("errors");
700 828
 				$this->error = $langs->trans("ErrorFailToGenerateFile", $outputfiledoc);
701 829
 			}
702
-		}
703
-		else
830
+		} else
704 831
 		{
705 832
 			$error++;
706 833
 			$langs->load("errors");
@@ -751,11 +878,13 @@  discard block
 block discarded – undo
751 878
 			$logname = $file['name'];
752 879
 			$logpath = $file['path'];
753 880
 
754
-			if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0)	// If log file exists and is not empty
881
+			if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) {
882
+			    // If log file exists and is not empty
755 883
 			{
756 884
 				// Handle already compressed files to rename them and add +1
757 885
 
758 886
 				$filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
887
+			}
759 888
 
760 889
 				$gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
761 890
 				$gzfiles = array();
@@ -859,8 +988,7 @@  discard block
 block discarded – undo
859 988
 			{
860 989
 				$tables[] = $row[0];
861 990
 			}
862
-		}
863
-		else
991
+		} else
864 992
 		{
865 993
 			$tables = is_array($tables) ? $tables : explode(',',$tables);
866 994
 		}
@@ -896,16 +1024,24 @@  discard block
 block discarded – undo
896 1024
 
897 1025
 ";
898 1026
 
899
-		if (GETPOST("nobin_disable_fk")) $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
1027
+		if (GETPOST("nobin_disable_fk")) {
1028
+		    $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
1029
+		}
900 1030
 		//$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
901
-		if (GETPOST("nobin_use_transaction")) $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1031
+		if (GETPOST("nobin_use_transaction")) {
1032
+		    $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1033
+		}
902 1034
 
903 1035
 		fwrite($handle, $sqlhead);
904 1036
 
905 1037
 		$ignore = '';
906
-		if (GETPOST("nobin_sql_ignore")) $ignore = 'IGNORE ';
1038
+		if (GETPOST("nobin_sql_ignore")) {
1039
+		    $ignore = 'IGNORE ';
1040
+		}
907 1041
 		$delayed = '';
908
-		if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
1042
+		if (GETPOST("nobin_delayed")) {
1043
+		    $delayed = 'DELAYED ';
1044
+		}
909 1045
 
910 1046
 		// Process each table and print their definition + their datas
911 1047
 		foreach($tables as $table)
@@ -913,7 +1049,10 @@  discard block
 block discarded – undo
913 1049
 			// Saving the table structure
914 1050
 			fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
915 1051
 
916
-			if (GETPOST("nobin_drop")) fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
1052
+			if (GETPOST("nobin_drop")) {
1053
+			    fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n");
1054
+			}
1055
+			// Dropping table if exists prior to re create it
917 1056
 			fwrite($handle,"/*!40101 SET @saved_cs_client     = @@character_set_client */;\n");
918 1057
 			fwrite($handle,"/*!40101 SET character_set_client = utf8 */;\n");
919 1058
 			$resqldrop=$db->query('SHOW CREATE TABLE '.$table);
@@ -921,17 +1060,22 @@  discard block
 block discarded – undo
921 1060
 			if (empty($row2[1]))
922 1061
 			{
923 1062
 				fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
924
-			}
925
-			else
1063
+			} else
926 1064
 			{
927 1065
 				fwrite($handle,$row2[1].";\n");
928 1066
 				//fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
929 1067
 
930 1068
 				// Dumping the data (locking the table and disabling the keys check while doing the process)
931 1069
 				fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
932
-				if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
933
-				if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
934
-				else fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
1070
+				if (!GETPOST("nobin_nolocks")) {
1071
+				    fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n");
1072
+				}
1073
+				// Lock the table before inserting data (when the data will be imported back)
1074
+				if (GETPOST("nobin_disable_fk")) {
1075
+				    fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
1076
+				} else {
1077
+				    fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
1078
+				}
935 1079
 
936 1080
 				$sql='SELECT * FROM '.$table;
937 1081
 				$result = $db->query($sql);
@@ -959,8 +1103,14 @@  discard block
 block discarded – undo
959 1103
 					}
960 1104
 					fwrite($handle,implode(',', $row).");\n");
961 1105
 				}
962
-				if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
963
-				if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
1106
+				if (GETPOST("nobin_disable_fk")) {
1107
+				    fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n");
1108
+				}
1109
+				// Enabling back the keys/index checking
1110
+				if (!GETPOST("nobin_nolocks")) {
1111
+				    fwrite($handle, "UNLOCK TABLES;\n");
1112
+				}
1113
+				// Unlocking the table
964 1114
 				fwrite($handle,"\n\n\n");
965 1115
 			}
966 1116
 		}
@@ -986,8 +1136,12 @@  discard block
 block discarded – undo
986 1136
 
987 1137
 		// Write the footer (restore the previous database settings)
988 1138
 		$sqlfooter="\n\n";
989
-		if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
990
-		if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
1139
+		if (GETPOST("nobin_use_transaction")) {
1140
+		    $sqlfooter .= "COMMIT;\n";
1141
+		}
1142
+		if (GETPOST("nobin_disable_fk")) {
1143
+		    $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
1144
+		}
991 1145
 		$sqlfooter.="\n\n-- Dump completed on ".date('Y-m-d G-i-s');
992 1146
 		fwrite($handle, $sqlfooter);
993 1147
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formcontract.class.php 3 patches
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -33,9 +33,9 @@  discard block
 block discarded – undo
33 33
     public $db;
34 34
 
35 35
     /**
36
-	 * @var string Error code (or message)
37
-	 */
38
-	public $error='';
36
+     * @var string Error code (or message)
37
+     */
38
+    public $error='';
39 39
 
40 40
 
41 41
     /**
@@ -50,135 +50,135 @@  discard block
 block discarded – undo
50 50
 
51 51
 
52 52
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
53
-	/**
54
-	 *	Show a combo list with contracts qualified for a third party
55
-	 *
56
-	 *	@param	int		$socid      Id third party (-1=all, 0=only contracts not linked to a third party, id=contracts not linked or linked to third party id)
57
-	 *	@param  int		$selected   Id contract preselected
58
-	 *	@param  string	$htmlname   Nom de la zone html
59
-	 *	@param	int		$maxlength	Maximum length of label
60
-	 *	@param	int		$showempty	Show empty line
61
-	 *	@return int         		Nbr of project if OK, <0 if KO
62
-	 */
63
-	function select_contract($socid=-1, $selected='', $htmlname='contrattid', $maxlength=16, $showempty=1)
64
-	{
53
+    /**
54
+     *	Show a combo list with contracts qualified for a third party
55
+     *
56
+     *	@param	int		$socid      Id third party (-1=all, 0=only contracts not linked to a third party, id=contracts not linked or linked to third party id)
57
+     *	@param  int		$selected   Id contract preselected
58
+     *	@param  string	$htmlname   Nom de la zone html
59
+     *	@param	int		$maxlength	Maximum length of label
60
+     *	@param	int		$showempty	Show empty line
61
+     *	@return int         		Nbr of project if OK, <0 if KO
62
+     */
63
+    function select_contract($socid=-1, $selected='', $htmlname='contrattid', $maxlength=16, $showempty=1)
64
+    {
65 65
         // phpcs:enable
66
-		global $db,$user,$conf,$langs;
66
+        global $db,$user,$conf,$langs;
67 67
 
68
-		$hideunselectables = false;
69
-		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
68
+        $hideunselectables = false;
69
+        if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
70 70
 
71
-		// Search all contacts
72
-		$sql = 'SELECT c.rowid, c.ref, c.fk_soc, c.statut';
73
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'contrat as c';
74
-		$sql.= " WHERE c.entity = ".$conf->entity;
75
-		//if ($contratListId) $sql.= " AND c.rowid IN (".$contratListId.")";
76
-		if ($socid > 0)
77
-		{
78
-			// CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
79
-		    	if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))
80
-			    $sql.= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)";
81
-		    	else if ($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')
82
-			{
83
-		        	$sql.= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") ";
84
-				$sql.= " OR c.fk_soc IS NULL)";
85
-		    	}
86
-		}
87
-		if ($socid == 0) $sql.= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)";
88
-		$sql.= " ORDER BY c.ref ";
71
+        // Search all contacts
72
+        $sql = 'SELECT c.rowid, c.ref, c.fk_soc, c.statut';
73
+        $sql.= ' FROM '.MAIN_DB_PREFIX .'contrat as c';
74
+        $sql.= " WHERE c.entity = ".$conf->entity;
75
+        //if ($contratListId) $sql.= " AND c.rowid IN (".$contratListId.")";
76
+        if ($socid > 0)
77
+        {
78
+            // CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
79
+                if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))
80
+                $sql.= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)";
81
+                else if ($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')
82
+            {
83
+                    $sql.= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") ";
84
+                $sql.= " OR c.fk_soc IS NULL)";
85
+                }
86
+        }
87
+        if ($socid == 0) $sql.= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)";
88
+        $sql.= " ORDER BY c.ref ";
89 89
 
90
-		dol_syslog(get_class($this)."::select_contract", LOG_DEBUG);
91
-		$resql=$db->query($sql);
92
-		if ($resql)
93
-		{
94
-			print '<select class="flat" name="'.$htmlname.'">';
95
-			if ($showempty) print '<option value="0">&nbsp;</option>';
96
-			$num = $db->num_rows($resql);
97
-			$i = 0;
98
-			if ($num)
99
-			{
100
-				while ($i < $num)
101
-				{
102
-					$obj = $db->fetch_object($resql);
103
-					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
104
-					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
105
-					{
106
-						// Do nothing
107
-					}
108
-					else
109
-					{
110
-						$labeltoshow=dol_trunc($obj->ref,18);
111
-						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
112
-						//else $labeltoshow.=' ('.$langs->trans("Private").')';
113
-						if (!empty($selected) && $selected == $obj->rowid && $obj->statut > 0)
114
-						{
115
-							print '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
116
-						}
117
-						else
118
-						{
119
-							$disabled=0;
120
-							if ( $obj->statut ==  0)
121
-							{
122
-								$disabled=1;
123
-								$labeltoshow.=' ('.$langs->trans("Draft").')';
124
-							}
125
-							if ( empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
126
-							{
127
-								$disabled=1;
128
-								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
129
-							}
90
+        dol_syslog(get_class($this)."::select_contract", LOG_DEBUG);
91
+        $resql=$db->query($sql);
92
+        if ($resql)
93
+        {
94
+            print '<select class="flat" name="'.$htmlname.'">';
95
+            if ($showempty) print '<option value="0">&nbsp;</option>';
96
+            $num = $db->num_rows($resql);
97
+            $i = 0;
98
+            if ($num)
99
+            {
100
+                while ($i < $num)
101
+                {
102
+                    $obj = $db->fetch_object($resql);
103
+                    // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
104
+                    if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
105
+                    {
106
+                        // Do nothing
107
+                    }
108
+                    else
109
+                    {
110
+                        $labeltoshow=dol_trunc($obj->ref,18);
111
+                        //if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
112
+                        //else $labeltoshow.=' ('.$langs->trans("Private").')';
113
+                        if (!empty($selected) && $selected == $obj->rowid && $obj->statut > 0)
114
+                        {
115
+                            print '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
116
+                        }
117
+                        else
118
+                        {
119
+                            $disabled=0;
120
+                            if ( $obj->statut ==  0)
121
+                            {
122
+                                $disabled=1;
123
+                                $labeltoshow.=' ('.$langs->trans("Draft").')';
124
+                            }
125
+                            if ( empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
126
+                            {
127
+                                $disabled=1;
128
+                                $labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
129
+                            }
130 130
 
131
-							if ($hideunselectables && $disabled)
132
-							{
133
-								$resultat='';
134
-							}
135
-							else
136
-							{
137
-								$resultat='<option value="'.$obj->rowid.'"';
138
-								if ($disabled) $resultat.=' disabled';
139
-								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
140
-								//else $labeltoshow.=' ('.$langs->trans("Private").')';
141
-								$resultat.='>'.$labeltoshow;
142
-								$resultat.='</option>';
143
-							}
144
-							print $resultat;
145
-						}
146
-					}
147
-					$i++;
148
-				}
149
-			}
150
-			print '</select>';
151
-			$db->free($resql);
131
+                            if ($hideunselectables && $disabled)
132
+                            {
133
+                                $resultat='';
134
+                            }
135
+                            else
136
+                            {
137
+                                $resultat='<option value="'.$obj->rowid.'"';
138
+                                if ($disabled) $resultat.=' disabled';
139
+                                //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
140
+                                //else $labeltoshow.=' ('.$langs->trans("Private").')';
141
+                                $resultat.='>'.$labeltoshow;
142
+                                $resultat.='</option>';
143
+                            }
144
+                            print $resultat;
145
+                        }
146
+                    }
147
+                    $i++;
148
+                }
149
+            }
150
+            print '</select>';
151
+            $db->free($resql);
152 152
 
153
-			if (!empty($conf->use_javascript_ajax))
154
-			{
155
-				// Make select dynamic
156
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
157
-				print ajax_combobox($htmlname);
158
-			}
153
+            if (!empty($conf->use_javascript_ajax))
154
+            {
155
+                // Make select dynamic
156
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
157
+                print ajax_combobox($htmlname);
158
+            }
159 159
 
160
-			return $num;
161
-		}
162
-		else
163
-		{
164
-			dol_print_error($db);
165
-			return -1;
166
-		}
167
-	}
160
+            return $num;
161
+        }
162
+        else
163
+        {
164
+            dol_print_error($db);
165
+            return -1;
166
+        }
167
+    }
168 168
 
169
-	/**
170
-	 *	Show a form to select a contract
171
-	 *
172
-	 *  @param	int		$page       Page
173
-	 *	@param	int		$socid      Id third party (-1=all, 0=only contracts not linked to a third party, id=contracts not linked or linked to third party id)
174
-	 *	@param  int		$selected   Id contract preselected
175
-	 *	@param  string	$htmlname   Nom de la zone html
176
-	 *	@param	int		$maxlength	Maximum length of label
177
-	 *	@param	int		$showempty	Show empty line
178
-	 *	@return int                 Nbr of project if OK, <0 if KO
179
-	 */
180
-	function formSelectContract($page, $socid=-1, $selected='', $htmlname='contrattid', $maxlength=16, $showempty=1)
181
-	{
169
+    /**
170
+     *	Show a form to select a contract
171
+     *
172
+     *  @param	int		$page       Page
173
+     *	@param	int		$socid      Id third party (-1=all, 0=only contracts not linked to a third party, id=contracts not linked or linked to third party id)
174
+     *	@param  int		$selected   Id contract preselected
175
+     *	@param  string	$htmlname   Nom de la zone html
176
+     *	@param	int		$maxlength	Maximum length of label
177
+     *	@param	int		$showempty	Show empty line
178
+     *	@return int                 Nbr of project if OK, <0 if KO
179
+     */
180
+    function formSelectContract($page, $socid=-1, $selected='', $htmlname='contrattid', $maxlength=16, $showempty=1)
181
+    {
182 182
         global $langs;
183 183
 
184 184
         print "\n";
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 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
     /**
@@ -60,35 +60,35 @@  discard block
 block discarded – undo
60 60
 	 *	@param	int		$showempty	Show empty line
61 61
 	 *	@return int         		Nbr of project if OK, <0 if KO
62 62
 	 */
63
-	function select_contract($socid=-1, $selected='', $htmlname='contrattid', $maxlength=16, $showempty=1)
63
+	function select_contract($socid = -1, $selected = '', $htmlname = 'contrattid', $maxlength = 16, $showempty = 1)
64 64
 	{
65 65
         // phpcs:enable
66
-		global $db,$user,$conf,$langs;
66
+		global $db, $user, $conf, $langs;
67 67
 
68 68
 		$hideunselectables = false;
69
-		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
69
+		if (!empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
70 70
 
71 71
 		// Search all contacts
72 72
 		$sql = 'SELECT c.rowid, c.ref, c.fk_soc, c.statut';
73
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'contrat as c';
74
-		$sql.= " WHERE c.entity = ".$conf->entity;
73
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'contrat as c';
74
+		$sql .= " WHERE c.entity = ".$conf->entity;
75 75
 		//if ($contratListId) $sql.= " AND c.rowid IN (".$contratListId.")";
76 76
 		if ($socid > 0)
77 77
 		{
78 78
 			// CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
79 79
 		    	if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))
80
-			    $sql.= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)";
80
+			    $sql .= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)";
81 81
 		    	else if ($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')
82 82
 			{
83
-		        	$sql.= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") ";
84
-				$sql.= " OR c.fk_soc IS NULL)";
83
+		        	$sql .= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") ";
84
+				$sql .= " OR c.fk_soc IS NULL)";
85 85
 		    	}
86 86
 		}
87
-		if ($socid == 0) $sql.= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)";
88
-		$sql.= " ORDER BY c.ref ";
87
+		if ($socid == 0) $sql .= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)";
88
+		$sql .= " ORDER BY c.ref ";
89 89
 
90 90
 		dol_syslog(get_class($this)."::select_contract", LOG_DEBUG);
91
-		$resql=$db->query($sql);
91
+		$resql = $db->query($sql);
92 92
 		if ($resql)
93 93
 		{
94 94
 			print '<select class="flat" name="'.$htmlname.'">';
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
 				{
102 102
 					$obj = $db->fetch_object($resql);
103 103
 					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
104
-					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
104
+					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$user->rights->societe->lire)
105 105
 					{
106 106
 						// Do nothing
107 107
 					}
108 108
 					else
109 109
 					{
110
-						$labeltoshow=dol_trunc($obj->ref,18);
110
+						$labeltoshow = dol_trunc($obj->ref, 18);
111 111
 						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
112 112
 						//else $labeltoshow.=' ('.$langs->trans("Private").')';
113 113
 						if (!empty($selected) && $selected == $obj->rowid && $obj->statut > 0)
@@ -116,30 +116,30 @@  discard block
 block discarded – undo
116 116
 						}
117 117
 						else
118 118
 						{
119
-							$disabled=0;
120
-							if ( $obj->statut ==  0)
119
+							$disabled = 0;
120
+							if ($obj->statut == 0)
121 121
 							{
122
-								$disabled=1;
123
-								$labeltoshow.=' ('.$langs->trans("Draft").')';
122
+								$disabled = 1;
123
+								$labeltoshow .= ' ('.$langs->trans("Draft").')';
124 124
 							}
125
-							if ( empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
125
+							if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) && $socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
126 126
 							{
127
-								$disabled=1;
128
-								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
127
+								$disabled = 1;
128
+								$labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
129 129
 							}
130 130
 
131 131
 							if ($hideunselectables && $disabled)
132 132
 							{
133
-								$resultat='';
133
+								$resultat = '';
134 134
 							}
135 135
 							else
136 136
 							{
137
-								$resultat='<option value="'.$obj->rowid.'"';
138
-								if ($disabled) $resultat.=' disabled';
137
+								$resultat = '<option value="'.$obj->rowid.'"';
138
+								if ($disabled) $resultat .= ' disabled';
139 139
 								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
140 140
 								//else $labeltoshow.=' ('.$langs->trans("Private").')';
141
-								$resultat.='>'.$labeltoshow;
142
-								$resultat.='</option>';
141
+								$resultat .= '>'.$labeltoshow;
142
+								$resultat .= '</option>';
143 143
 							}
144 144
 							print $resultat;
145 145
 						}
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 			if (!empty($conf->use_javascript_ajax))
154 154
 			{
155 155
 				// Make select dynamic
156
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
156
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
157 157
 				print ajax_combobox($htmlname);
158 158
 			}
159 159
 
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	 *	@param	int		$showempty	Show empty line
178 178
 	 *	@return int                 Nbr of project if OK, <0 if KO
179 179
 	 */
180
-	function formSelectContract($page, $socid=-1, $selected='', $htmlname='contrattid', $maxlength=16, $showempty=1)
180
+	function formSelectContract($page, $socid = -1, $selected = '', $htmlname = 'contrattid', $maxlength = 16, $showempty = 1)
181 181
 	{
182 182
         global $langs;
183 183
 
Please login to merge, or discard this patch.
Braces   +19 added lines, -15 removed lines patch added patch discarded remove patch
@@ -66,7 +66,9 @@  discard block
 block discarded – undo
66 66
 		global $db,$user,$conf,$langs;
67 67
 
68 68
 		$hideunselectables = false;
69
-		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
69
+		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) {
70
+		    $hideunselectables = true;
71
+		}
70 72
 
71 73
 		// Search all contacts
72 74
 		$sql = 'SELECT c.rowid, c.ref, c.fk_soc, c.statut';
@@ -76,15 +78,17 @@  discard block
 block discarded – undo
76 78
 		if ($socid > 0)
77 79
 		{
78 80
 			// CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
79
-		    	if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))
80
-			    $sql.= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)";
81
-		    	else if ($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')
81
+		    	if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY)) {
82
+		    				    $sql.= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)";
83
+		    	} else if ($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')
82 84
 			{
83 85
 		        	$sql.= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") ";
84 86
 				$sql.= " OR c.fk_soc IS NULL)";
85 87
 		    	}
86 88
 		}
87
-		if ($socid == 0) $sql.= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)";
89
+		if ($socid == 0) {
90
+		    $sql.= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)";
91
+		}
88 92
 		$sql.= " ORDER BY c.ref ";
89 93
 
90 94
 		dol_syslog(get_class($this)."::select_contract", LOG_DEBUG);
@@ -92,7 +96,9 @@  discard block
 block discarded – undo
92 96
 		if ($resql)
93 97
 		{
94 98
 			print '<select class="flat" name="'.$htmlname.'">';
95
-			if ($showempty) print '<option value="0">&nbsp;</option>';
99
+			if ($showempty) {
100
+			    print '<option value="0">&nbsp;</option>';
101
+			}
96 102
 			$num = $db->num_rows($resql);
97 103
 			$i = 0;
98 104
 			if ($num)
@@ -104,8 +110,7 @@  discard block
 block discarded – undo
104 110
 					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
105 111
 					{
106 112
 						// Do nothing
107
-					}
108
-					else
113
+					} else
109 114
 					{
110 115
 						$labeltoshow=dol_trunc($obj->ref,18);
111 116
 						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
@@ -113,8 +118,7 @@  discard block
 block discarded – undo
113 118
 						if (!empty($selected) && $selected == $obj->rowid && $obj->statut > 0)
114 119
 						{
115 120
 							print '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
116
-						}
117
-						else
121
+						} else
118 122
 						{
119 123
 							$disabled=0;
120 124
 							if ( $obj->statut ==  0)
@@ -131,11 +135,12 @@  discard block
 block discarded – undo
131 135
 							if ($hideunselectables && $disabled)
132 136
 							{
133 137
 								$resultat='';
134
-							}
135
-							else
138
+							} else
136 139
 							{
137 140
 								$resultat='<option value="'.$obj->rowid.'"';
138
-								if ($disabled) $resultat.=' disabled';
141
+								if ($disabled) {
142
+								    $resultat.=' disabled';
143
+								}
139 144
 								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
140 145
 								//else $labeltoshow.=' ('.$langs->trans("Private").')';
141 146
 								$resultat.='>'.$labeltoshow;
@@ -158,8 +163,7 @@  discard block
 block discarded – undo
158 163
 			}
159 164
 
160 165
 			return $num;
161
-		}
162
-		else
166
+		} else
163 167
 		{
164 168
 			dol_print_error($db);
165 169
 			return -1;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formmargin.class.php 3 patches
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -34,9 +34,9 @@  discard block
 block discarded – undo
34 34
     public $db;
35 35
 
36 36
     /**
37
-	 * @var string Error code (or message)
38
-	 */
39
-	public $error='';
37
+     * @var string Error code (or message)
38
+     */
39
+    public $error='';
40 40
 
41 41
 
42 42
     /**
@@ -51,234 +51,234 @@  discard block
 block discarded – undo
51 51
 
52 52
 
53 53
 
54
-	/**
55
-	 *	get array with margin information from lines of object
56
-	 *  TODO Move this in common class.
57
-	 *
58
-	 * 	@param	CommonObject	$object			Object we want to get margin information for
59
-	 * 	@param 	boolean			$force_price	True of not
60
-	 * 	@return array							Array with info
61
-	 */
62
-	function getMarginInfosArray($object, $force_price=false)
63
-	{
64
-		global $conf, $db;
54
+    /**
55
+     *	get array with margin information from lines of object
56
+     *  TODO Move this in common class.
57
+     *
58
+     * 	@param	CommonObject	$object			Object we want to get margin information for
59
+     * 	@param 	boolean			$force_price	True of not
60
+     * 	@return array							Array with info
61
+     */
62
+    function getMarginInfosArray($object, $force_price=false)
63
+    {
64
+        global $conf, $db;
65 65
 
66
-		// Default returned array
67
-		$marginInfos = array(
68
-				'pa_products' => 0,
69
-				'pv_products' => 0,
70
-				'margin_on_products' => 0,
71
-				'margin_rate_products' => '',
72
-				'mark_rate_products' => '',
73
-				'pa_services' => 0,
74
-				'pv_services' => 0,
75
-				'margin_on_services' => 0,
76
-				'margin_rate_services' => '',
77
-				'mark_rate_services' => '',
78
-				'pa_total' => 0,
79
-				'pv_total' => 0,
80
-				'total_margin' => 0,
81
-				'total_margin_rate' => '',
82
-				'total_mark_rate' => ''
83
-		);
66
+        // Default returned array
67
+        $marginInfos = array(
68
+                'pa_products' => 0,
69
+                'pv_products' => 0,
70
+                'margin_on_products' => 0,
71
+                'margin_rate_products' => '',
72
+                'mark_rate_products' => '',
73
+                'pa_services' => 0,
74
+                'pv_services' => 0,
75
+                'margin_on_services' => 0,
76
+                'margin_rate_services' => '',
77
+                'mark_rate_services' => '',
78
+                'pa_total' => 0,
79
+                'pv_total' => 0,
80
+                'total_margin' => 0,
81
+                'total_margin_rate' => '',
82
+                'total_mark_rate' => ''
83
+        );
84 84
 
85
-		foreach($object->lines as $line)
86
-		{
87
-			if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price)
88
-			{
89
-				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
90
-				$product = new ProductFournisseur($db);
91
-				if ($product->fetch_product_fournisseur_price($line->fk_fournprice))
92
-					$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
93
-			}
94
-			// si prix d'achat non renseigné et devrait l'être, alors prix achat = prix vente
95
-			if ((!isset($line->pa_ht) || $line->pa_ht == 0) && $line->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
96
-				$line->pa_ht = $line->subprice * (1 - ($line->remise_percent / 100));
97
-			}
85
+        foreach($object->lines as $line)
86
+        {
87
+            if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price)
88
+            {
89
+                require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
90
+                $product = new ProductFournisseur($db);
91
+                if ($product->fetch_product_fournisseur_price($line->fk_fournprice))
92
+                    $line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
93
+            }
94
+            // si prix d'achat non renseigné et devrait l'être, alors prix achat = prix vente
95
+            if ((!isset($line->pa_ht) || $line->pa_ht == 0) && $line->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
96
+                $line->pa_ht = $line->subprice * (1 - ($line->remise_percent / 100));
97
+            }
98 98
 
99
-			$pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
100
-			$pa_ht = ($pv < 0 ? - $line->pa_ht : $line->pa_ht);      // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
101
-			$pa = $line->qty * $pa_ht;
99
+            $pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
100
+            $pa_ht = ($pv < 0 ? - $line->pa_ht : $line->pa_ht);      // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
101
+            $pa = $line->qty * $pa_ht;
102 102
 
103
-			// calcul des marges
104
-			if (isset($line->fk_remise_except) && isset($conf->global->MARGIN_METHODE_FOR_DISCOUNT)) {    // remise
105
-				if ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '1') { // remise globale considérée comme produit
106
-					$marginInfos['pa_products'] += $pa;
107
-					$marginInfos['pv_products'] += $pv;
108
-					$marginInfos['pa_total'] +=  $pa;
109
-					$marginInfos['pv_total'] +=  $pv;
110
-					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
111
-					//if ($pv < 0)
112
-					//{
113
-					//	$marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
114
-					//}
115
-					//else
116
-						$marginInfos['margin_on_products'] += $pv - $pa;
117
-				}
118
-				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
119
-					$marginInfos['pa_services'] += $pa;
120
-					$marginInfos['pv_services'] += $pv;
121
-					$marginInfos['pa_total'] +=  $pa;
122
-					$marginInfos['pv_total'] +=  $pv;
123
-					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
124
-					//if ($pv < 0)
125
-					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
126
-					//else
127
-						$marginInfos['margin_on_services'] += $pv - $pa;
128
-				}
129
-				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
130
-					$marginInfos['pa_total'] += $pa;
131
-					$marginInfos['pv_total'] += $pv;
132
-				}
133
-			}
134
-			else {
135
-				$type=$line->product_type?$line->product_type:$line->fk_product_type;
136
-				if ($type == 0) {  // product
137
-					$marginInfos['pa_products'] += $pa;
138
-					$marginInfos['pv_products'] += $pv;
139
-					$marginInfos['pa_total'] +=  $pa;
140
-					$marginInfos['pv_total'] +=  $pv;
141
-					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
142
-					//if ($pv < 0)
143
-					//{
144
-					//    $marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
145
-					//}
146
-					//else
147
-					//{
148
-					    $marginInfos['margin_on_products'] += $pv - $pa;
149
-					//}
150
-				}
151
-				elseif ($type == 1) {  // service
152
-					$marginInfos['pa_services'] += $pa;
153
-					$marginInfos['pv_services'] += $pv;
154
-					$marginInfos['pa_total'] +=  $pa;
155
-					$marginInfos['pv_total'] +=  $pv;
156
-					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
157
-					//if ($pv < 0)
158
-					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
159
-					//else
160
-						$marginInfos['margin_on_services'] += $pv - $pa;
161
-				}
162
-			}
163
-		}
164
-		if ($marginInfos['pa_products'] > 0)
165
-			$marginInfos['margin_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pa_products'];
166
-		if ($marginInfos['pv_products'] > 0)
167
-			$marginInfos['mark_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pv_products'];
103
+            // calcul des marges
104
+            if (isset($line->fk_remise_except) && isset($conf->global->MARGIN_METHODE_FOR_DISCOUNT)) {    // remise
105
+                if ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '1') { // remise globale considérée comme produit
106
+                    $marginInfos['pa_products'] += $pa;
107
+                    $marginInfos['pv_products'] += $pv;
108
+                    $marginInfos['pa_total'] +=  $pa;
109
+                    $marginInfos['pv_total'] +=  $pv;
110
+                    // if credit note, margin = -1 * (abs(selling_price) - buying_price)
111
+                    //if ($pv < 0)
112
+                    //{
113
+                    //	$marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
114
+                    //}
115
+                    //else
116
+                        $marginInfos['margin_on_products'] += $pv - $pa;
117
+                }
118
+                elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
119
+                    $marginInfos['pa_services'] += $pa;
120
+                    $marginInfos['pv_services'] += $pv;
121
+                    $marginInfos['pa_total'] +=  $pa;
122
+                    $marginInfos['pv_total'] +=  $pv;
123
+                    // if credit note, margin = -1 * (abs(selling_price) - buying_price)
124
+                    //if ($pv < 0)
125
+                    //	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
126
+                    //else
127
+                        $marginInfos['margin_on_services'] += $pv - $pa;
128
+                }
129
+                elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
130
+                    $marginInfos['pa_total'] += $pa;
131
+                    $marginInfos['pv_total'] += $pv;
132
+                }
133
+            }
134
+            else {
135
+                $type=$line->product_type?$line->product_type:$line->fk_product_type;
136
+                if ($type == 0) {  // product
137
+                    $marginInfos['pa_products'] += $pa;
138
+                    $marginInfos['pv_products'] += $pv;
139
+                    $marginInfos['pa_total'] +=  $pa;
140
+                    $marginInfos['pv_total'] +=  $pv;
141
+                    // if credit note, margin = -1 * (abs(selling_price) - buying_price)
142
+                    //if ($pv < 0)
143
+                    //{
144
+                    //    $marginInfos['margin_on_products'] += -1 * (abs($pv) - $pa);
145
+                    //}
146
+                    //else
147
+                    //{
148
+                        $marginInfos['margin_on_products'] += $pv - $pa;
149
+                    //}
150
+                }
151
+                elseif ($type == 1) {  // service
152
+                    $marginInfos['pa_services'] += $pa;
153
+                    $marginInfos['pv_services'] += $pv;
154
+                    $marginInfos['pa_total'] +=  $pa;
155
+                    $marginInfos['pv_total'] +=  $pv;
156
+                    // if credit note, margin = -1 * (abs(selling_price) - buying_price)
157
+                    //if ($pv < 0)
158
+                    //	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
159
+                    //else
160
+                        $marginInfos['margin_on_services'] += $pv - $pa;
161
+                }
162
+            }
163
+        }
164
+        if ($marginInfos['pa_products'] > 0)
165
+            $marginInfos['margin_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pa_products'];
166
+        if ($marginInfos['pv_products'] > 0)
167
+            $marginInfos['mark_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pv_products'];
168 168
 
169
-		if ($marginInfos['pa_services'] > 0)
170
-			$marginInfos['margin_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pa_services'];
171
-		if ($marginInfos['pv_services'] > 0)
172
-			$marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
169
+        if ($marginInfos['pa_services'] > 0)
170
+            $marginInfos['margin_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pa_services'];
171
+        if ($marginInfos['pv_services'] > 0)
172
+            $marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
173 173
 
174
-		// if credit note, margin = -1 * (abs(selling_price) - buying_price)
175
-		//if ($marginInfos['pv_total'] < 0)
176
-		//	$marginInfos['total_margin'] = -1 * (abs($marginInfos['pv_total']) - $marginInfos['pa_total']);
177
-		//else
178
-			$marginInfos['total_margin'] = $marginInfos['pv_total'] - $marginInfos['pa_total'];
179
-		if ($marginInfos['pa_total'] > 0)
180
-			$marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
181
-		if ($marginInfos['pv_total'] > 0)
182
-			$marginInfos['total_mark_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pv_total'];
174
+        // if credit note, margin = -1 * (abs(selling_price) - buying_price)
175
+        //if ($marginInfos['pv_total'] < 0)
176
+        //	$marginInfos['total_margin'] = -1 * (abs($marginInfos['pv_total']) - $marginInfos['pa_total']);
177
+        //else
178
+            $marginInfos['total_margin'] = $marginInfos['pv_total'] - $marginInfos['pa_total'];
179
+        if ($marginInfos['pa_total'] > 0)
180
+            $marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
181
+        if ($marginInfos['pv_total'] > 0)
182
+            $marginInfos['total_mark_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pv_total'];
183 183
 
184
-		return $marginInfos;
185
-	}
184
+        return $marginInfos;
185
+    }
186 186
 
187
-	/**
188
-	 * 	Show the array with all margin infos
189
-	 *
190
-	 *	@param	CommonObject	$object			Object we want to get margin information for
191
-	 * 	@param 	boolean			$force_price	Force price
192
-	 * 	@return	void
193
-	 */
194
-	function displayMarginInfos($object, $force_price=false)
195
-	{
196
-		global $langs, $conf, $user;
187
+    /**
188
+     * 	Show the array with all margin infos
189
+     *
190
+     *	@param	CommonObject	$object			Object we want to get margin information for
191
+     * 	@param 	boolean			$force_price	Force price
192
+     * 	@return	void
193
+     */
194
+    function displayMarginInfos($object, $force_price=false)
195
+    {
196
+        global $langs, $conf, $user;
197 197
 
198
-    	if (! empty($user->societe_id)) return;
198
+        if (! empty($user->societe_id)) return;
199 199
 
200
-    	if (! $user->rights->margins->liretous) return;
200
+        if (! $user->rights->margins->liretous) return;
201 201
 
202 202
         $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
203 203
 
204
-		$marginInfo = $this->getMarginInfosArray($object, $force_price);
204
+        $marginInfo = $this->getMarginInfosArray($object, $force_price);
205 205
 
206
-		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
207
-		{
208
-			print $langs->trans('ShowMarginInfos').' : ';
209
-	        $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
210
-	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
211
-	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
206
+        if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
207
+        {
208
+            print $langs->trans('ShowMarginInfos').' : ';
209
+            $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
210
+            print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
211
+            print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
212 212
 
213
-    	    print '<script>$(document).ready(function() {
213
+            print '<script>$(document).ready(function() {
214 214
         	    $("span#showMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 0); $(".margininfos").show(); $("span#showMarginInfos").addClass("hideobject"); $("span#hideMarginInfos").removeClass("hideobject");})});
215 215
         	    $("span#hideMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 1); $(".margininfos").hide(); $("span#hideMarginInfos").addClass("hideobject"); $("span#showMarginInfos").removeClass("hideobject");})});
216 216
       	        });</script>';
217
-    	    if (!empty($hidemargininfos)) print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
218
-		}
217
+            if (!empty($hidemargininfos)) print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
218
+        }
219 219
 
220
-		print '<div class="div-table-responsive-no-min">';
221
-		print '<!-- Margin table -->'."\n";
220
+        print '<div class="div-table-responsive-no-min">';
221
+        print '<!-- Margin table -->'."\n";
222 222
 
223
-		print '<table class="noborder margintable centpercent">';
224
-		print '<tr class="liste_titre">';
225
-		print '<td class="liste_titre">'.$langs->trans('Margins').'</td>';
226
-		print '<td class="liste_titre" align="right">'.$langs->trans('SellingPrice').'</td>';
227
-		if ($conf->global->MARGIN_TYPE == "1")
228
-			print '<td class="liste_titre" align="right">'.$langs->trans('BuyingPrice').'</td>';
229
-		else
230
-			print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
231
-		print '<td class="liste_titre" align="right">'.$langs->trans('Margin').'</td>';
232
-		if (! empty($conf->global->DISPLAY_MARGIN_RATES))
233
-			print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
234
-		if (! empty($conf->global->DISPLAY_MARK_RATES))
235
-			print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
236
-		print '</tr>';
223
+        print '<table class="noborder margintable centpercent">';
224
+        print '<tr class="liste_titre">';
225
+        print '<td class="liste_titre">'.$langs->trans('Margins').'</td>';
226
+        print '<td class="liste_titre" align="right">'.$langs->trans('SellingPrice').'</td>';
227
+        if ($conf->global->MARGIN_TYPE == "1")
228
+            print '<td class="liste_titre" align="right">'.$langs->trans('BuyingPrice').'</td>';
229
+        else
230
+            print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
231
+        print '<td class="liste_titre" align="right">'.$langs->trans('Margin').'</td>';
232
+        if (! empty($conf->global->DISPLAY_MARGIN_RATES))
233
+            print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
234
+        if (! empty($conf->global->DISPLAY_MARK_RATES))
235
+            print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
236
+        print '</tr>';
237 237
 
238
-		if (! empty($conf->product->enabled))
239
-		{
240
-			//if ($marginInfo['margin_on_products'] != 0 && $marginInfo['margin_on_services'] != 0) {
241
-			print '<tr class="oddeven">';
242
-			print '<td>'.$langs->trans('MarginOnProducts').'</td>';
243
-			print '<td align="right">'.price($marginInfo['pv_products'], null, null, null, null, $rounding).'</td>';
244
-			print '<td align="right">'.price($marginInfo['pa_products'], null, null, null, null, $rounding).'</td>';
245
-			print '<td align="right">'.price($marginInfo['margin_on_products'], null, null, null, null, $rounding).'</td>';
246
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
-				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
248
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
249
-				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
250
-			print '</tr>';
251
-		}
238
+        if (! empty($conf->product->enabled))
239
+        {
240
+            //if ($marginInfo['margin_on_products'] != 0 && $marginInfo['margin_on_services'] != 0) {
241
+            print '<tr class="oddeven">';
242
+            print '<td>'.$langs->trans('MarginOnProducts').'</td>';
243
+            print '<td align="right">'.price($marginInfo['pv_products'], null, null, null, null, $rounding).'</td>';
244
+            print '<td align="right">'.price($marginInfo['pa_products'], null, null, null, null, $rounding).'</td>';
245
+            print '<td align="right">'.price($marginInfo['margin_on_products'], null, null, null, null, $rounding).'</td>';
246
+            if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
+                print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
248
+            if (! empty($conf->global->DISPLAY_MARK_RATES))
249
+                print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
250
+            print '</tr>';
251
+        }
252 252
 
253
-		if (! empty($conf->service->enabled))
254
-		{
255
-			print '<tr class="oddeven">';
256
-			print '<td>'.$langs->trans('MarginOnServices').'</td>';
257
-			print '<td align="right">'.price($marginInfo['pv_services'], null, null, null, null, $rounding).'</td>';
258
-			print '<td align="right">'.price($marginInfo['pa_services'], null, null, null, null, $rounding).'</td>';
259
-			print '<td align="right">'.price($marginInfo['margin_on_services'], null, null, null, null, $rounding).'</td>';
260
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
261
-				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
262
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
263
-				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
264
-			print '</tr>';
265
-		}
253
+        if (! empty($conf->service->enabled))
254
+        {
255
+            print '<tr class="oddeven">';
256
+            print '<td>'.$langs->trans('MarginOnServices').'</td>';
257
+            print '<td align="right">'.price($marginInfo['pv_services'], null, null, null, null, $rounding).'</td>';
258
+            print '<td align="right">'.price($marginInfo['pa_services'], null, null, null, null, $rounding).'</td>';
259
+            print '<td align="right">'.price($marginInfo['margin_on_services'], null, null, null, null, $rounding).'</td>';
260
+            if (! empty($conf->global->DISPLAY_MARGIN_RATES))
261
+                print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
262
+            if (! empty($conf->global->DISPLAY_MARK_RATES))
263
+                print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
264
+            print '</tr>';
265
+        }
266 266
 
267
-		if (! empty($conf->product->enabled) && ! empty($conf->service->enabled))
268
-		{
269
-			print '<tr class="liste_total">';
270
-			print '<td>'.$langs->trans('TotalMargin').'</td>';
271
-			print '<td align="right">'.price($marginInfo['pv_total'], null, null, null, null, $rounding).'</td>';
272
-			print '<td align="right">'.price($marginInfo['pa_total'], null, null, null, null, $rounding).'</td>';
273
-			print '<td align="right">'.price($marginInfo['total_margin'], null, null, null, null, $rounding).'</td>';
274
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
275
-				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
276
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
277
-				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
278
-			print '</tr>';
279
-		}
280
-		print '</table>';
281
-		print '</div>';
282
-	}
267
+        if (! empty($conf->product->enabled) && ! empty($conf->service->enabled))
268
+        {
269
+            print '<tr class="liste_total">';
270
+            print '<td>'.$langs->trans('TotalMargin').'</td>';
271
+            print '<td align="right">'.price($marginInfo['pv_total'], null, null, null, null, $rounding).'</td>';
272
+            print '<td align="right">'.price($marginInfo['pa_total'], null, null, null, null, $rounding).'</td>';
273
+            print '<td align="right">'.price($marginInfo['total_margin'], null, null, null, null, $rounding).'</td>';
274
+            if (! empty($conf->global->DISPLAY_MARGIN_RATES))
275
+                print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
276
+            if (! empty($conf->global->DISPLAY_MARK_RATES))
277
+                print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
278
+            print '</tr>';
279
+        }
280
+        print '</table>';
281
+        print '</div>';
282
+    }
283 283
 }
284 284
 
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
     /**
37 37
 	 * @var string Error code (or message)
38 38
 	 */
39
-	public $error='';
39
+	public $error = '';
40 40
 
41 41
 
42 42
     /**
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 	 * 	@param 	boolean			$force_price	True of not
60 60
 	 * 	@return array							Array with info
61 61
 	 */
62
-	function getMarginInfosArray($object, $force_price=false)
62
+	function getMarginInfosArray($object, $force_price = false)
63 63
 	{
64 64
 		global $conf, $db;
65 65
 
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 				'total_mark_rate' => ''
83 83
 		);
84 84
 
85
-		foreach($object->lines as $line)
85
+		foreach ($object->lines as $line)
86 86
 		{
87 87
 			if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price)
88 88
 			{
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 			}
98 98
 
99 99
 			$pv = $line->qty * $line->subprice * (1 - $line->remise_percent / 100);
100
-			$pa_ht = ($pv < 0 ? - $line->pa_ht : $line->pa_ht);      // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
100
+			$pa_ht = ($pv < 0 ? -$line->pa_ht : $line->pa_ht); // We choosed to have line->pa_ht always positive in database, so we guess the correct sign
101 101
 			$pa = $line->qty * $pa_ht;
102 102
 
103 103
 			// calcul des marges
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 				if ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '1') { // remise globale considérée comme produit
106 106
 					$marginInfos['pa_products'] += $pa;
107 107
 					$marginInfos['pv_products'] += $pv;
108
-					$marginInfos['pa_total'] +=  $pa;
109
-					$marginInfos['pv_total'] +=  $pv;
108
+					$marginInfos['pa_total'] += $pa;
109
+					$marginInfos['pv_total'] += $pv;
110 110
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
111 111
 					//if ($pv < 0)
112 112
 					//{
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
 				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
119 119
 					$marginInfos['pa_services'] += $pa;
120 120
 					$marginInfos['pv_services'] += $pv;
121
-					$marginInfos['pa_total'] +=  $pa;
122
-					$marginInfos['pv_total'] +=  $pv;
121
+					$marginInfos['pa_total'] += $pa;
122
+					$marginInfos['pv_total'] += $pv;
123 123
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
124 124
 					//if ($pv < 0)
125 125
 					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
@@ -132,12 +132,12 @@  discard block
 block discarded – undo
132 132
 				}
133 133
 			}
134 134
 			else {
135
-				$type=$line->product_type?$line->product_type:$line->fk_product_type;
135
+				$type = $line->product_type ? $line->product_type : $line->fk_product_type;
136 136
 				if ($type == 0) {  // product
137 137
 					$marginInfos['pa_products'] += $pa;
138 138
 					$marginInfos['pv_products'] += $pv;
139
-					$marginInfos['pa_total'] +=  $pa;
140
-					$marginInfos['pv_total'] +=  $pv;
139
+					$marginInfos['pa_total'] += $pa;
140
+					$marginInfos['pv_total'] += $pv;
141 141
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
142 142
 					//if ($pv < 0)
143 143
 					//{
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
 				elseif ($type == 1) {  // service
152 152
 					$marginInfos['pa_services'] += $pa;
153 153
 					$marginInfos['pv_services'] += $pv;
154
-					$marginInfos['pa_total'] +=  $pa;
155
-					$marginInfos['pv_total'] +=  $pv;
154
+					$marginInfos['pa_total'] += $pa;
155
+					$marginInfos['pv_total'] += $pv;
156 156
 					// if credit note, margin = -1 * (abs(selling_price) - buying_price)
157 157
 					//if ($pv < 0)
158 158
 					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
@@ -191,24 +191,24 @@  discard block
 block discarded – undo
191 191
 	 * 	@param 	boolean			$force_price	Force price
192 192
 	 * 	@return	void
193 193
 	 */
194
-	function displayMarginInfos($object, $force_price=false)
194
+	function displayMarginInfos($object, $force_price = false)
195 195
 	{
196 196
 		global $langs, $conf, $user;
197 197
 
198
-    	if (! empty($user->societe_id)) return;
198
+    	if (!empty($user->societe_id)) return;
199 199
 
200
-    	if (! $user->rights->margins->liretous) return;
200
+    	if (!$user->rights->margins->liretous) return;
201 201
 
202 202
         $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
203 203
 
204 204
 		$marginInfo = $this->getMarginInfosArray($object, $force_price);
205 205
 
206
-		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
206
+		if (!empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
207 207
 		{
208 208
 			print $langs->trans('ShowMarginInfos').' : ';
209 209
 	        $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
210
-	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
211
-	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
210
+	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos) ? '' : 'hideobject').'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</span>';
211
+	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos) ? 'hideobject' : '').'">'.img_picto($langs->trans("Enabled"), 'switch_on').'</span>';
212 212
 
213 213
     	    print '<script>$(document).ready(function() {
214 214
         	    $("span#showMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 0); $(".margininfos").show(); $("span#showMarginInfos").addClass("hideobject"); $("span#hideMarginInfos").removeClass("hideobject");})});
@@ -229,13 +229,13 @@  discard block
 block discarded – undo
229 229
 		else
230 230
 			print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
231 231
 		print '<td class="liste_titre" align="right">'.$langs->trans('Margin').'</td>';
232
-		if (! empty($conf->global->DISPLAY_MARGIN_RATES))
232
+		if (!empty($conf->global->DISPLAY_MARGIN_RATES))
233 233
 			print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
234
-		if (! empty($conf->global->DISPLAY_MARK_RATES))
234
+		if (!empty($conf->global->DISPLAY_MARK_RATES))
235 235
 			print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
236 236
 		print '</tr>';
237 237
 
238
-		if (! empty($conf->product->enabled))
238
+		if (!empty($conf->product->enabled))
239 239
 		{
240 240
 			//if ($marginInfo['margin_on_products'] != 0 && $marginInfo['margin_on_services'] != 0) {
241 241
 			print '<tr class="oddeven">';
@@ -243,38 +243,38 @@  discard block
 block discarded – undo
243 243
 			print '<td align="right">'.price($marginInfo['pv_products'], null, null, null, null, $rounding).'</td>';
244 244
 			print '<td align="right">'.price($marginInfo['pa_products'], null, null, null, null, $rounding).'</td>';
245 245
 			print '<td align="right">'.price($marginInfo['margin_on_products'], null, null, null, null, $rounding).'</td>';
246
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
-				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
248
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
249
-				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
246
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
247
+				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '') ? '' : price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
248
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
249
+				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '') ? '' : price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
250 250
 			print '</tr>';
251 251
 		}
252 252
 
253
-		if (! empty($conf->service->enabled))
253
+		if (!empty($conf->service->enabled))
254 254
 		{
255 255
 			print '<tr class="oddeven">';
256 256
 			print '<td>'.$langs->trans('MarginOnServices').'</td>';
257 257
 			print '<td align="right">'.price($marginInfo['pv_services'], null, null, null, null, $rounding).'</td>';
258 258
 			print '<td align="right">'.price($marginInfo['pa_services'], null, null, null, null, $rounding).'</td>';
259 259
 			print '<td align="right">'.price($marginInfo['margin_on_services'], null, null, null, null, $rounding).'</td>';
260
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
261
-				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
262
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
263
-				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
260
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
261
+				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '') ? '' : price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
262
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
263
+				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '') ? '' : price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
264 264
 			print '</tr>';
265 265
 		}
266 266
 
267
-		if (! empty($conf->product->enabled) && ! empty($conf->service->enabled))
267
+		if (!empty($conf->product->enabled) && !empty($conf->service->enabled))
268 268
 		{
269 269
 			print '<tr class="liste_total">';
270 270
 			print '<td>'.$langs->trans('TotalMargin').'</td>';
271 271
 			print '<td align="right">'.price($marginInfo['pv_total'], null, null, null, null, $rounding).'</td>';
272 272
 			print '<td align="right">'.price($marginInfo['pa_total'], null, null, null, null, $rounding).'</td>';
273 273
 			print '<td align="right">'.price($marginInfo['total_margin'], null, null, null, null, $rounding).'</td>';
274
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
275
-				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
276
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
277
-				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
274
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
275
+				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
276
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
277
+				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
278 278
 			print '</tr>';
279 279
 		}
280 280
 		print '</table>';
Please login to merge, or discard this patch.
Braces   +66 added lines, -46 removed lines patch added patch discarded remove patch
@@ -88,8 +88,9 @@  discard block
 block discarded – undo
88 88
 			{
89 89
 				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
90 90
 				$product = new ProductFournisseur($db);
91
-				if ($product->fetch_product_fournisseur_price($line->fk_fournprice))
92
-					$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
91
+				if ($product->fetch_product_fournisseur_price($line->fk_fournprice)) {
92
+									$line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
93
+				}
93 94
 			}
94 95
 			// si prix d'achat non renseigné et devrait l'être, alors prix achat = prix vente
95 96
 			if ((!isset($line->pa_ht) || $line->pa_ht == 0) && $line->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
@@ -114,8 +115,7 @@  discard block
 block discarded – undo
114 115
 					//}
115 116
 					//else
116 117
 						$marginInfos['margin_on_products'] += $pv - $pa;
117
-				}
118
-				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
118
+				} elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service
119 119
 					$marginInfos['pa_services'] += $pa;
120 120
 					$marginInfos['pv_services'] += $pv;
121 121
 					$marginInfos['pa_total'] +=  $pa;
@@ -125,13 +125,11 @@  discard block
 block discarded – undo
125 125
 					//	$marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa);
126 126
 					//else
127 127
 						$marginInfos['margin_on_services'] += $pv - $pa;
128
-				}
129
-				elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
128
+				} elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total
130 129
 					$marginInfos['pa_total'] += $pa;
131 130
 					$marginInfos['pv_total'] += $pv;
132 131
 				}
133
-			}
134
-			else {
132
+			} else {
135 133
 				$type=$line->product_type?$line->product_type:$line->fk_product_type;
136 134
 				if ($type == 0) {  // product
137 135
 					$marginInfos['pa_products'] += $pa;
@@ -147,8 +145,7 @@  discard block
 block discarded – undo
147 145
 					//{
148 146
 					    $marginInfos['margin_on_products'] += $pv - $pa;
149 147
 					//}
150
-				}
151
-				elseif ($type == 1) {  // service
148
+				} elseif ($type == 1) {  // service
152 149
 					$marginInfos['pa_services'] += $pa;
153 150
 					$marginInfos['pv_services'] += $pv;
154 151
 					$marginInfos['pa_total'] +=  $pa;
@@ -161,25 +158,31 @@  discard block
 block discarded – undo
161 158
 				}
162 159
 			}
163 160
 		}
164
-		if ($marginInfos['pa_products'] > 0)
165
-			$marginInfos['margin_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pa_products'];
166
-		if ($marginInfos['pv_products'] > 0)
167
-			$marginInfos['mark_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pv_products'];
161
+		if ($marginInfos['pa_products'] > 0) {
162
+					$marginInfos['margin_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pa_products'];
163
+		}
164
+		if ($marginInfos['pv_products'] > 0) {
165
+					$marginInfos['mark_rate_products'] = 100 * $marginInfos['margin_on_products'] / $marginInfos['pv_products'];
166
+		}
168 167
 
169
-		if ($marginInfos['pa_services'] > 0)
170
-			$marginInfos['margin_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pa_services'];
171
-		if ($marginInfos['pv_services'] > 0)
172
-			$marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
168
+		if ($marginInfos['pa_services'] > 0) {
169
+					$marginInfos['margin_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pa_services'];
170
+		}
171
+		if ($marginInfos['pv_services'] > 0) {
172
+					$marginInfos['mark_rate_services'] = 100 * $marginInfos['margin_on_services'] / $marginInfos['pv_services'];
173
+		}
173 174
 
174 175
 		// if credit note, margin = -1 * (abs(selling_price) - buying_price)
175 176
 		//if ($marginInfos['pv_total'] < 0)
176 177
 		//	$marginInfos['total_margin'] = -1 * (abs($marginInfos['pv_total']) - $marginInfos['pa_total']);
177 178
 		//else
178 179
 			$marginInfos['total_margin'] = $marginInfos['pv_total'] - $marginInfos['pa_total'];
179
-		if ($marginInfos['pa_total'] > 0)
180
-			$marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
181
-		if ($marginInfos['pv_total'] > 0)
182
-			$marginInfos['total_mark_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pv_total'];
180
+		if ($marginInfos['pa_total'] > 0) {
181
+					$marginInfos['total_margin_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pa_total'];
182
+		}
183
+		if ($marginInfos['pv_total'] > 0) {
184
+					$marginInfos['total_mark_rate'] = 100 * $marginInfos['total_margin'] / $marginInfos['pv_total'];
185
+		}
183 186
 
184 187
 		return $marginInfos;
185 188
 	}
@@ -195,17 +198,23 @@  discard block
 block discarded – undo
195 198
 	{
196 199
 		global $langs, $conf, $user;
197 200
 
198
-    	if (! empty($user->societe_id)) return;
201
+    	if (! empty($user->societe_id)) {
202
+    	    return;
203
+    	}
199 204
 
200
-    	if (! $user->rights->margins->liretous) return;
205
+    	if (! $user->rights->margins->liretous) {
206
+    	    return;
207
+    	}
201 208
 
202 209
         $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
203 210
 
204 211
 		$marginInfo = $this->getMarginInfosArray($object, $force_price);
205 212
 
206
-		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON))	// TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
213
+		if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON)) {
214
+		    // TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
207 215
 		{
208 216
 			print $langs->trans('ShowMarginInfos').' : ';
217
+		}
209 218
 	        $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW'];
210 219
 	    	print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'':'hideobject').'">'.img_picto($langs->trans("Disabled"),'switch_off').'</span>';
211 220
 	    	print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos)?'hideobject':'').'">'.img_picto($langs->trans("Enabled"),'switch_on').'</span>';
@@ -214,7 +223,9 @@  discard block
 block discarded – undo
214 223
         	    $("span#showMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 0); $(".margininfos").show(); $("span#showMarginInfos").addClass("hideobject"); $("span#hideMarginInfos").removeClass("hideobject");})});
215 224
         	    $("span#hideMarginInfos").click(function() { $.getScript( "'.dol_buildpath('/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', 1).'", function( data, textStatus, jqxhr ) { $.cookie("DOLUSER_MARGININFO_HIDE_SHOW", 1); $(".margininfos").hide(); $("span#hideMarginInfos").addClass("hideobject"); $("span#showMarginInfos").removeClass("hideobject");})});
216 225
       	        });</script>';
217
-    	    if (!empty($hidemargininfos)) print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
226
+    	    if (!empty($hidemargininfos)) {
227
+    	        print '<script>$(document).ready(function() {$(".margininfos").hide();});</script>';
228
+    	    }
218 229
 		}
219 230
 
220 231
 		print '<div class="div-table-responsive-no-min">';
@@ -224,15 +235,18 @@  discard block
 block discarded – undo
224 235
 		print '<tr class="liste_titre">';
225 236
 		print '<td class="liste_titre">'.$langs->trans('Margins').'</td>';
226 237
 		print '<td class="liste_titre" align="right">'.$langs->trans('SellingPrice').'</td>';
227
-		if ($conf->global->MARGIN_TYPE == "1")
228
-			print '<td class="liste_titre" align="right">'.$langs->trans('BuyingPrice').'</td>';
229
-		else
230
-			print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
238
+		if ($conf->global->MARGIN_TYPE == "1") {
239
+					print '<td class="liste_titre" align="right">'.$langs->trans('BuyingPrice').'</td>';
240
+		} else {
241
+					print '<td class="liste_titre" align="right">'.$langs->trans('CostPrice').'</td>';
242
+		}
231 243
 		print '<td class="liste_titre" align="right">'.$langs->trans('Margin').'</td>';
232
-		if (! empty($conf->global->DISPLAY_MARGIN_RATES))
233
-			print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
234
-		if (! empty($conf->global->DISPLAY_MARK_RATES))
235
-			print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
244
+		if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
245
+					print '<td class="liste_titre" align="right">'.$langs->trans('MarginRate').'</td>';
246
+		}
247
+		if (! empty($conf->global->DISPLAY_MARK_RATES)) {
248
+					print '<td class="liste_titre" align="right">'.$langs->trans('MarkRate').'</td>';
249
+		}
236 250
 		print '</tr>';
237 251
 
238 252
 		if (! empty($conf->product->enabled))
@@ -243,10 +257,12 @@  discard block
 block discarded – undo
243 257
 			print '<td align="right">'.price($marginInfo['pv_products'], null, null, null, null, $rounding).'</td>';
244 258
 			print '<td align="right">'.price($marginInfo['pa_products'], null, null, null, null, $rounding).'</td>';
245 259
 			print '<td align="right">'.price($marginInfo['margin_on_products'], null, null, null, null, $rounding).'</td>';
246
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
-				print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
248
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
249
-				print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
260
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
261
+							print '<td align="right">'.(($marginInfo['margin_rate_products'] == '')?'':price($marginInfo['margin_rate_products'], null, null, null, null, $rounding).'%').'</td>';
262
+			}
263
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
264
+							print '<td align="right">'.(($marginInfo['mark_rate_products'] == '')?'':price($marginInfo['mark_rate_products'], null, null, null, null, $rounding).'%').'</td>';
265
+			}
250 266
 			print '</tr>';
251 267
 		}
252 268
 
@@ -257,10 +273,12 @@  discard block
 block discarded – undo
257 273
 			print '<td align="right">'.price($marginInfo['pv_services'], null, null, null, null, $rounding).'</td>';
258 274
 			print '<td align="right">'.price($marginInfo['pa_services'], null, null, null, null, $rounding).'</td>';
259 275
 			print '<td align="right">'.price($marginInfo['margin_on_services'], null, null, null, null, $rounding).'</td>';
260
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
261
-				print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
262
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
263
-				print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
276
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
277
+							print '<td align="right">'.(($marginInfo['margin_rate_services'] == '')?'':price($marginInfo['margin_rate_services'], null, null, null, null, $rounding).'%').'</td>';
278
+			}
279
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
280
+							print '<td align="right">'.(($marginInfo['mark_rate_services'] == '')?'':price($marginInfo['mark_rate_services'], null, null, null, null, $rounding).'%').'</td>';
281
+			}
264 282
 			print '</tr>';
265 283
 		}
266 284
 
@@ -271,10 +289,12 @@  discard block
 block discarded – undo
271 289
 			print '<td align="right">'.price($marginInfo['pv_total'], null, null, null, null, $rounding).'</td>';
272 290
 			print '<td align="right">'.price($marginInfo['pa_total'], null, null, null, null, $rounding).'</td>';
273 291
 			print '<td align="right">'.price($marginInfo['total_margin'], null, null, null, null, $rounding).'</td>';
274
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
275
-				print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
276
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
277
-				print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
292
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
293
+							print '<td align="right">'.(($marginInfo['total_margin_rate'] == '')?'':price($marginInfo['total_margin_rate'], null, null, null, null, $rounding).'%').'</td>';
294
+			}
295
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
296
+							print '<td align="right">'.(($marginInfo['total_mark_rate'] == '')?'':price($marginInfo['total_mark_rate'], null, null, null, null, $rounding).'%').'</td>';
297
+			}
278 298
 			print '</tr>';
279 299
 		}
280 300
 		print '</table>';
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formpropal.class.php 3 patches
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -27,26 +27,26 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class FormPropal
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 40
 
41
-	/**
42
-	 * Constructor
43
-	 *
44
-	 * @param		DoliDB		$db      Database handler
45
-	 */
46
-	public function __construct($db)
47
-	{
48
-		$this->db = $db;
49
-	}
41
+    /**
42
+     * Constructor
43
+     *
44
+     * @param		DoliDB		$db      Database handler
45
+     */
46
+    public function __construct($db)
47
+    {
48
+        $this->db = $db;
49
+    }
50 50
 
51 51
     /**
52 52
      *    Return combo list of differents status of a proposal
@@ -114,11 +114,11 @@  discard block
 block discarded – undo
114 114
         {
115 115
             if ($excludedraft)
116 116
             {
117
-				if ($obj['code'] == 'Draft' || $obj['code'] == 'PR_DRAFT')
118
-				{
119
-					$i++;
120
-					continue;
121
-				}
117
+                if ($obj['code'] == 'Draft' || $obj['code'] == 'PR_DRAFT')
118
+                {
119
+                    $i++;
120
+                    continue;
121
+                }
122 122
             }
123 123
             if ($selected != '' && $selected == $obj['id'])
124 124
             {
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
                 print $langs->trans($prefix.$key.($short?'Short':''));
135 135
             }
136 136
             else
137
-			{
137
+            {
138 138
                 $conv_to_new_code=array('PR_DRAFT'=>'Draft','PR_OPEN'=>'Validated','PR_CLOSED'=>'Closed','PR_SIGNED'=>'Signed','PR_NOTSIGNED'=>'NotSigned','PR_FAC'=>'Billed');
139 139
                 if (! empty($conv_to_new_code[$obj['code']])) $key=$conv_to_new_code[$obj['code']];
140 140
 
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 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
 	/**
@@ -60,18 +60,18 @@  discard block
 block discarded – undo
60 60
      *    @param    string  $htmlname       Name of select field
61 61
      *    @return	void
62 62
      */
63
-    function selectProposalStatus($selected='',$short=0, $excludedraft=0, $showempty=1, $mode='customer',$htmlname='propal_statut')
63
+    function selectProposalStatus($selected = '', $short = 0, $excludedraft = 0, $showempty = 1, $mode = 'customer', $htmlname = 'propal_statut')
64 64
     {
65 65
         global $langs;
66 66
 
67
-        $prefix='';
68
-        $listofstatus=array();
67
+        $prefix = '';
68
+        $listofstatus = array();
69 69
         if ($mode == 'supplier')
70 70
         {
71
-            $prefix='SupplierProposalStatus';
71
+            $prefix = 'SupplierProposalStatus';
72 72
 
73 73
             $langs->load("supplier_proposal");
74
-            $listofstatus=array(
74
+            $listofstatus = array(
75 75
                 0=>array('id'=>0, 'code'=>'PR_DRAFT'),
76 76
                 1=>array('id'=>1, 'code'=>'PR_OPEN'),
77 77
                 2=>array('id'=>2, 'code'=>'PR_SIGNED'),
@@ -81,12 +81,12 @@  discard block
 block discarded – undo
81 81
         }
82 82
         else
83 83
         {
84
-            $prefix="PropalStatus";
84
+            $prefix = "PropalStatus";
85 85
 
86 86
             $sql = "SELECT id, code, label, active FROM ".MAIN_DB_PREFIX."c_propalst";
87 87
             $sql .= " WHERE active = 1";
88 88
             dol_syslog(get_class($this)."::selectProposalStatus", LOG_DEBUG);
89
-            $resql=$this->db->query($sql);
89
+            $resql = $this->db->query($sql);
90 90
             if ($resql)
91 91
             {
92 92
                 $num = $this->db->num_rows($resql);
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
                     while ($i < $num)
97 97
                     {
98 98
                         $obj = $this->db->fetch_object($resql);
99
-                        $listofstatus[$obj->id]=array('id'=>$obj->id,'code'=>$obj->code,'label'=>$obj->label);
99
+                        $listofstatus[$obj->id] = array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$obj->label);
100 100
                         $i++;
101 101
                     }
102 102
                 }
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
         print '<select class="flat" name="'.$htmlname.'">';
111 111
         if ($showempty) print '<option value="-1">&nbsp;</option>';
112 112
 
113
-        foreach($listofstatus as $key => $obj)
113
+        foreach ($listofstatus as $key => $obj)
114 114
         {
115 115
             if ($excludedraft)
116 116
             {
@@ -128,17 +128,17 @@  discard block
 block discarded – undo
128 128
             {
129 129
                 print '<option value="'.$obj['id'].'">';
130 130
             }
131
-            $key=$obj['code'];
132
-            if ($langs->trans($prefix.$key.($short?'Short':'')) != $prefix.$key.($short?'Short':''))
131
+            $key = $obj['code'];
132
+            if ($langs->trans($prefix.$key.($short ? 'Short' : '')) != $prefix.$key.($short ? 'Short' : ''))
133 133
             {
134
-                print $langs->trans($prefix.$key.($short?'Short':''));
134
+                print $langs->trans($prefix.$key.($short ? 'Short' : ''));
135 135
             }
136 136
             else
137 137
 			{
138
-                $conv_to_new_code=array('PR_DRAFT'=>'Draft','PR_OPEN'=>'Validated','PR_CLOSED'=>'Closed','PR_SIGNED'=>'Signed','PR_NOTSIGNED'=>'NotSigned','PR_FAC'=>'Billed');
139
-                if (! empty($conv_to_new_code[$obj['code']])) $key=$conv_to_new_code[$obj['code']];
138
+                $conv_to_new_code = array('PR_DRAFT'=>'Draft', 'PR_OPEN'=>'Validated', 'PR_CLOSED'=>'Closed', 'PR_SIGNED'=>'Signed', 'PR_NOTSIGNED'=>'NotSigned', 'PR_FAC'=>'Billed');
139
+                if (!empty($conv_to_new_code[$obj['code']])) $key = $conv_to_new_code[$obj['code']];
140 140
 
141
-                print ($langs->trans($prefix.$key.($short?'Short':''))!=$prefix.$key.($short?'Short':''))?$langs->trans($prefix.$key.($short?'Short':'')):($obj['label']?$obj['label']:$obj['code']);
141
+                print ($langs->trans($prefix.$key.($short ? 'Short' : '')) != $prefix.$key.($short ? 'Short' : '')) ? $langs->trans($prefix.$key.($short ? 'Short' : '')) : ($obj['label'] ? $obj['label'] : $obj['code']);
142 142
             }
143 143
             print '</option>';
144 144
             $i++;
Please login to merge, or discard this patch.
Braces   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -78,8 +78,7 @@  discard block
 block discarded – undo
78 78
                 3=>array('id'=>3, 'code'=>'PR_NOTSIGNED'),
79 79
                 4=>array('id'=>4, 'code'=>'PR_CLOSED')
80 80
             );
81
-        }
82
-        else
81
+        } else
83 82
         {
84 83
             $prefix="PropalStatus";
85 84
 
@@ -100,15 +99,16 @@  discard block
 block discarded – undo
100 99
                         $i++;
101 100
                     }
102 101
                 }
103
-            }
104
-            else
102
+            } else
105 103
             {
106 104
                 dol_print_error($this->db);
107 105
             }
108 106
         }
109 107
 
110 108
         print '<select class="flat" name="'.$htmlname.'">';
111
-        if ($showempty) print '<option value="-1">&nbsp;</option>';
109
+        if ($showempty) {
110
+            print '<option value="-1">&nbsp;</option>';
111
+        }
112 112
 
113 113
         foreach($listofstatus as $key => $obj)
114 114
         {
@@ -123,8 +123,7 @@  discard block
 block discarded – undo
123 123
             if ($selected != '' && $selected == $obj['id'])
124 124
             {
125 125
                 print '<option value="'.$obj['id'].'" selected>';
126
-            }
127
-            else
126
+            } else
128 127
             {
129 128
                 print '<option value="'.$obj['id'].'">';
130 129
             }
@@ -132,11 +131,12 @@  discard block
 block discarded – undo
132 131
             if ($langs->trans($prefix.$key.($short?'Short':'')) != $prefix.$key.($short?'Short':''))
133 132
             {
134 133
                 print $langs->trans($prefix.$key.($short?'Short':''));
135
-            }
136
-            else
134
+            } else
137 135
 			{
138 136
                 $conv_to_new_code=array('PR_DRAFT'=>'Draft','PR_OPEN'=>'Validated','PR_CLOSED'=>'Closed','PR_SIGNED'=>'Signed','PR_NOTSIGNED'=>'NotSigned','PR_FAC'=>'Billed');
139
-                if (! empty($conv_to_new_code[$obj['code']])) $key=$conv_to_new_code[$obj['code']];
137
+                if (! empty($conv_to_new_code[$obj['code']])) {
138
+                    $key=$conv_to_new_code[$obj['code']];
139
+                }
140 140
 
141 141
                 print ($langs->trans($prefix.$key.($short?'Short':''))!=$prefix.$key.($short?'Short':''))?$langs->trans($prefix.$key.($short?'Short':'')):($obj['label']?$obj['label']:$obj['code']);
142 142
             }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/discount.class.php 3 patches
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -34,23 +34,23 @@  discard block
 block discarded – undo
34 34
     public $db;
35 35
 
36 36
     /**
37
-	 * @var string Error code (or message)
38
-	 */
39
-	public $error;
37
+     * @var string Error code (or message)
38
+     */
39
+    public $error;
40 40
 
41
-	/**
42
-	 * @var string[]	Array of error strings
43
-	 */
44
-	public $errors=array();
41
+    /**
42
+     * @var string[]	Array of error strings
43
+     */
44
+    public $errors=array();
45 45
 
46
-	/**
47
-	 * @var int ID discount
48
-	 */
49
-	public $id;
46
+    /**
47
+     * @var int ID discount
48
+     */
49
+    public $id;
50 50
 
51 51
     /**
52
-	 * @var int Thirdparty ID
53
-	 */
52
+     * @var int Thirdparty ID
53
+     */
54 54
     public $fk_soc;
55 55
 
56 56
     public $discount_type;			// 0 => customer discount, 1 => supplier discount
@@ -60,14 +60,14 @@  discard block
 block discarded – undo
60 60
     public $tva_tx;				// Vat rate
61 61
 
62 62
     /**
63
-	 * @var int User ID Id utilisateur qui accorde la remise
64
-	 */
65
-	public $fk_user;
63
+     * @var int User ID Id utilisateur qui accorde la remise
64
+     */
65
+    public $fk_user;
66 66
 
67 67
     /**
68
-	 * @var string description
69
-	 */
70
-	public $description;
68
+     * @var string description
69
+     */
70
+    public $description;
71 71
 
72 72
     public $datec;					// Date creation
73 73
 
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
      */
112 112
     function fetch($rowid, $fk_facture_source=0, $fk_invoice_supplier_source=0)
113 113
     {
114
-    	global $conf;
114
+        global $conf;
115 115
 
116 116
         // Check parameters
117 117
         if (! $rowid && ! $fk_facture_source && ! $fk_invoice_supplier_source)
@@ -288,29 +288,29 @@  discard block
 block discarded – undo
288 288
         // Check if we can remove the discount
289 289
         if ($this->fk_invoice_supplier_source)
290 290
         {
291
-        	$sql="SELECT COUNT(rowid) as nb";
292
-        	$sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except";
293
-        	$sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL";	// Not used as absolute simple discount
294
-        	$sql.=" OR fk_invoice_supplier IS NOT NULL)"; 			// Not used as credit note and not used as deposit
295
-        	$sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
296
-        	//$sql.=" AND rowid != ".$this->id;
297
-
298
-        	dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
299
-        	$resql=$this->db->query($sql);
300
-        	if ($resql)
301
-        	{
302
-        		$obj = $this->db->fetch_object($resql);
303
-        		if ($obj->nb > 0)
304
-        		{
305
-        			$this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
306
-        			return -2;
307
-        		}
308
-        	}
309
-        	else
310
-        	{
311
-        		dol_print_error($this->db);
312
-        		return -1;
313
-        	}
291
+            $sql="SELECT COUNT(rowid) as nb";
292
+            $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except";
293
+            $sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL";	// Not used as absolute simple discount
294
+            $sql.=" OR fk_invoice_supplier IS NOT NULL)"; 			// Not used as credit note and not used as deposit
295
+            $sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
296
+            //$sql.=" AND rowid != ".$this->id;
297
+
298
+            dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
299
+            $resql=$this->db->query($sql);
300
+            if ($resql)
301
+            {
302
+                $obj = $this->db->fetch_object($resql);
303
+                if ($obj->nb > 0)
304
+                {
305
+                    $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
306
+                    return -2;
307
+                }
308
+            }
309
+            else
310
+            {
311
+                dol_print_error($this->db);
312
+                return -1;
313
+            }
314 314
         }
315 315
 
316 316
         $this->db->begin();
@@ -352,23 +352,23 @@  discard block
 block discarded – undo
352 352
             }
353 353
             elseif($this->fk_invoice_supplier_source) {
354 354
 
355
-            	$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
356
-            	$sql.=" set paye=0, fk_statut=1";
357
-            	$sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source;
358
-
359
-            	dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
360
-            	$result=$this->db->query($sql);
361
-            	if ($result)
362
-            	{
363
-            		$this->db->commit();
364
-            		return 1;
365
-            	}
366
-            	else
367
-            	{
368
-            		$this->error=$this->db->lasterror();
369
-            		$this->db->rollback();
370
-            		return -1;
371
-            	}
355
+                $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
356
+                $sql.=" set paye=0, fk_statut=1";
357
+                $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source;
358
+
359
+                dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
360
+                $result=$this->db->query($sql);
361
+                if ($result)
362
+                {
363
+                    $this->db->commit();
364
+                    return 1;
365
+                }
366
+                else
367
+                {
368
+                    $this->error=$this->db->lasterror();
369
+                    $this->db->rollback();
370
+                    return -1;
371
+                }
372 372
             }
373 373
             else
374 374
             {
@@ -413,11 +413,11 @@  discard block
 block discarded – undo
413 413
 
414 414
         $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
415 415
         if(! empty($this->discount_type)) {
416
-        	if ($rowidline)    $sql.=" SET fk_invoice_supplier_line = ".$rowidline;
417
-        	if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice;
416
+            if ($rowidline)    $sql.=" SET fk_invoice_supplier_line = ".$rowidline;
417
+            if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice;
418 418
         } else {
419
-        	if ($rowidline)    $sql.=" SET fk_facture_line = ".$rowidline;
420
-        	if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice;
419
+            if ($rowidline)    $sql.=" SET fk_facture_line = ".$rowidline;
420
+            if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice;
421 421
         }
422 422
         $sql.=" WHERE rowid = ".$this->id;
423 423
 
@@ -425,13 +425,13 @@  discard block
 block discarded – undo
425 425
         $resql = $this->db->query($sql);
426 426
         if ($resql)
427 427
         {
428
-        	if(! empty($this->discount_type)) {
429
-        		$this->fk_invoice_supplier_line=$rowidline;
430
-        		$this->fk_invoice_supplier=$rowidinvoice;
431
-        	} else {
432
-        		$this->fk_facture_line=$rowidline;
433
-        		$this->fk_facture=$rowidinvoice;
434
-        	}
428
+            if(! empty($this->discount_type)) {
429
+                $this->fk_invoice_supplier_line=$rowidline;
430
+                $this->fk_invoice_supplier=$rowidinvoice;
431
+            } else {
432
+                $this->fk_facture_line=$rowidline;
433
+                $this->fk_facture=$rowidinvoice;
434
+            }
435 435
             return 1;
436 436
         }
437 437
         else
@@ -453,11 +453,11 @@  discard block
 block discarded – undo
453 453
     {
454 454
         // phpcs:enable
455 455
         $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
456
-		if(! empty($this->discount_type)) {
457
-       		$sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
458
-		} else {
459
-			$sql.=" SET fk_facture_line = NULL, fk_facture = NULL";
460
-		}
456
+        if(! empty($this->discount_type)) {
457
+                $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
458
+        } else {
459
+            $sql.=" SET fk_facture_line = NULL, fk_facture = NULL";
460
+        }
461 461
         $sql.=" WHERE rowid = ".$this->id;
462 462
 
463 463
         dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG);
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
      */
487 487
     function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $discount_type=0)
488 488
     {
489
-    	global $conf;
489
+        global $conf;
490 490
 
491 491
         $sql  = "SELECT SUM(rc.amount_ttc) as amount";
492 492
         //$sql  = "SELECT rc.amount_ttc as amount";
@@ -494,9 +494,9 @@  discard block
 block discarded – undo
494 494
         $sql.= " WHERE rc.entity = " . $conf->entity;
495 495
         $sql.= " AND rc.discount_type=".intval($discount_type);
496 496
         if (! empty($discount_type)) {
497
-        	$sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
497
+            $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
498 498
         } else {
499
-        	$sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
499
+            $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
500 500
         }
501 501
         if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id;
502 502
         if (is_object($user))    $sql.= " AND rc.fk_user = ".$user->id;
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
      *  Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended).
525 525
      *
526 526
      *	@param		CommonInvoice	$invoice		Object invoice (customer of supplier)
527
-	 *  @param 		int 		    $multicurrency 	Return multicurrency_amount instead of amount
527
+     *  @param 		int 		    $multicurrency 	Return multicurrency_amount instead of amount
528 528
      *	@return		int				     			<0 if KO, Sum of credit notes and deposits amount otherwise
529 529
      */
530 530
     function getSumDepositsUsed($invoice, $multicurrency=0)
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
         {
558 558
             $obj = $this->db->fetch_object($resql);
559 559
             if ($multicurrency) return $obj->multicurrency_amount;
560
-			else return $obj->amount;
560
+            else return $obj->amount;
561 561
         }
562 562
         else
563 563
         {
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
      *  Return amount (with tax) of all credit notes invoices + excess received used by invoice as a payment
571 571
      *
572 572
      *	@param		CommonInvoice	  $invoice	    	Object invoice
573
-	 *	@param		int			      $multicurrency	Return multicurrency_amount instead of amount
573
+     *	@param		int			      $multicurrency	Return multicurrency_amount instead of amount
574 574
      *	@return		int					        		<0 if KO, Sum of credit notes and excess received amount otherwise
575 575
      */
576 576
     function getSumCreditNotesUsed($invoice, $multicurrency=0)
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
         {
604 604
             $obj = $this->db->fetch_object($resql);
605 605
             if ($multicurrency) return $obj->multicurrency_amount;
606
-			else return $obj->amount;
606
+            else return $obj->amount;
607 607
         }
608 608
         else
609 609
         {
@@ -650,22 +650,22 @@  discard block
 block discarded – undo
650 650
     }
651 651
 
652 652
 
653
-	/**
653
+    /**
654 654
      *  Initialise an instance with random values.
655 655
      *  Used to build previews or test instances.
656 656
      *	id must be 0 if object instance is a specimen.
657 657
      *
658 658
      *  @return	void
659
-	 */
660
-	function initAsSpecimen()
661
-	{
662
-		global $user,$langs,$conf;
663
-
664
-		$this->fk_soc         = 1;
665
-		$this->amount_ht      = 10;
666
-		$this->amount_tva     = 1.96;
667
-		$this->amount_ttc     = 11.96;
668
-		$this->tva_tx         = 19.6;
669
-		$this->description    = 'Specimen discount';
670
-	}
659
+     */
660
+    function initAsSpecimen()
661
+    {
662
+        global $user,$langs,$conf;
663
+
664
+        $this->fk_soc         = 1;
665
+        $this->amount_ht      = 10;
666
+        $this->amount_tva     = 1.96;
667
+        $this->amount_ttc     = 11.96;
668
+        $this->tva_tx         = 19.6;
669
+        $this->description    = 'Specimen discount';
670
+    }
671 671
 }
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 	/**
42 42
 	 * @var string[]	Array of error strings
43 43
 	 */
44
-	public $errors=array();
44
+	public $errors = array();
45 45
 
46 46
 	/**
47 47
 	 * @var int ID discount
@@ -53,11 +53,11 @@  discard block
 block discarded – undo
53 53
 	 */
54 54
     public $fk_soc;
55 55
 
56
-    public $discount_type;			// 0 => customer discount, 1 => supplier discount
57
-    public $amount_ht;				//
58
-    public $amount_tva;			//
59
-    public $amount_ttc;			//
60
-    public $tva_tx;				// Vat rate
56
+    public $discount_type; // 0 => customer discount, 1 => supplier discount
57
+    public $amount_ht; //
58
+    public $amount_tva; //
59
+    public $amount_ttc; //
60
+    public $tva_tx; // Vat rate
61 61
 
62 62
     /**
63 63
 	 * @var int User ID Id utilisateur qui accorde la remise
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	 */
70 70
 	public $description;
71 71
 
72
-    public $datec;					// Date creation
72
+    public $datec; // Date creation
73 73
 
74 74
     /**
75 75
      * @var int ID invoice line when a discount is used into an invoice line (for absolute discounts)
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
      */
87 87
     public $fk_facture_source;
88 88
 
89
-    public $ref_facture_source;	    // Ref credit note having caused the discount
89
+    public $ref_facture_source; // Ref credit note having caused the discount
90 90
 
91 91
     public $ref_invoice_supplier_source;
92 92
 
@@ -109,31 +109,31 @@  discard block
 block discarded – undo
109 109
      *  @param		int		$fk_invoice_supplier_source		fk_invoice_supplier_source
110 110
      *	@return		int										<0 if KO, =0 if not found, >0 if OK
111 111
      */
112
-    function fetch($rowid, $fk_facture_source=0, $fk_invoice_supplier_source=0)
112
+    function fetch($rowid, $fk_facture_source = 0, $fk_invoice_supplier_source = 0)
113 113
     {
114 114
     	global $conf;
115 115
 
116 116
         // Check parameters
117
-        if (! $rowid && ! $fk_facture_source && ! $fk_invoice_supplier_source)
117
+        if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source)
118 118
         {
119
-            $this->error='ErrorBadParameters';
119
+            $this->error = 'ErrorBadParameters';
120 120
             return -1;
121 121
         }
122 122
 
123 123
         $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,";
124
-        $sql.= " sr.fk_user,";
125
-        $sql.= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,";
126
-        $sql.= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,";
127
-        $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.fk_invoice_supplier_line, sr.fk_invoice_supplier, sr.fk_invoice_supplier_source, sr.description,";
128
-        $sql.= " sr.datec,";
129
-        $sql.= " f.ref as ref_facture_source, fsup.ref as ref_invoice_supplier_source";
130
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
131
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid";
132
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid";
133
-        $sql.= " WHERE sr.entity = " . $conf->entity;
134
-        if ($rowid) $sql.= " AND sr.rowid=".$rowid;
135
-        if ($fk_facture_source) $sql.= " AND sr.fk_facture_source=".$fk_facture_source;
136
-        if ($fk_invoice_supplier_source) $sql.= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source;
124
+        $sql .= " sr.fk_user,";
125
+        $sql .= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,";
126
+        $sql .= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,";
127
+        $sql .= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.fk_invoice_supplier_line, sr.fk_invoice_supplier, sr.fk_invoice_supplier_source, sr.description,";
128
+        $sql .= " sr.datec,";
129
+        $sql .= " f.ref as ref_facture_source, fsup.ref as ref_invoice_supplier_source";
130
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
131
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid";
132
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid";
133
+        $sql .= " WHERE sr.entity = ".$conf->entity;
134
+        if ($rowid) $sql .= " AND sr.rowid=".$rowid;
135
+        if ($fk_facture_source) $sql .= " AND sr.fk_facture_source=".$fk_facture_source;
136
+        if ($fk_invoice_supplier_source) $sql .= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source;
137 137
 
138 138
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
139 139
         $resql = $this->db->query($sql);
@@ -159,12 +159,12 @@  discard block
 block discarded – undo
159 159
                 $this->fk_user = $obj->fk_user;
160 160
                 $this->fk_facture_line = $obj->fk_facture_line;
161 161
                 $this->fk_facture = $obj->fk_facture;
162
-                $this->fk_facture_source = $obj->fk_facture_source;		// Id avoir source
163
-                $this->ref_facture_source = $obj->ref_facture_source;	// Ref avoir source
162
+                $this->fk_facture_source = $obj->fk_facture_source; // Id avoir source
163
+                $this->ref_facture_source = $obj->ref_facture_source; // Ref avoir source
164 164
                 $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line;
165 165
                 $this->fk_invoice_supplier = $obj->fk_invoice_supplier;
166
-                $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source;		// Id avoir source
167
-                $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source;	// Ref avoir source
166
+                $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id avoir source
167
+                $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref avoir source
168 168
                 $this->description = $obj->description;
169 169
                 $this->datec = $this->db->jdate($obj->datec);
170 170
 
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
         }
180 180
         else
181 181
         {
182
-            $this->error=$this->db->error();
182
+            $this->error = $this->db->error();
183 183
             return -1;
184 184
         }
185 185
     }
@@ -196,52 +196,52 @@  discard block
 block discarded – undo
196 196
         global $conf, $langs;
197 197
 
198 198
         // Clean parameters
199
-        $this->amount_ht=price2num($this->amount_ht);
200
-        $this->amount_tva=price2num($this->amount_tva);
201
-        $this->amount_ttc=price2num($this->amount_ttc);
199
+        $this->amount_ht = price2num($this->amount_ht);
200
+        $this->amount_tva = price2num($this->amount_tva);
201
+        $this->amount_ttc = price2num($this->amount_ttc);
202 202
 
203
-        $this->tva_tx=price2num($this->tva_tx);
203
+        $this->tva_tx = price2num($this->tva_tx);
204 204
 
205
-        $this->multicurrency_amount_ht=price2num($this->multicurrency_amount_ht);
206
-        $this->multicurrency_amount_tva=price2num($this->multicurrency_amount_tva);
207
-        $this->multicurrency_amount_ttc=price2num($this->multicurrency_amount_ttc);
205
+        $this->multicurrency_amount_ht = price2num($this->multicurrency_amount_ht);
206
+        $this->multicurrency_amount_tva = price2num($this->multicurrency_amount_tva);
207
+        $this->multicurrency_amount_ttc = price2num($this->multicurrency_amount_ttc);
208 208
 
209
-        if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht=0;
210
-        if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva=0;
211
-        if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc=0;
209
+        if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht = 0;
210
+        if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva = 0;
211
+        if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc = 0;
212 212
 
213 213
         // Check parameters
214 214
         if (empty($this->description))
215 215
         {
216
-            $this->error='BadValueForPropertyDescription';
216
+            $this->error = 'BadValueForPropertyDescription';
217 217
             dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
218 218
             return -1;
219 219
         }
220 220
 
221 221
         // Insert request
222 222
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except";
223
-        $sql.= " (entity, datec, fk_soc, discount_type, fk_user, description,";
224
-        $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,";
225
-        $sql.= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,";
226
-        $sql.= " fk_facture_source, fk_invoice_supplier_source";
227
-        $sql.= ")";
228
-        $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type)?0:intval($this->discount_type)).", ".$user->id.", '".$this->db->escape($this->description)."',";
229
-        $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.",";
230
-        $sql.= " ".$this->multicurrency_amount_ht.", ".$this->multicurrency_amount_tva.", ".$this->multicurrency_amount_ttc.", ";
231
-        $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").",";
232
-        $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null");
233
-        $sql.= ")";
223
+        $sql .= " (entity, datec, fk_soc, discount_type, fk_user, description,";
224
+        $sql .= " amount_ht, amount_tva, amount_ttc, tva_tx,";
225
+        $sql .= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,";
226
+        $sql .= " fk_facture_source, fk_invoice_supplier_source";
227
+        $sql .= ")";
228
+        $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec != '' ? $this->datec : dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type) ? 0 : intval($this->discount_type)).", ".$user->id.", '".$this->db->escape($this->description)."',";
229
+        $sql .= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.",";
230
+        $sql .= " ".$this->multicurrency_amount_ht.", ".$this->multicurrency_amount_tva.", ".$this->multicurrency_amount_ttc.", ";
231
+        $sql .= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null").",";
232
+        $sql .= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'" : "null");
233
+        $sql .= ")";
234 234
 
235 235
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
236
-        $resql=$this->db->query($sql);
236
+        $resql = $this->db->query($sql);
237 237
         if ($resql)
238 238
         {
239
-            $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except");
239
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except");
240 240
             return $this->id;
241 241
         }
242 242
         else
243 243
         {
244
-            $this->error=$this->db->lasterror().' - sql='.$sql;
244
+            $this->error = $this->db->lasterror().' - sql='.$sql;
245 245
             return -1;
246 246
         }
247 247
     }
@@ -260,21 +260,21 @@  discard block
 block discarded – undo
260 260
         // Check if we can remove the discount
261 261
         if ($this->fk_facture_source)
262 262
         {
263
-            $sql="SELECT COUNT(rowid) as nb";
264
-            $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except";
265
-            $sql.=" WHERE (fk_facture_line IS NOT NULL";	// Not used as absolute simple discount
266
-            $sql.=" OR fk_facture IS NOT NULL)"; 			// Not used as credit note and not used as deposit
267
-            $sql.=" AND fk_facture_source = ".$this->fk_facture_source;
263
+            $sql = "SELECT COUNT(rowid) as nb";
264
+            $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except";
265
+            $sql .= " WHERE (fk_facture_line IS NOT NULL"; // Not used as absolute simple discount
266
+            $sql .= " OR fk_facture IS NOT NULL)"; // Not used as credit note and not used as deposit
267
+            $sql .= " AND fk_facture_source = ".$this->fk_facture_source;
268 268
             //$sql.=" AND rowid != ".$this->id;
269 269
 
270 270
             dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
271
-            $resql=$this->db->query($sql);
271
+            $resql = $this->db->query($sql);
272 272
             if ($resql)
273 273
             {
274 274
                 $obj = $this->db->fetch_object($resql);
275 275
                 if ($obj->nb > 0)
276 276
                 {
277
-                    $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
277
+                    $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
278 278
                     return -2;
279 279
                 }
280 280
             }
@@ -288,21 +288,21 @@  discard block
 block discarded – undo
288 288
         // Check if we can remove the discount
289 289
         if ($this->fk_invoice_supplier_source)
290 290
         {
291
-        	$sql="SELECT COUNT(rowid) as nb";
292
-        	$sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except";
293
-        	$sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL";	// Not used as absolute simple discount
294
-        	$sql.=" OR fk_invoice_supplier IS NOT NULL)"; 			// Not used as credit note and not used as deposit
295
-        	$sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
291
+        	$sql = "SELECT COUNT(rowid) as nb";
292
+        	$sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except";
293
+        	$sql .= " WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount
294
+        	$sql .= " OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit
295
+        	$sql .= " AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
296 296
         	//$sql.=" AND rowid != ".$this->id;
297 297
 
298 298
         	dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
299
-        	$resql=$this->db->query($sql);
299
+        	$resql = $this->db->query($sql);
300 300
         	if ($resql)
301 301
         	{
302 302
         		$obj = $this->db->fetch_object($resql);
303 303
         		if ($obj->nb > 0)
304 304
         		{
305
-        			$this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
305
+        			$this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
306 306
         			return -2;
307 307
         		}
308 308
         	}
@@ -317,27 +317,27 @@  discard block
 block discarded – undo
317 317
 
318 318
         // Delete but only if not used
319 319
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except ";
320
-        if ($this->fk_facture_source) $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source;	// Delete all lines of same serie
321
-        elseif ($this->fk_invoice_supplier_source) $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;	// Delete all lines of same serie
322
-        else $sql.= " WHERE rowid = ".$this->id;	// Delete only line
323
-        $sql.= " AND (fk_facture_line IS NULL";	// Not used as absolute simple discount
324
-        $sql.= " AND fk_facture IS NULL)";		// Not used as credit note and not used as deposit
325
-        $sql.= " AND (fk_invoice_supplier_line IS NULL";	// Not used as absolute simple discount
326
-        $sql.= " AND fk_invoice_supplier IS NULL)";		// Not used as credit note and not used as deposit
320
+        if ($this->fk_facture_source) $sql .= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie
321
+        elseif ($this->fk_invoice_supplier_source) $sql .= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie
322
+        else $sql .= " WHERE rowid = ".$this->id; // Delete only line
323
+        $sql .= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount
324
+        $sql .= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit
325
+        $sql .= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount
326
+        $sql .= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit
327 327
 
328 328
         dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG);
329
-        $result=$this->db->query($sql);
329
+        $result = $this->db->query($sql);
330 330
         if ($result)
331 331
         {
332 332
             // If source of discount was a credit note or deposit, we change source statut.
333 333
             if ($this->fk_facture_source)
334 334
             {
335 335
                 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
336
-                $sql.=" set paye=0, fk_statut=1";
337
-                $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source;
336
+                $sql .= " set paye=0, fk_statut=1";
337
+                $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source;
338 338
 
339 339
                 dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
340
-                $result=$this->db->query($sql);
340
+                $result = $this->db->query($sql);
341 341
                 if ($result)
342 342
                 {
343 343
                     $this->db->commit();
@@ -345,19 +345,19 @@  discard block
 block discarded – undo
345 345
                 }
346 346
                 else
347 347
                 {
348
-                    $this->error=$this->db->lasterror();
348
+                    $this->error = $this->db->lasterror();
349 349
                     $this->db->rollback();
350 350
                     return -1;
351 351
                 }
352 352
             }
353
-            elseif($this->fk_invoice_supplier_source) {
353
+            elseif ($this->fk_invoice_supplier_source) {
354 354
 
355 355
             	$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
356
-            	$sql.=" set paye=0, fk_statut=1";
357
-            	$sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source;
356
+            	$sql .= " set paye=0, fk_statut=1";
357
+            	$sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source;
358 358
 
359 359
             	dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
360
-            	$result=$this->db->query($sql);
360
+            	$result = $this->db->query($sql);
361 361
             	if ($result)
362 362
             	{
363 363
             		$this->db->commit();
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
             	}
366 366
             	else
367 367
             	{
368
-            		$this->error=$this->db->lasterror();
368
+            		$this->error = $this->db->lasterror();
369 369
             		$this->db->rollback();
370 370
             		return -1;
371 371
             	}
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
         }
379 379
         else
380 380
         {
381
-            $this->error=$this->db->lasterror();
381
+            $this->error = $this->db->lasterror();
382 382
             $this->db->rollback();
383 383
             return -1;
384 384
         }
@@ -396,47 +396,47 @@  discard block
 block discarded – undo
396 396
      *	@param		int		$rowidinvoice	Invoice id (To use discount as a credit note to reduc payment of invoice)
397 397
      *	@return		int						<0 if KO, >0 if OK
398 398
      */
399
-    function link_to_invoice($rowidline,$rowidinvoice)
399
+    function link_to_invoice($rowidline, $rowidinvoice)
400 400
     {
401 401
         // phpcs:enable
402 402
         // Check parameters
403
-        if (! $rowidline && ! $rowidinvoice)
403
+        if (!$rowidline && !$rowidinvoice)
404 404
         {
405
-            $this->error='ErrorBadParameters';
405
+            $this->error = 'ErrorBadParameters';
406 406
             return -1;
407 407
         }
408 408
         if ($rowidline && $rowidinvoice)
409 409
         {
410
-            $this->error='ErrorBadParameters';
410
+            $this->error = 'ErrorBadParameters';
411 411
             return -2;
412 412
         }
413 413
 
414
-        $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
415
-        if(! empty($this->discount_type)) {
416
-        	if ($rowidline)    $sql.=" SET fk_invoice_supplier_line = ".$rowidline;
417
-        	if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice;
414
+        $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
415
+        if (!empty($this->discount_type)) {
416
+        	if ($rowidline)    $sql .= " SET fk_invoice_supplier_line = ".$rowidline;
417
+        	if ($rowidinvoice) $sql .= " SET fk_invoice_supplier = ".$rowidinvoice;
418 418
         } else {
419
-        	if ($rowidline)    $sql.=" SET fk_facture_line = ".$rowidline;
420
-        	if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice;
419
+        	if ($rowidline)    $sql .= " SET fk_facture_line = ".$rowidline;
420
+        	if ($rowidinvoice) $sql .= " SET fk_facture = ".$rowidinvoice;
421 421
         }
422
-        $sql.=" WHERE rowid = ".$this->id;
422
+        $sql .= " WHERE rowid = ".$this->id;
423 423
 
424 424
         dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG);
425 425
         $resql = $this->db->query($sql);
426 426
         if ($resql)
427 427
         {
428
-        	if(! empty($this->discount_type)) {
429
-        		$this->fk_invoice_supplier_line=$rowidline;
430
-        		$this->fk_invoice_supplier=$rowidinvoice;
428
+        	if (!empty($this->discount_type)) {
429
+        		$this->fk_invoice_supplier_line = $rowidline;
430
+        		$this->fk_invoice_supplier = $rowidinvoice;
431 431
         	} else {
432
-        		$this->fk_facture_line=$rowidline;
433
-        		$this->fk_facture=$rowidinvoice;
432
+        		$this->fk_facture_line = $rowidline;
433
+        		$this->fk_facture = $rowidinvoice;
434 434
         	}
435 435
             return 1;
436 436
         }
437 437
         else
438 438
         {
439
-            $this->error=$this->db->error();
439
+            $this->error = $this->db->error();
440 440
             return -3;
441 441
         }
442 442
     }
@@ -452,13 +452,13 @@  discard block
 block discarded – undo
452 452
     function unlink_invoice()
453 453
     {
454 454
         // phpcs:enable
455
-        $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
456
-		if(! empty($this->discount_type)) {
457
-       		$sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
455
+        $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
456
+		if (!empty($this->discount_type)) {
457
+       		$sql .= " SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
458 458
 		} else {
459
-			$sql.=" SET fk_facture_line = NULL, fk_facture = NULL";
459
+			$sql .= " SET fk_facture_line = NULL, fk_facture = NULL";
460 460
 		}
461
-        $sql.=" WHERE rowid = ".$this->id;
461
+        $sql .= " WHERE rowid = ".$this->id;
462 462
 
463 463
         dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG);
464 464
         $resql = $this->db->query($sql);
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
         }
469 469
         else
470 470
         {
471
-            $this->error=$this->db->error();
471
+            $this->error = $this->db->error();
472 472
             return -3;
473 473
         }
474 474
     }
@@ -484,27 +484,27 @@  discard block
 block discarded – undo
484 484
      *  @param      int			$discount_type  0 => customer discount, 1 => supplier discount
485 485
      * 	@return		int						<0 if KO, amount otherwise
486 486
      */
487
-    function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $discount_type=0)
487
+    function getAvailableDiscounts($company = '', $user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
488 488
     {
489 489
     	global $conf;
490 490
 
491
-        $sql  = "SELECT SUM(rc.amount_ttc) as amount";
491
+        $sql = "SELECT SUM(rc.amount_ttc) as amount";
492 492
         //$sql  = "SELECT rc.amount_ttc as amount";
493
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
494
-        $sql.= " WHERE rc.entity = " . $conf->entity;
495
-        $sql.= " AND rc.discount_type=".intval($discount_type);
496
-        if (! empty($discount_type)) {
497
-        	$sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
493
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
494
+        $sql .= " WHERE rc.entity = ".$conf->entity;
495
+        $sql .= " AND rc.discount_type=".intval($discount_type);
496
+        if (!empty($discount_type)) {
497
+        	$sql .= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
498 498
         } else {
499
-        	$sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
499
+        	$sql .= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
500 500
         }
501
-        if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id;
502
-        if (is_object($user))    $sql.= " AND rc.fk_user = ".$user->id;
503
-        if ($filter)   $sql.=' AND ('.$filter.')';
504
-        if ($maxvalue) $sql.=' AND rc.amount_ttc <= '.price2num($maxvalue);
501
+        if (is_object($company)) $sql .= " AND rc.fk_soc = ".$company->id;
502
+        if (is_object($user))    $sql .= " AND rc.fk_user = ".$user->id;
503
+        if ($filter)   $sql .= ' AND ('.$filter.')';
504
+        if ($maxvalue) $sql .= ' AND rc.amount_ttc <= '.price2num($maxvalue);
505 505
 
506 506
         dol_syslog(get_class($this)."::getAvailableDiscounts", LOG_DEBUG);
507
-        $resql=$this->db->query($sql);
507
+        $resql = $this->db->query($sql);
508 508
         if ($resql)
509 509
         {
510 510
             $obj = $this->db->fetch_object($resql);
@@ -527,32 +527,32 @@  discard block
 block discarded – undo
527 527
 	 *  @param 		int 		    $multicurrency 	Return multicurrency_amount instead of amount
528 528
      *	@return		int				     			<0 if KO, Sum of credit notes and deposits amount otherwise
529 529
      */
530
-    function getSumDepositsUsed($invoice, $multicurrency=0)
530
+    function getSumDepositsUsed($invoice, $multicurrency = 0)
531 531
     {
532 532
         dol_syslog(get_class($this)."::getSumDepositsUsed", LOG_DEBUG);
533 533
 
534 534
         if ($invoice->element == 'facture' || $invoice->element == 'invoice')
535 535
         {
536 536
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
537
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
538
-            $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
539
-            $sql.= ' AND f.type = 3';
537
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
538
+            $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
539
+            $sql .= ' AND f.type = 3';
540 540
         }
541 541
         else if ($invoice->element == 'invoice_supplier')
542 542
         {
543 543
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
544
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
545
-            $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
546
-            $sql.= ' AND f.type = 3';
544
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
545
+            $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
546
+            $sql .= ' AND f.type = 3';
547 547
         }
548 548
         else
549 549
         {
550
-            $this->error=get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter";
550
+            $this->error = get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter";
551 551
             dol_print_error($this->error);
552 552
             return -1;
553 553
         }
554 554
 
555
-        $resql=$this->db->query($sql);
555
+        $resql = $this->db->query($sql);
556 556
         if ($resql)
557 557
         {
558 558
             $obj = $this->db->fetch_object($resql);
@@ -573,32 +573,32 @@  discard block
 block discarded – undo
573 573
 	 *	@param		int			      $multicurrency	Return multicurrency_amount instead of amount
574 574
      *	@return		int					        		<0 if KO, Sum of credit notes and excess received amount otherwise
575 575
      */
576
-    function getSumCreditNotesUsed($invoice, $multicurrency=0)
576
+    function getSumCreditNotesUsed($invoice, $multicurrency = 0)
577 577
     {
578 578
         dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG);
579 579
 
580 580
         if ($invoice->element == 'facture' || $invoice->element == 'invoice')
581 581
         {
582 582
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
583
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
584
-            $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
585
-            $sql.= ' AND (f.type = 2 OR f.type = 0)';	// Find discount coming from credit note or excess received
583
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
584
+            $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
585
+            $sql .= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received
586 586
         }
587 587
         else if ($invoice->element == 'invoice_supplier')
588 588
         {
589 589
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
590
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
591
-            $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
592
-            $sql.= ' AND (f.type = 2 OR f.type = 0)';	// Find discount coming from credit note or excess paid
590
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
591
+            $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
592
+            $sql .= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess paid
593 593
         }
594 594
         else
595 595
         {
596
-            $this->error=get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
596
+            $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
597 597
             dol_print_error($this->error);
598 598
             return -1;
599 599
         }
600 600
 
601
-        $resql=$this->db->query($sql);
601
+        $resql = $this->db->query($sql);
602 602
         if ($resql)
603 603
         {
604 604
             $obj = $this->db->fetch_object($resql);
@@ -619,33 +619,33 @@  discard block
 block discarded – undo
619 619
      *	@param		string	$option			Where to link to ('invoice' or 'discount')
620 620
      *	@return		string					String with URL
621 621
      */
622
-    function getNomUrl($withpicto,$option='invoice')
622
+    function getNomUrl($withpicto, $option = 'invoice')
623 623
     {
624 624
         global $langs;
625 625
 
626
-        $result='';
626
+        $result = '';
627 627
 
628 628
         if ($option == 'invoice') {
629
-            $facid=! empty($this->discount_type)?$this->fk_invoice_supplier_source:$this->fk_facture_source;
630
-            $link=! empty($this->discount_type)?'/fourn/facture/card.php':'/compta/facture/card.php';
631
-            $label=$langs->trans("ShowDiscount").': '.$this->ref_facture_source;
629
+            $facid = !empty($this->discount_type) ? $this->fk_invoice_supplier_source : $this->fk_facture_source;
630
+            $link = !empty($this->discount_type) ? '/fourn/facture/card.php' : '/compta/facture/card.php';
631
+            $label = $langs->trans("ShowDiscount").': '.$this->ref_facture_source;
632 632
             $link = '<a href="'.DOL_URL_ROOT.$link.'?facid='.$facid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
633
-            $linkend='</a>';
634
-            $ref=! empty($this->discount_type)?$this->ref_invoice_supplier_source:$this->ref_facture_source;
635
-            $picto='bill';
633
+            $linkend = '</a>';
634
+            $ref = !empty($this->discount_type) ? $this->ref_invoice_supplier_source : $this->ref_facture_source;
635
+            $picto = 'bill';
636 636
         }
637 637
         if ($option == 'discount') {
638
-            $label=$langs->trans("Discount");
638
+            $label = $langs->trans("Discount");
639 639
             $link = '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$this->fk_soc.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
640
-            $linkend='</a>';
641
-            $ref=$langs->trans("Discount");
642
-            $picto='generic';
640
+            $linkend = '</a>';
641
+            $ref = $langs->trans("Discount");
642
+            $picto = 'generic';
643 643
         }
644 644
 
645 645
 
646
-        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
647
-        if ($withpicto && $withpicto != 2) $result.=' ';
648
-        $result.=$link.$ref.$linkend;
646
+        if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
647
+        if ($withpicto && $withpicto != 2) $result .= ' ';
648
+        $result .= $link.$ref.$linkend;
649 649
         return $result;
650 650
     }
651 651
 
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 	 */
660 660
 	function initAsSpecimen()
661 661
 	{
662
-		global $user,$langs,$conf;
662
+		global $user, $langs, $conf;
663 663
 
664 664
 		$this->fk_soc         = 1;
665 665
 		$this->amount_ht      = 10;
Please login to merge, or discard this patch.
Braces   +88 added lines, -59 removed lines patch added patch discarded remove patch
@@ -131,9 +131,15 @@  discard block
 block discarded – undo
131 131
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid";
132 132
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid";
133 133
         $sql.= " WHERE sr.entity = " . $conf->entity;
134
-        if ($rowid) $sql.= " AND sr.rowid=".$rowid;
135
-        if ($fk_facture_source) $sql.= " AND sr.fk_facture_source=".$fk_facture_source;
136
-        if ($fk_invoice_supplier_source) $sql.= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source;
134
+        if ($rowid) {
135
+            $sql.= " AND sr.rowid=".$rowid;
136
+        }
137
+        if ($fk_facture_source) {
138
+            $sql.= " AND sr.fk_facture_source=".$fk_facture_source;
139
+        }
140
+        if ($fk_invoice_supplier_source) {
141
+            $sql.= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source;
142
+        }
137 143
 
138 144
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
139 145
         $resql = $this->db->query($sql);
@@ -170,14 +176,12 @@  discard block
 block discarded – undo
170 176
 
171 177
                 $this->db->free($resql);
172 178
                 return 1;
173
-            }
174
-            else
179
+            } else
175 180
             {
176 181
                 $this->db->free($resql);
177 182
                 return 0;
178 183
             }
179
-        }
180
-        else
184
+        } else
181 185
         {
182 186
             $this->error=$this->db->error();
183 187
             return -1;
@@ -206,9 +210,15 @@  discard block
 block discarded – undo
206 210
         $this->multicurrency_amount_tva=price2num($this->multicurrency_amount_tva);
207 211
         $this->multicurrency_amount_ttc=price2num($this->multicurrency_amount_ttc);
208 212
 
209
-        if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht=0;
210
-        if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva=0;
211
-        if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc=0;
213
+        if (empty($this->multicurrency_amount_ht)) {
214
+            $this->multicurrency_amount_ht=0;
215
+        }
216
+        if (empty($this->multicurrency_amount_tva)) {
217
+            $this->multicurrency_amount_tva=0;
218
+        }
219
+        if (empty($this->multicurrency_amount_ttc)) {
220
+            $this->multicurrency_amount_ttc=0;
221
+        }
212 222
 
213 223
         // Check parameters
214 224
         if (empty($this->description))
@@ -238,8 +248,7 @@  discard block
 block discarded – undo
238 248
         {
239 249
             $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except");
240 250
             return $this->id;
241
-        }
242
-        else
251
+        } else
243 252
         {
244 253
             $this->error=$this->db->lasterror().' - sql='.$sql;
245 254
             return -1;
@@ -277,8 +286,7 @@  discard block
 block discarded – undo
277 286
                     $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
278 287
                     return -2;
279 288
                 }
280
-            }
281
-            else
289
+            } else
282 290
             {
283 291
                 dol_print_error($this->db);
284 292
                 return -1;
@@ -305,8 +313,7 @@  discard block
 block discarded – undo
305 313
         			$this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
306 314
         			return -2;
307 315
         		}
308
-        	}
309
-        	else
316
+        	} else
310 317
         	{
311 318
         		dol_print_error($this->db);
312 319
         		return -1;
@@ -317,9 +324,18 @@  discard block
 block discarded – undo
317 324
 
318 325
         // Delete but only if not used
319 326
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except ";
320
-        if ($this->fk_facture_source) $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source;	// Delete all lines of same serie
321
-        elseif ($this->fk_invoice_supplier_source) $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;	// Delete all lines of same serie
322
-        else $sql.= " WHERE rowid = ".$this->id;	// Delete only line
327
+        if ($this->fk_facture_source) {
328
+            $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source;
329
+        }
330
+        // Delete all lines of same serie
331
+        elseif ($this->fk_invoice_supplier_source) {
332
+            $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
333
+        }
334
+        // Delete all lines of same serie
335
+        else {
336
+            $sql.= " WHERE rowid = ".$this->id;
337
+        }
338
+        // Delete only line
323 339
         $sql.= " AND (fk_facture_line IS NULL";	// Not used as absolute simple discount
324 340
         $sql.= " AND fk_facture IS NULL)";		// Not used as credit note and not used as deposit
325 341
         $sql.= " AND (fk_invoice_supplier_line IS NULL";	// Not used as absolute simple discount
@@ -342,15 +358,13 @@  discard block
 block discarded – undo
342 358
                 {
343 359
                     $this->db->commit();
344 360
                     return 1;
345
-                }
346
-                else
361
+                } else
347 362
                 {
348 363
                     $this->error=$this->db->lasterror();
349 364
                     $this->db->rollback();
350 365
                     return -1;
351 366
                 }
352
-            }
353
-            elseif($this->fk_invoice_supplier_source) {
367
+            } elseif($this->fk_invoice_supplier_source) {
354 368
 
355 369
             	$sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
356 370
             	$sql.=" set paye=0, fk_statut=1";
@@ -362,21 +376,18 @@  discard block
 block discarded – undo
362 376
             	{
363 377
             		$this->db->commit();
364 378
             		return 1;
365
-            	}
366
-            	else
379
+            	} else
367 380
             	{
368 381
             		$this->error=$this->db->lasterror();
369 382
             		$this->db->rollback();
370 383
             		return -1;
371 384
             	}
372
-            }
373
-            else
385
+            } else
374 386
             {
375 387
                 $this->db->commit();
376 388
                 return 1;
377 389
             }
378
-        }
379
-        else
390
+        } else
380 391
         {
381 392
             $this->error=$this->db->lasterror();
382 393
             $this->db->rollback();
@@ -413,11 +424,19 @@  discard block
 block discarded – undo
413 424
 
414 425
         $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
415 426
         if(! empty($this->discount_type)) {
416
-        	if ($rowidline)    $sql.=" SET fk_invoice_supplier_line = ".$rowidline;
417
-        	if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice;
427
+        	if ($rowidline) {
428
+        	    $sql.=" SET fk_invoice_supplier_line = ".$rowidline;
429
+        	}
430
+        	if ($rowidinvoice) {
431
+        	    $sql.=" SET fk_invoice_supplier = ".$rowidinvoice;
432
+        	}
418 433
         } else {
419
-        	if ($rowidline)    $sql.=" SET fk_facture_line = ".$rowidline;
420
-        	if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice;
434
+        	if ($rowidline) {
435
+        	    $sql.=" SET fk_facture_line = ".$rowidline;
436
+        	}
437
+        	if ($rowidinvoice) {
438
+        	    $sql.=" SET fk_facture = ".$rowidinvoice;
439
+        	}
421 440
         }
422 441
         $sql.=" WHERE rowid = ".$this->id;
423 442
 
@@ -433,8 +452,7 @@  discard block
 block discarded – undo
433 452
         		$this->fk_facture=$rowidinvoice;
434 453
         	}
435 454
             return 1;
436
-        }
437
-        else
455
+        } else
438 456
         {
439 457
             $this->error=$this->db->error();
440 458
             return -3;
@@ -465,8 +483,7 @@  discard block
 block discarded – undo
465 483
         if ($resql)
466 484
         {
467 485
             return 1;
468
-        }
469
-        else
486
+        } else
470 487
         {
471 488
             $this->error=$this->db->error();
472 489
             return -3;
@@ -498,10 +515,18 @@  discard block
 block discarded – undo
498 515
         } else {
499 516
         	$sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
500 517
         }
501
-        if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id;
502
-        if (is_object($user))    $sql.= " AND rc.fk_user = ".$user->id;
503
-        if ($filter)   $sql.=' AND ('.$filter.')';
504
-        if ($maxvalue) $sql.=' AND rc.amount_ttc <= '.price2num($maxvalue);
518
+        if (is_object($company)) {
519
+            $sql.= " AND rc.fk_soc = ".$company->id;
520
+        }
521
+        if (is_object($user)) {
522
+            $sql.= " AND rc.fk_user = ".$user->id;
523
+        }
524
+        if ($filter) {
525
+            $sql.=' AND ('.$filter.')';
526
+        }
527
+        if ($maxvalue) {
528
+            $sql.=' AND rc.amount_ttc <= '.price2num($maxvalue);
529
+        }
505 530
 
506 531
         dol_syslog(get_class($this)."::getAvailableDiscounts", LOG_DEBUG);
507 532
         $resql=$this->db->query($sql);
@@ -537,15 +562,13 @@  discard block
 block discarded – undo
537 562
             $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
538 563
             $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
539 564
             $sql.= ' AND f.type = 3';
540
-        }
541
-        else if ($invoice->element == 'invoice_supplier')
565
+        } else if ($invoice->element == 'invoice_supplier')
542 566
         {
543 567
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
544 568
             $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
545 569
             $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
546 570
             $sql.= ' AND f.type = 3';
547
-        }
548
-        else
571
+        } else
549 572
         {
550 573
             $this->error=get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter";
551 574
             dol_print_error($this->error);
@@ -556,10 +579,12 @@  discard block
 block discarded – undo
556 579
         if ($resql)
557 580
         {
558 581
             $obj = $this->db->fetch_object($resql);
559
-            if ($multicurrency) return $obj->multicurrency_amount;
560
-			else return $obj->amount;
561
-        }
562
-        else
582
+            if ($multicurrency) {
583
+                return $obj->multicurrency_amount;
584
+            } else {
585
+			    return $obj->amount;
586
+			}
587
+        } else
563 588
         {
564 589
             $this->error = $this->db->lasterror();
565 590
             return -1;
@@ -583,15 +608,13 @@  discard block
 block discarded – undo
583 608
             $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
584 609
             $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
585 610
             $sql.= ' AND (f.type = 2 OR f.type = 0)';	// Find discount coming from credit note or excess received
586
-        }
587
-        else if ($invoice->element == 'invoice_supplier')
611
+        } else if ($invoice->element == 'invoice_supplier')
588 612
         {
589 613
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
590 614
             $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
591 615
             $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
592 616
             $sql.= ' AND (f.type = 2 OR f.type = 0)';	// Find discount coming from credit note or excess paid
593
-        }
594
-        else
617
+        } else
595 618
         {
596 619
             $this->error=get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
597 620
             dol_print_error($this->error);
@@ -602,10 +625,12 @@  discard block
 block discarded – undo
602 625
         if ($resql)
603 626
         {
604 627
             $obj = $this->db->fetch_object($resql);
605
-            if ($multicurrency) return $obj->multicurrency_amount;
606
-			else return $obj->amount;
607
-        }
608
-        else
628
+            if ($multicurrency) {
629
+                return $obj->multicurrency_amount;
630
+            } else {
631
+			    return $obj->amount;
632
+			}
633
+        } else
609 634
         {
610 635
             $this->error = $this->db->lasterror();
611 636
             return -1;
@@ -643,8 +668,12 @@  discard block
 block discarded – undo
643 668
         }
644 669
 
645 670
 
646
-        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
647
-        if ($withpicto && $withpicto != 2) $result.=' ';
671
+        if ($withpicto) {
672
+            $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
673
+        }
674
+        if ($withpicto && $withpicto != 2) {
675
+            $result.=' ';
676
+        }
648 677
         $result.=$link.$ref.$linkend;
649 678
         return $result;
650 679
     }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/openid.class.php 3 patches
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -30,8 +30,8 @@  discard block
 block discarded – undo
30 30
     var $URLs = array();
31 31
     var $error = array();
32 32
     var $fields = array(
33
-		'required' => array(),
34
-		'optional' => array(),
33
+        'required' => array(),
34
+        'optional' => array(),
35 35
     );
36 36
 
37 37
     /**
@@ -399,8 +399,8 @@  discard block
 block discarded – undo
399 399
         // phpcs:enable
400 400
         global $conf;
401 401
 
402
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
403
-		if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
402
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
403
+        if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
404 404
 
405 405
         $response = getURLContent($url);
406 406
 
@@ -475,9 +475,9 @@  discard block
 block discarded – undo
475 475
     {
476 476
         // phpcs:enable
477 477
         $params = array(
478
-			'openid.assoc_handle' => urlencode($_GET['openid_assoc_handle']),
479
-			'openid.signed' => urlencode($_GET['openid_signed']),
480
-			'openid.sig' => urlencode($_GET['openid_sig'])
478
+            'openid.assoc_handle' => urlencode($_GET['openid_assoc_handle']),
479
+            'openid.signed' => urlencode($_GET['openid_signed']),
480
+            'openid.sig' => urlencode($_GET['openid_sig'])
481 481
         );
482 482
         // Send only required parameters to confirm validity
483 483
         $arr_signed = explode(",",str_replace('sreg.','sreg_',$_GET['openid_signed']));
@@ -520,16 +520,16 @@  discard block
 block discarded – undo
520 520
      */
521 521
     function sendDiscoveryRequestToGetXRDS($url='')
522 522
     {
523
-    	global $conf;
523
+        global $conf;
524 524
 
525
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
526
-		if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
525
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
526
+        if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
527 527
 
528
-		dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS get XRDS');
528
+        dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS get XRDS');
529 529
 
530
-		$addheaders=array('Accept: application/xrds+xml');
530
+        $addheaders=array('Accept: application/xrds+xml');
531 531
         $response = getURLContent($url, 'GET', '', 1, $addheaders);
532
-		/* response should like this:
532
+        /* response should like this:
533 533
 		<?xml version="1.0" encoding="UTF-8"?>
534 534
 		<xrds:XRDS xmlns:xrds="xri://$xrds" xmlns="xri://$xrd*($v*2.0)">
535 535
 		<XRD>
@@ -542,12 +542,12 @@  discard block
 block discarded – undo
542 542
 		</XRD>
543 543
 		</xrds:XRDS>
544 544
 		*/
545
-		$content=$response['content'];
545
+        $content=$response['content'];
546 546
 
547 547
         $server='';
548 548
         if (preg_match('/'.preg_quote('<URI>','/').'(.*)'.preg_quote('</URI>','/').'/is', $content, $reg))
549 549
         {
550
-        	$server=$reg[1];
550
+            $server=$reg[1];
551 551
         }
552 552
 
553 553
         if (empty($server))
@@ -556,10 +556,10 @@  discard block
 block discarded – undo
556 556
             return false;
557 557
         }
558 558
         else
559
-       {
560
-       		dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS found endpoint = '.$server);
561
-        	$this->SetOpenIDServer($server);
562
-        	return $server;
563
-	    }
559
+        {
560
+                dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS found endpoint = '.$server);
561
+            $this->SetOpenIDServer($server);
562
+            return $server;
563
+        }
564 564
     }
565 565
 }
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
     {
186 186
         // phpcs:enable
187 187
         $e = $this->error;
188
-        return array('code'=>$e[0],'description'=>$e[1]);
188
+        return array('code'=>$e[0], 'description'=>$e[1]);
189 189
     }
190 190
 
191 191
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -200,10 +200,10 @@  discard block
 block discarded – undo
200 200
     {
201 201
         // phpcs:enable
202 202
         $errs['OPENID_NOSERVERSFOUND'] = 'Cannot find OpenID Server TAG on Identity page.';
203
-        if ($desc == null){
203
+        if ($desc == null) {
204 204
             $desc = $errs[$code];
205 205
         }
206
-        $this->error = array($code,$desc);
206
+        $this->error = array($code, $desc);
207 207
     }
208 208
 
209 209
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
     {
236 236
         $r = array();
237 237
         $response = explode("\n", $response);
238
-        foreach($response as $line) {
238
+        foreach ($response as $line) {
239 239
             $line = trim($line);
240 240
             if ($line != "") {
241 241
                 list($key, $value) = explode(":", $line, 2);
@@ -263,13 +263,13 @@  discard block
 block discarded – undo
263 263
         if (!isset($u['path']) || ($u['path'] == '/')) {
264 264
             $u['path'] = '';
265 265
         }
266
-        if(substr($u['path'],-1,1) == '/'){
267
-            $u['path'] = substr($u['path'], 0, strlen($u['path'])-1);
266
+        if (substr($u['path'], -1, 1) == '/') {
267
+            $u['path'] = substr($u['path'], 0, strlen($u['path']) - 1);
268 268
         }
269
-        if (isset($u['query'])){ // If there is a query string, then use identity as is
270
-            return $u['host'] . $u['path'] . '?' . $u['query'];
271
-        }else{
272
-            return $u['host'] . $u['path'];
269
+        if (isset($u['query'])) { // If there is a query string, then use identity as is
270
+            return $u['host'].$u['path'].'?'.$u['query'];
271
+        } else {
272
+            return $u['host'].$u['path'];
273 273
         }
274 274
     }
275 275
 
@@ -282,12 +282,12 @@  discard block
 block discarded – undo
282 282
     function array2url($arr)
283 283
     {
284 284
         // converts associated array to URL Query String
285
-        if (!is_array($arr)){
285
+        if (!is_array($arr)) {
286 286
             return false;
287 287
         }
288 288
         $query = '';
289
-        foreach($arr as $key => $value){
290
-            $query .= $key . "=" . $value . "&";
289
+        foreach ($arr as $key => $value) {
290
+            $query .= $key."=".$value."&";
291 291
         }
292 292
         return $query;
293 293
     }
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
      * @param string	$params		Params
302 302
      * @return boolean|unknown
303 303
      */
304
-    function FSOCK_Request($url, $method="GET", $params = "")
304
+    function FSOCK_Request($url, $method = "GET", $params = "")
305 305
     {
306 306
         // phpcs:enable
307 307
         $fp = fsockopen("ssl://www.myopenid.com", 443, $errno, $errstr, 3); // Connection timeout is 3 seconds
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             $this->ErrorStore('OPENID_SOCKETERROR', $errstr);
310 310
             return false;
311 311
         } else {
312
-            $request = $method . " /server HTTP/1.0\r\n";
312
+            $request = $method." /server HTTP/1.0\r\n";
313 313
             $request .= "User-Agent: Dolibarr\r\n";
314 314
             $request .= "Connection: close\r\n\r\n";
315 315
             fwrite($fp, $request);
@@ -335,13 +335,13 @@  discard block
 block discarded – undo
335 335
      * @param 	string	$params		Params
336 336
      * @return string
337 337
      */
338
-    function CURL_Request($url, $method="GET", $params = "")
338
+    function CURL_Request($url, $method = "GET", $params = "")
339 339
     {
340 340
         // phpcs:enable
341 341
         // Remember, SSL MUST BE SUPPORTED
342 342
         if (is_array($params)) $params = $this->array2url($params);
343 343
 
344
-        $curl = curl_init($url . ($method == "GET" && $params != "" ? "?" . $params : ""));
344
+        $curl = curl_init($url.($method == "GET" && $params != "" ? "?".$params : ""));
345 345
         @curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
346 346
         curl_setopt($curl, CURLOPT_HEADER, false);
347 347
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
@@ -351,9 +351,9 @@  discard block
 block discarded – undo
351 351
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
352 352
         $response = curl_exec($curl);
353 353
 
354
-        if (curl_errno($curl) == 0){
354
+        if (curl_errno($curl) == 0) {
355 355
             $response;
356
-        }else{
356
+        } else {
357 357
             $this->ErrorStore('OPENID_CURL', curl_error($curl));
358 358
         }
359 359
         return $response;
@@ -394,13 +394,13 @@  discard block
 block discarded – undo
394 394
      * @param	string	$url	Url to found endpoint
395 395
      * @return 	string			Endpoint
396 396
      */
397
-    function GetOpenIDServer($url='')
397
+    function GetOpenIDServer($url = '')
398 398
     {
399 399
         // phpcs:enable
400 400
         global $conf;
401 401
 
402 402
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
403
-		if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
403
+		if (empty($url)) $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL;
404 404
 
405 405
         $response = getURLContent($url);
406 406
 
@@ -434,13 +434,13 @@  discard block
 block discarded – undo
434 434
 
435 435
         if (isset($this->fields['required'])
436 436
         && (count($this->fields['required']) > 0)) {
437
-            $params['openid.sreg.required'] = implode(',',$this->fields['required']);
437
+            $params['openid.sreg.required'] = implode(',', $this->fields['required']);
438 438
         }
439 439
         if (isset($this->fields['optional'])
440 440
         && (count($this->fields['optional']) > 0)) {
441
-            $params['openid.sreg.optional'] = implode(',',$this->fields['optional']);
441
+            $params['openid.sreg.optional'] = implode(',', $this->fields['optional']);
442 442
         }
443
-        return $this->URLs['openid_server'] . "?". $this->array2url($params);
443
+        return $this->URLs['openid_server']."?".$this->array2url($params);
444 444
     }
445 445
 
446 446
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
         }
462 462
         else
463 463
         {	// Default Header Redirect
464
-            header('Location: ' . $redirect_to);
464
+            header('Location: '.$redirect_to);
465 465
         }
466 466
     }
467 467
 
@@ -480,14 +480,14 @@  discard block
 block discarded – undo
480 480
 			'openid.sig' => urlencode($_GET['openid_sig'])
481 481
         );
482 482
         // Send only required parameters to confirm validity
483
-        $arr_signed = explode(",",str_replace('sreg.','sreg_',$_GET['openid_signed']));
483
+        $arr_signed = explode(",", str_replace('sreg.', 'sreg_', $_GET['openid_signed']));
484 484
         $num = count($arr_signed);
485 485
         for ($i = 0; $i < $num; $i++)
486 486
         {
487
-            $s = str_replace('sreg_','sreg.', $arr_signed[$i]);
488
-            $c = $_GET['openid_' . $arr_signed[$i]];
487
+            $s = str_replace('sreg_', 'sreg.', $arr_signed[$i]);
488
+            $c = $_GET['openid_'.$arr_signed[$i]];
489 489
             // if ($c != ""){
490
-            $params['openid.' . $s] = urlencode($c);
490
+            $params['openid.'.$s] = urlencode($c);
491 491
             // }
492 492
         }
493 493
         $params['openid.mode'] = "check_authentication";
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
         {
498 498
             return false;
499 499
         }
500
-        $response = $this->CURL_Request($openid_server,'POST',$params);
500
+        $response = $this->CURL_Request($openid_server, 'POST', $params);
501 501
         $data = $this->splitResponse($response);
502 502
         if ($data['is_valid'] == "true")
503 503
         {
@@ -518,16 +518,16 @@  discard block
 block discarded – undo
518 518
      * @param	string	$url	Url of endpoint to request
519 519
      * @return 	string			First endpoint OpenID server found. False if it failed to found.
520 520
      */
521
-    function sendDiscoveryRequestToGetXRDS($url='')
521
+    function sendDiscoveryRequestToGetXRDS($url = '')
522 522
     {
523 523
     	global $conf;
524 524
 
525 525
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
526
-		if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
526
+		if (empty($url)) $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL;
527 527
 
528 528
 		dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS get XRDS');
529 529
 
530
-		$addheaders=array('Accept: application/xrds+xml');
530
+		$addheaders = array('Accept: application/xrds+xml');
531 531
         $response = getURLContent($url, 'GET', '', 1, $addheaders);
532 532
 		/* response should like this:
533 533
 		<?xml version="1.0" encoding="UTF-8"?>
@@ -542,12 +542,12 @@  discard block
 block discarded – undo
542 542
 		</XRD>
543 543
 		</xrds:XRDS>
544 544
 		*/
545
-		$content=$response['content'];
545
+		$content = $response['content'];
546 546
 
547
-        $server='';
548
-        if (preg_match('/'.preg_quote('<URI>','/').'(.*)'.preg_quote('</URI>','/').'/is', $content, $reg))
547
+        $server = '';
548
+        if (preg_match('/'.preg_quote('<URI>', '/').'(.*)'.preg_quote('</URI>', '/').'/is', $content, $reg))
549 549
         {
550
-        	$server=$reg[1];
550
+        	$server = $reg[1];
551 551
         }
552 552
 
553 553
         if (empty($server))
Please login to merge, or discard this patch.
Braces   +21 added lines, -16 removed lines patch added patch discarded remove patch
@@ -218,8 +218,7 @@  discard block
 block discarded – undo
218 218
         if (count($this->error) > 0)
219 219
         {
220 220
             return true;
221
-        }
222
-        else
221
+        } else
223 222
         {
224 223
             return false;
225 224
         }
@@ -255,8 +254,9 @@  discard block
 block discarded – undo
255 254
     function OpenID_Standarize($openid_identity = null)
256 255
     {
257 256
         // phpcs:enable
258
-        if ($openid_identity === null)
259
-        $openid_identity = $this->openid_url_identity;
257
+        if ($openid_identity === null) {
258
+                $openid_identity = $this->openid_url_identity;
259
+        }
260 260
 
261 261
         $u = parse_url(strtolower(trim($openid_identity)));
262 262
 
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
         }
269 269
         if (isset($u['query'])){ // If there is a query string, then use identity as is
270 270
             return $u['host'] . $u['path'] . '?' . $u['query'];
271
-        }else{
271
+        } else{
272 272
             return $u['host'] . $u['path'];
273 273
         }
274 274
     }
@@ -339,7 +339,9 @@  discard block
 block discarded – undo
339 339
     {
340 340
         // phpcs:enable
341 341
         // Remember, SSL MUST BE SUPPORTED
342
-        if (is_array($params)) $params = $this->array2url($params);
342
+        if (is_array($params)) {
343
+            $params = $this->array2url($params);
344
+        }
343 345
 
344 346
         $curl = curl_init($url . ($method == "GET" && $params != "" ? "?" . $params : ""));
345 347
         @curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
@@ -347,13 +349,15 @@  discard block
 block discarded – undo
347 349
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
348 350
         curl_setopt($curl, CURLOPT_HTTPGET, ($method == "GET"));
349 351
         curl_setopt($curl, CURLOPT_POST, ($method == "POST"));
350
-        if ($method == "POST") curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
352
+        if ($method == "POST") {
353
+            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
354
+        }
351 355
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
352 356
         $response = curl_exec($curl);
353 357
 
354 358
         if (curl_errno($curl) == 0){
355 359
             $response;
356
-        }else{
360
+        } else{
357 361
             $this->ErrorStore('OPENID_CURL', curl_error($curl));
358 362
         }
359 363
         return $response;
@@ -400,7 +404,9 @@  discard block
 block discarded – undo
400 404
         global $conf;
401 405
 
402 406
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
403
-		if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
407
+		if (empty($url)) {
408
+		    $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
409
+		}
404 410
 
405 411
         $response = getURLContent($url);
406 412
 
@@ -458,8 +464,7 @@  discard block
 block discarded – undo
458 464
             echo '<script language="JavaScript" type="text/javascript">window.location=\'';
459 465
             echo $redirect_to;
460 466
             echo '\';</script>';
461
-        }
462
-        else
467
+        } else
463 468
         {	// Default Header Redirect
464 469
             header('Location: ' . $redirect_to);
465 470
         }
@@ -502,8 +507,7 @@  discard block
 block discarded – undo
502 507
         if ($data['is_valid'] == "true")
503 508
         {
504 509
             return true;
505
-        }
506
-        else
510
+        } else
507 511
         {
508 512
             return false;
509 513
         }
@@ -523,7 +527,9 @@  discard block
 block discarded – undo
523 527
     	global $conf;
524 528
 
525 529
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
526
-		if (empty($url)) $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
530
+		if (empty($url)) {
531
+		    $url=$conf->global->MAIN_AUTHENTICATION_OPENID_URL;
532
+		}
527 533
 
528 534
 		dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS get XRDS');
529 535
 
@@ -554,8 +560,7 @@  discard block
 block discarded – undo
554 560
         {
555 561
             $this->ErrorStore('OPENID_NOSERVERSFOUND');
556 562
             return false;
557
-        }
558
-        else
563
+        } else
559 564
        {
560 565
        		dol_syslog(get_class($this).'::sendDiscoveryRequestToGetXRDS found endpoint = '.$server);
561 566
         	$this->SetOpenIDServer($server);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/emailsenderprofile.class.php 3 patches
Indentation   +385 added lines, -385 removed lines patch added patch discarded remove patch
@@ -35,401 +35,401 @@
 block discarded – undo
35 35
  */
36 36
 class EmailSenderProfile extends CommonObject
37 37
 {
38
-	/**
39
-	 * @var string ID to identify managed object
40
-	 */
41
-	public $element = 'emailsenderprofile';
42
-
43
-	/**
44
-	 * @var string Name of table without prefix where object is stored
45
-	 */
46
-	public $table_element = 'c_email_senderprofile';
47
-
48
-	/**
49
-	 * @var array  Does emailsenderprofile support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50
-	 */
51
-	public $ismultientitymanaged = 1;
52
-
53
-	/**
54
-	 * @var string String with name of icon for emailsenderprofile
55
-	 */
56
-	public $picto = 'emailsenderprofile@monmodule';
57
-
58
-
59
-	/**
60
-	 *             'type' if the field format.
61
-	 *             'label' the translation key.
62
-	 *             'enabled' is a condition when the filed must be managed.
63
-	 *             'visible' says if field is visible in list (-1 means not shown by default but can be added into list to be viewed).
64
-	 *             'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
65
-	 *             'index' if we want an index in database.
66
-	 *             'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
67
-	 *             'position' is the sort order of field.
68
-	 *             'searchall' is 1 if we want to search in this field when making a search from the quick search button.
69
-	 *             'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
70
-	 *             'help' is a string visible as a tooltip on field
71
-	 *             'comment' is not used. You can store here any text of your choice.
72
-	 */
73
-
74
-	// BEGIN MODULEBUILDER PROPERTIES
75
-	/**
76
-	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
77
-	 */
78
-	public $fields=array(
79
-		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',),
80
-		'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
81
-		'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1),
82
-		'email' => array('type'=>'varchar(255)', 'label'=>'Email', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1),
83
-		//'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
84
-		//'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>-1,),
85
-		'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,),
86
-		'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,),
87
-		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
88
-		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
89
-		'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1),
90
-	);
91
-
92
-	/**
93
-	 * @var int ID
94
-	 */
95
-	public $rowid;
96
-
97
-	/**
98
-	 * @var int Entity
99
-	 */
100
-	public $entity;
101
-
102
-	/**
38
+    /**
39
+     * @var string ID to identify managed object
40
+     */
41
+    public $element = 'emailsenderprofile';
42
+
43
+    /**
44
+     * @var string Name of table without prefix where object is stored
45
+     */
46
+    public $table_element = 'c_email_senderprofile';
47
+
48
+    /**
49
+     * @var array  Does emailsenderprofile support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50
+     */
51
+    public $ismultientitymanaged = 1;
52
+
53
+    /**
54
+     * @var string String with name of icon for emailsenderprofile
55
+     */
56
+    public $picto = 'emailsenderprofile@monmodule';
57
+
58
+
59
+    /**
60
+     *             'type' if the field format.
61
+     *             'label' the translation key.
62
+     *             'enabled' is a condition when the filed must be managed.
63
+     *             'visible' says if field is visible in list (-1 means not shown by default but can be added into list to be viewed).
64
+     *             'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
65
+     *             'index' if we want an index in database.
66
+     *             'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
67
+     *             'position' is the sort order of field.
68
+     *             'searchall' is 1 if we want to search in this field when making a search from the quick search button.
69
+     *             'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
70
+     *             'help' is a string visible as a tooltip on field
71
+     *             'comment' is not used. You can store here any text of your choice.
72
+     */
73
+
74
+    // BEGIN MODULEBUILDER PROPERTIES
75
+    /**
76
+     * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
77
+     */
78
+    public $fields=array(
79
+        'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',),
80
+        'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
81
+        'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1),
82
+        'email' => array('type'=>'varchar(255)', 'label'=>'Email', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1),
83
+        //'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
84
+        //'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>-1,),
85
+        'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,),
86
+        'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,),
87
+        'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
88
+        'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
89
+        'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1),
90
+    );
91
+
92
+    /**
93
+     * @var int ID
94
+     */
95
+    public $rowid;
96
+
97
+    /**
98
+     * @var int Entity
99
+     */
100
+    public $entity;
101
+
102
+    /**
103 103
      * @var string Email Sender Profile label
104 104
      */
105 105
     public $label;
106 106
 
107
-	public $email;
108
-	public $date_creation;
109
-	public $tms;
110
-	//public $fk_user_creat;
111
-	//public $fk_user_modif;
112
-	public $signature;
113
-	public $position;
114
-	public $active;
115
-	// END MODULEBUILDER PROPERTIES
116
-
117
-
118
-
119
-	// If this object has a subtable with lines
120
-
121
-	/**
122
-	 * @var int    Name of subtable line
123
-	 */
124
-	//public $table_element_line = 'emailsenderprofiledet';
125
-	/**
126
-	 * @var int    Field with ID of parent key if this field has a parent
127
-	 */
128
-	//public $fk_element = 'fk_emailsenderprofile';
129
-	/**
130
-	 * @var int    Name of subtable class that manage subtable lines
131
-	 */
132
-	//public $class_element_line = 'EmailSenderProfileline';
133
-	/**
134
-	 * @var array  Array of child tables (child tables to delete before deleting a record)
135
-	 */
136
-	//protected $childtables=array('emailsenderprofiledet');
137
-	/**
138
-	 * @var EmailSenderProfileLine[]     Array of subtable lines
139
-	 */
140
-	//public $lines = array();
141
-
142
-
143
-
144
-	/**
145
-	 * Constructor
146
-	 *
147
-	 * @param DoliDb $db Database handler
148
-	 */
149
-	public function __construct(DoliDB $db)
150
-	{
151
-		global $conf;
152
-
153
-		$this->db = $db;
154
-
155
-		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0;
156
-		if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0;
157
-	}
158
-
159
-	/**
160
-	 * Create object into database
161
-	 *
162
-	 * @param  User $user      User that creates
163
-	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
164
-	 * @return int             <0 if KO, Id of created object if OK
165
-	 */
166
-	public function create(User $user, $notrigger = false)
167
-	{
168
-		return $this->createCommon($user, $notrigger);
169
-	}
170
-
171
-	/**
172
-	 * Clone and object into another one
173
-	 *
174
-	 * @param  	User 	$user      	User that creates
175
-	 * @param  	int 	$fromid     Id of object to clone
176
-	 * @return 	mixed 				New object created, <0 if KO
177
-	 */
178
-	public function createFromClone(User $user, $fromid)
179
-	{
180
-		global $hookmanager, $langs;
181
-		$error = 0;
182
-
183
-		dol_syslog(__METHOD__, LOG_DEBUG);
184
-
185
-		$object = new self($this->db);
186
-
187
-		$this->db->begin();
188
-
189
-		// Load source object
190
-		$object->fetchCommon($fromid);
191
-		// Reset some properties
192
-		unset($object->id);
193
-		unset($object->fk_user_creat);
194
-		unset($object->import_key);
195
-
196
-		// Clear fields
197
-		$object->ref = "copy_of_".$object->ref;
198
-		$object->title = $langs->trans("CopyOf")." ".$object->title;
199
-		// ...
200
-
201
-		// Create clone
202
-		$object->context['createfromclone'] = 'createfromclone';
203
-		$result = $object->createCommon($user);
204
-		if ($result < 0) {
205
-			$error++;
206
-			$this->error = $object->error;
207
-			$this->errors = $object->errors;
208
-		}
209
-
210
-		// End
211
-		if (!$error) {
212
-			$this->db->commit();
213
-			return $object;
214
-		} else {
215
-			$this->db->rollback();
216
-			return -1;
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * Load object in memory from the database
222
-	 *
223
-	 * @param int    $id   Id object
224
-	 * @param string $ref  Ref
225
-	 * @return int         <0 if KO, 0 if not found, >0 if OK
226
-	 */
227
-	public function fetch($id, $ref = null)
228
-	{
229
-		$result = $this->fetchCommon($id, $ref);
230
-		if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
231
-		return $result;
232
-	}
233
-
234
-	/**
235
-	 * Load object lines in memory from the database
236
-	 *
237
-	 * @return int         <0 if KO, 0 if not found, >0 if OK
238
-	 */
239
-	public function fetchLines()
240
-	{
241
-		$this->lines=array();
242
-
243
-		// Load lines with object EmailSenderProfileLine
244
-
245
-		return count($this->lines)?1:0;
246
-	}
247
-
248
-	/**
249
-	 * Update object into database
250
-	 *
251
-	 * @param  User $user      User that modifies
252
-	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
253
-	 * @return int             <0 if KO, >0 if OK
254
-	 */
255
-	public function update(User $user, $notrigger = false)
256
-	{
257
-		return $this->updateCommon($user, $notrigger);
258
-	}
259
-
260
-	/**
261
-	 * Delete object in database
262
-	 *
263
-	 * @param User $user       User that deletes
264
-	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
265
-	 * @return int             <0 if KO, >0 if OK
266
-	 */
267
-	public function delete(User $user, $notrigger = false)
268
-	{
269
-		return $this->deleteCommon($user, $notrigger);
270
-	}
271
-
272
-	/**
273
-	 *  Return a link to the object card (with optionaly the picto)
274
-	 *
275
-	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
276
-	 *	@return	string								String with URL
277
-	 */
278
-	function getNomUrl($withpicto=0)
279
-	{
280
-		global $db, $conf, $langs;
281
-		global $dolibarr_main_authentication, $dolibarr_main_demo;
282
-		global $menumanager;
283
-
284
-		$result = '';
285
-		$companylink = '';
107
+    public $email;
108
+    public $date_creation;
109
+    public $tms;
110
+    //public $fk_user_creat;
111
+    //public $fk_user_modif;
112
+    public $signature;
113
+    public $position;
114
+    public $active;
115
+    // END MODULEBUILDER PROPERTIES
116
+
117
+
118
+
119
+    // If this object has a subtable with lines
120
+
121
+    /**
122
+     * @var int    Name of subtable line
123
+     */
124
+    //public $table_element_line = 'emailsenderprofiledet';
125
+    /**
126
+     * @var int    Field with ID of parent key if this field has a parent
127
+     */
128
+    //public $fk_element = 'fk_emailsenderprofile';
129
+    /**
130
+     * @var int    Name of subtable class that manage subtable lines
131
+     */
132
+    //public $class_element_line = 'EmailSenderProfileline';
133
+    /**
134
+     * @var array  Array of child tables (child tables to delete before deleting a record)
135
+     */
136
+    //protected $childtables=array('emailsenderprofiledet');
137
+    /**
138
+     * @var EmailSenderProfileLine[]     Array of subtable lines
139
+     */
140
+    //public $lines = array();
141
+
142
+
143
+
144
+    /**
145
+     * Constructor
146
+     *
147
+     * @param DoliDb $db Database handler
148
+     */
149
+    public function __construct(DoliDB $db)
150
+    {
151
+        global $conf;
152
+
153
+        $this->db = $db;
154
+
155
+        if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0;
156
+        if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0;
157
+    }
158
+
159
+    /**
160
+     * Create object into database
161
+     *
162
+     * @param  User $user      User that creates
163
+     * @param  bool $notrigger false=launch triggers after, true=disable triggers
164
+     * @return int             <0 if KO, Id of created object if OK
165
+     */
166
+    public function create(User $user, $notrigger = false)
167
+    {
168
+        return $this->createCommon($user, $notrigger);
169
+    }
170
+
171
+    /**
172
+     * Clone and object into another one
173
+     *
174
+     * @param  	User 	$user      	User that creates
175
+     * @param  	int 	$fromid     Id of object to clone
176
+     * @return 	mixed 				New object created, <0 if KO
177
+     */
178
+    public function createFromClone(User $user, $fromid)
179
+    {
180
+        global $hookmanager, $langs;
181
+        $error = 0;
182
+
183
+        dol_syslog(__METHOD__, LOG_DEBUG);
184
+
185
+        $object = new self($this->db);
186
+
187
+        $this->db->begin();
188
+
189
+        // Load source object
190
+        $object->fetchCommon($fromid);
191
+        // Reset some properties
192
+        unset($object->id);
193
+        unset($object->fk_user_creat);
194
+        unset($object->import_key);
195
+
196
+        // Clear fields
197
+        $object->ref = "copy_of_".$object->ref;
198
+        $object->title = $langs->trans("CopyOf")." ".$object->title;
199
+        // ...
200
+
201
+        // Create clone
202
+        $object->context['createfromclone'] = 'createfromclone';
203
+        $result = $object->createCommon($user);
204
+        if ($result < 0) {
205
+            $error++;
206
+            $this->error = $object->error;
207
+            $this->errors = $object->errors;
208
+        }
209
+
210
+        // End
211
+        if (!$error) {
212
+            $this->db->commit();
213
+            return $object;
214
+        } else {
215
+            $this->db->rollback();
216
+            return -1;
217
+        }
218
+    }
219
+
220
+    /**
221
+     * Load object in memory from the database
222
+     *
223
+     * @param int    $id   Id object
224
+     * @param string $ref  Ref
225
+     * @return int         <0 if KO, 0 if not found, >0 if OK
226
+     */
227
+    public function fetch($id, $ref = null)
228
+    {
229
+        $result = $this->fetchCommon($id, $ref);
230
+        if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
231
+        return $result;
232
+    }
233
+
234
+    /**
235
+     * Load object lines in memory from the database
236
+     *
237
+     * @return int         <0 if KO, 0 if not found, >0 if OK
238
+     */
239
+    public function fetchLines()
240
+    {
241
+        $this->lines=array();
242
+
243
+        // Load lines with object EmailSenderProfileLine
244
+
245
+        return count($this->lines)?1:0;
246
+    }
247
+
248
+    /**
249
+     * Update object into database
250
+     *
251
+     * @param  User $user      User that modifies
252
+     * @param  bool $notrigger false=launch triggers after, true=disable triggers
253
+     * @return int             <0 if KO, >0 if OK
254
+     */
255
+    public function update(User $user, $notrigger = false)
256
+    {
257
+        return $this->updateCommon($user, $notrigger);
258
+    }
259
+
260
+    /**
261
+     * Delete object in database
262
+     *
263
+     * @param User $user       User that deletes
264
+     * @param bool $notrigger  false=launch triggers after, true=disable triggers
265
+     * @return int             <0 if KO, >0 if OK
266
+     */
267
+    public function delete(User $user, $notrigger = false)
268
+    {
269
+        return $this->deleteCommon($user, $notrigger);
270
+    }
271
+
272
+    /**
273
+     *  Return a link to the object card (with optionaly the picto)
274
+     *
275
+     *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
276
+     *	@return	string								String with URL
277
+     */
278
+    function getNomUrl($withpicto=0)
279
+    {
280
+        global $db, $conf, $langs;
281
+        global $dolibarr_main_authentication, $dolibarr_main_demo;
282
+        global $menumanager;
283
+
284
+        $result = '';
285
+        $companylink = '';
286 286
 
287 287
     $label=$this->label;
288 288
 
289 289
     $url='';
290
-		//$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id;
291
-
292
-		$linkstart = '';
293
-		$linkend='';
294
-
295
-		if ($withpicto)
296
-		{
297
-			$result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend);
298
-			if ($withpicto != 2) $result.=' ';
299
-		}
300
-		$result.= $linkstart . $this->label . $linkend;
301
-		return $result;
302
-	}
303
-
304
-	/**
305
-	 * Return link to download file from a direct external access
306
-	 *
307
-	 * @param	int				$withpicto			Add download picto into link
308
-	 * @return	string			HTML link to file
309
-	 */
310
-	function getDirectExternalLink($withpicto=0)
311
-	{
312
-		return 'todo';
313
-	}
314
-
315
-	/**
316
-	 *  Retourne le libelle du status d'un user (actif, inactif)
317
-	 *
318
-	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
319
-	 *  @return	string 			       Label of status
320
-	 */
321
-	function getLibStatut($mode=0)
322
-	{
323
-		return $this->LibStatut($this->status,$mode);
324
-	}
290
+        //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id;
291
+
292
+        $linkstart = '';
293
+        $linkend='';
294
+
295
+        if ($withpicto)
296
+        {
297
+            $result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend);
298
+            if ($withpicto != 2) $result.=' ';
299
+        }
300
+        $result.= $linkstart . $this->label . $linkend;
301
+        return $result;
302
+    }
303
+
304
+    /**
305
+     * Return link to download file from a direct external access
306
+     *
307
+     * @param	int				$withpicto			Add download picto into link
308
+     * @return	string			HTML link to file
309
+     */
310
+    function getDirectExternalLink($withpicto=0)
311
+    {
312
+        return 'todo';
313
+    }
314
+
315
+    /**
316
+     *  Retourne le libelle du status d'un user (actif, inactif)
317
+     *
318
+     *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
319
+     *  @return	string 			       Label of status
320
+     */
321
+    function getLibStatut($mode=0)
322
+    {
323
+        return $this->LibStatut($this->status,$mode);
324
+    }
325 325
 
326 326
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
327
-	/**
328
-	 *  Return the status
329
-	 *
330
-	 *  @param	int		$status        	Id status
331
-	 *  @param  int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
332
-	 *  @return string 			       	Label of status
333
-	 */
334
-	static function LibStatut($status,$mode=0)
335
-	{
336
-		global $langs;
337
-
338
-		if ($mode == 0 || $mode == 1)
339
-		{
340
-			if ($status == 1) return $langs->trans('Enabled');
341
-			if ($status == 0) return $langs->trans('Disabled');
342
-		}
343
-		elseif ($mode == 2)
344
-		{
345
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
346
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
347
-		}
348
-		elseif ($mode == 3)
349
-		{
350
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
351
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
352
-		}
353
-		elseif ($mode == 4)
354
-		{
355
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
356
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
357
-		}
358
-		elseif ($mode == 5)
359
-		{
360
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
361
-			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
362
-		}
363
-		elseif ($mode == 6)
364
-		{
365
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
366
-			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
367
-		}
368
-	}
369
-
370
-	/**
371
-	 *	Charge les informations d'ordre info dans l'objet commande
372
-	 *
373
-	 *	@param  int		$id       Id of order
374
-	 *	@return	void
375
-	 */
376
-	function info($id)
377
-	{
378
-		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
379
-		$sql.= ' fk_user_creat, fk_user_modif';
380
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
381
-		$sql.= ' WHERE t.rowid = '.$id;
382
-		$result=$this->db->query($sql);
383
-		if ($result)
384
-		{
385
-			if ($this->db->num_rows($result))
386
-			{
387
-				$obj = $this->db->fetch_object($result);
388
-				$this->id = $obj->rowid;
389
-				if ($obj->fk_user_author)
390
-				{
391
-					$cuser = new User($this->db);
392
-					$cuser->fetch($obj->fk_user_author);
393
-					$this->user_creation   = $cuser;
394
-				}
395
-
396
-				if ($obj->fk_user_valid)
397
-				{
398
-					$vuser = new User($this->db);
399
-					$vuser->fetch($obj->fk_user_valid);
400
-					$this->user_validation = $vuser;
401
-				}
402
-
403
-				if ($obj->fk_user_cloture)
404
-				{
405
-					$cluser = new User($this->db);
406
-					$cluser->fetch($obj->fk_user_cloture);
407
-					$this->user_cloture   = $cluser;
408
-				}
409
-
410
-				$this->date_creation     = $this->db->jdate($obj->datec);
411
-				$this->date_modification = $this->db->jdate($obj->datem);
412
-				$this->date_validation   = $this->db->jdate($obj->datev);
413
-			}
414
-
415
-			$this->db->free($result);
416
-		}
417
-		else
418
-		{
419
-			dol_print_error($this->db);
420
-		}
421
-	}
422
-
423
-	/**
424
-	 * Initialise object with example values
425
-	 * Id must be 0 if object instance is a specimen
426
-	 *
427
-	 * @return void
428
-	 */
429
-	public function initAsSpecimen()
430
-	{
431
-		$this->initAsSpecimenCommon();
432
-	}
327
+    /**
328
+     *  Return the status
329
+     *
330
+     *  @param	int		$status        	Id status
331
+     *  @param  int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
332
+     *  @return string 			       	Label of status
333
+     */
334
+    static function LibStatut($status,$mode=0)
335
+    {
336
+        global $langs;
337
+
338
+        if ($mode == 0 || $mode == 1)
339
+        {
340
+            if ($status == 1) return $langs->trans('Enabled');
341
+            if ($status == 0) return $langs->trans('Disabled');
342
+        }
343
+        elseif ($mode == 2)
344
+        {
345
+            if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
346
+            if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
347
+        }
348
+        elseif ($mode == 3)
349
+        {
350
+            if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
351
+            if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
352
+        }
353
+        elseif ($mode == 4)
354
+        {
355
+            if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
356
+            if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
357
+        }
358
+        elseif ($mode == 5)
359
+        {
360
+            if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
361
+            if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
362
+        }
363
+        elseif ($mode == 6)
364
+        {
365
+            if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
366
+            if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
367
+        }
368
+    }
369
+
370
+    /**
371
+     *	Charge les informations d'ordre info dans l'objet commande
372
+     *
373
+     *	@param  int		$id       Id of order
374
+     *	@return	void
375
+     */
376
+    function info($id)
377
+    {
378
+        $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
379
+        $sql.= ' fk_user_creat, fk_user_modif';
380
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
381
+        $sql.= ' WHERE t.rowid = '.$id;
382
+        $result=$this->db->query($sql);
383
+        if ($result)
384
+        {
385
+            if ($this->db->num_rows($result))
386
+            {
387
+                $obj = $this->db->fetch_object($result);
388
+                $this->id = $obj->rowid;
389
+                if ($obj->fk_user_author)
390
+                {
391
+                    $cuser = new User($this->db);
392
+                    $cuser->fetch($obj->fk_user_author);
393
+                    $this->user_creation   = $cuser;
394
+                }
395
+
396
+                if ($obj->fk_user_valid)
397
+                {
398
+                    $vuser = new User($this->db);
399
+                    $vuser->fetch($obj->fk_user_valid);
400
+                    $this->user_validation = $vuser;
401
+                }
402
+
403
+                if ($obj->fk_user_cloture)
404
+                {
405
+                    $cluser = new User($this->db);
406
+                    $cluser->fetch($obj->fk_user_cloture);
407
+                    $this->user_cloture   = $cluser;
408
+                }
409
+
410
+                $this->date_creation     = $this->db->jdate($obj->datec);
411
+                $this->date_modification = $this->db->jdate($obj->datem);
412
+                $this->date_validation   = $this->db->jdate($obj->datev);
413
+            }
414
+
415
+            $this->db->free($result);
416
+        }
417
+        else
418
+        {
419
+            dol_print_error($this->db);
420
+        }
421
+    }
422
+
423
+    /**
424
+     * Initialise object with example values
425
+     * Id must be 0 if object instance is a specimen
426
+     *
427
+     * @return void
428
+     */
429
+    public function initAsSpecimen()
430
+    {
431
+        $this->initAsSpecimenCommon();
432
+    }
433 433
 }
434 434
 
435 435
 /**
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
  */
27 27
 
28 28
 // Put here all includes required by your class file
29
-require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
29
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30 30
 //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
31 31
 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
32 32
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 	/**
76 76
 	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
77 77
 	 */
78
-	public $fields=array(
78
+	public $fields = array(
79 79
 		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',),
80 80
 		'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
81 81
 		'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1),
@@ -152,8 +152,8 @@  discard block
 block discarded – undo
152 152
 
153 153
 		$this->db = $db;
154 154
 
155
-		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0;
156
-		if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0;
155
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0;
156
+		if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0;
157 157
 	}
158 158
 
159 159
 	/**
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 	public function fetch($id, $ref = null)
228 228
 	{
229 229
 		$result = $this->fetchCommon($id, $ref);
230
-		if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
230
+		if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
231 231
 		return $result;
232 232
 	}
233 233
 
@@ -238,11 +238,11 @@  discard block
 block discarded – undo
238 238
 	 */
239 239
 	public function fetchLines()
240 240
 	{
241
-		$this->lines=array();
241
+		$this->lines = array();
242 242
 
243 243
 		// Load lines with object EmailSenderProfileLine
244 244
 
245
-		return count($this->lines)?1:0;
245
+		return count($this->lines) ? 1 : 0;
246 246
 	}
247 247
 
248 248
 	/**
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
276 276
 	 *	@return	string								String with URL
277 277
 	 */
278
-	function getNomUrl($withpicto=0)
278
+	function getNomUrl($withpicto = 0)
279 279
 	{
280 280
 		global $db, $conf, $langs;
281 281
 		global $dolibarr_main_authentication, $dolibarr_main_demo;
@@ -284,20 +284,20 @@  discard block
 block discarded – undo
284 284
 		$result = '';
285 285
 		$companylink = '';
286 286
 
287
-    $label=$this->label;
287
+    $label = $this->label;
288 288
 
289
-    $url='';
289
+    $url = '';
290 290
 		//$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id;
291 291
 
292 292
 		$linkstart = '';
293
-		$linkend='';
293
+		$linkend = '';
294 294
 
295 295
 		if ($withpicto)
296 296
 		{
297
-			$result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend);
298
-			if ($withpicto != 2) $result.=' ';
297
+			$result .= ($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend);
298
+			if ($withpicto != 2) $result .= ' ';
299 299
 		}
300
-		$result.= $linkstart . $this->label . $linkend;
300
+		$result .= $linkstart.$this->label.$linkend;
301 301
 		return $result;
302 302
 	}
303 303
 
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 	 * @param	int				$withpicto			Add download picto into link
308 308
 	 * @return	string			HTML link to file
309 309
 	 */
310
-	function getDirectExternalLink($withpicto=0)
310
+	function getDirectExternalLink($withpicto = 0)
311 311
 	{
312 312
 		return 'todo';
313 313
 	}
@@ -318,9 +318,9 @@  discard block
 block discarded – undo
318 318
 	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
319 319
 	 *  @return	string 			       Label of status
320 320
 	 */
321
-	function getLibStatut($mode=0)
321
+	function getLibStatut($mode = 0)
322 322
 	{
323
-		return $this->LibStatut($this->status,$mode);
323
+		return $this->LibStatut($this->status, $mode);
324 324
 	}
325 325
 
326 326
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 	 *  @param  int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
332 332
 	 *  @return string 			       	Label of status
333 333
 	 */
334
-	static function LibStatut($status,$mode=0)
334
+	static function LibStatut($status, $mode = 0)
335 335
 	{
336 336
 		global $langs;
337 337
 
@@ -342,28 +342,28 @@  discard block
 block discarded – undo
342 342
 		}
343 343
 		elseif ($mode == 2)
344 344
 		{
345
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
346
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
345
+			if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
346
+			if ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
347 347
 		}
348 348
 		elseif ($mode == 3)
349 349
 		{
350
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
351
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
350
+			if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4');
351
+			if ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5');
352 352
 		}
353 353
 		elseif ($mode == 4)
354 354
 		{
355
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
356
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
355
+			if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
356
+			if ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
357 357
 		}
358 358
 		elseif ($mode == 5)
359 359
 		{
360
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
361
-			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
360
+			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4');
361
+			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5');
362 362
 		}
363 363
 		elseif ($mode == 6)
364 364
 		{
365
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
366
-			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
365
+			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4');
366
+			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5');
367 367
 		}
368 368
 	}
369 369
 
@@ -376,10 +376,10 @@  discard block
 block discarded – undo
376 376
 	function info($id)
377 377
 	{
378 378
 		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
379
-		$sql.= ' fk_user_creat, fk_user_modif';
380
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
381
-		$sql.= ' WHERE t.rowid = '.$id;
382
-		$result=$this->db->query($sql);
379
+		$sql .= ' fk_user_creat, fk_user_modif';
380
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
381
+		$sql .= ' WHERE t.rowid = '.$id;
382
+		$result = $this->db->query($sql);
383 383
 		if ($result)
384 384
 		{
385 385
 			if ($this->db->num_rows($result))
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
 				{
391 391
 					$cuser = new User($this->db);
392 392
 					$cuser->fetch($obj->fk_user_author);
393
-					$this->user_creation   = $cuser;
393
+					$this->user_creation = $cuser;
394 394
 				}
395 395
 
396 396
 				if ($obj->fk_user_valid)
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 				{
405 405
 					$cluser = new User($this->db);
406 406
 					$cluser->fetch($obj->fk_user_cloture);
407
-					$this->user_cloture   = $cluser;
407
+					$this->user_cloture = $cluser;
408 408
 				}
409 409
 
410 410
 				$this->date_creation     = $this->db->jdate($obj->datec);
Please login to merge, or discard this patch.
Braces   +54 added lines, -28 removed lines patch added patch discarded remove patch
@@ -152,8 +152,12 @@  discard block
 block discarded – undo
152 152
 
153 153
 		$this->db = $db;
154 154
 
155
-		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0;
156
-		if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0;
155
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
156
+		    $this->fields['rowid']['visible']=0;
157
+		}
158
+		if (empty($conf->multicompany->enabled)) {
159
+		    $this->fields['entity']['enabled']=0;
160
+		}
157 161
 	}
158 162
 
159 163
 	/**
@@ -227,7 +231,9 @@  discard block
 block discarded – undo
227 231
 	public function fetch($id, $ref = null)
228 232
 	{
229 233
 		$result = $this->fetchCommon($id, $ref);
230
-		if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
234
+		if ($result > 0 && ! empty($this->table_element_line)) {
235
+		    $this->fetchLines();
236
+		}
231 237
 		return $result;
232 238
 	}
233 239
 
@@ -295,7 +301,9 @@  discard block
 block discarded – undo
295 301
 		if ($withpicto)
296 302
 		{
297 303
 			$result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend);
298
-			if ($withpicto != 2) $result.=' ';
304
+			if ($withpicto != 2) {
305
+			    $result.=' ';
306
+			}
299 307
 		}
300 308
 		$result.= $linkstart . $this->label . $linkend;
301 309
 		return $result;
@@ -337,33 +345,52 @@  discard block
 block discarded – undo
337 345
 
338 346
 		if ($mode == 0 || $mode == 1)
339 347
 		{
340
-			if ($status == 1) return $langs->trans('Enabled');
341
-			if ($status == 0) return $langs->trans('Disabled');
342
-		}
343
-		elseif ($mode == 2)
348
+			if ($status == 1) {
349
+			    return $langs->trans('Enabled');
350
+			}
351
+			if ($status == 0) {
352
+			    return $langs->trans('Disabled');
353
+			}
354
+		} elseif ($mode == 2)
344 355
 		{
345
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
346
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
347
-		}
348
-		elseif ($mode == 3)
356
+			if ($status == 1) {
357
+			    return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
358
+			}
359
+			if ($status == 0) {
360
+			    return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
361
+			}
362
+		} elseif ($mode == 3)
349 363
 		{
350
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
351
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
352
-		}
353
-		elseif ($mode == 4)
364
+			if ($status == 1) {
365
+			    return img_picto($langs->trans('Enabled'),'statut4');
366
+			}
367
+			if ($status == 0) {
368
+			    return img_picto($langs->trans('Disabled'),'statut5');
369
+			}
370
+		} elseif ($mode == 4)
354 371
 		{
355
-			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
356
-			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
357
-		}
358
-		elseif ($mode == 5)
372
+			if ($status == 1) {
373
+			    return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
374
+			}
375
+			if ($status == 0) {
376
+			    return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
377
+			}
378
+		} elseif ($mode == 5)
359 379
 		{
360
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
361
-			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
362
-		}
363
-		elseif ($mode == 6)
380
+			if ($status == 1) {
381
+			    return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
382
+			}
383
+			if ($status == 0) {
384
+			    return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
385
+			}
386
+		} elseif ($mode == 6)
364 387
 		{
365
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
366
-			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
388
+			if ($status == 1) {
389
+			    return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
390
+			}
391
+			if ($status == 0) {
392
+			    return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
393
+			}
367 394
 		}
368 395
 	}
369 396
 
@@ -413,8 +440,7 @@  discard block
 block discarded – undo
413 440
 			}
414 441
 
415 442
 			$this->db->free($result);
416
-		}
417
-		else
443
+		} else
418 444
 		{
419 445
 			dol_print_error($this->db);
420 446
 		}
Please login to merge, or discard this patch.