--- /tmp/dsg/dolibarr/htdocs/core/class/github_CMailFile.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_CMailFile.class.php @@ -32,7 +32,7 @@ /** * Class to send emails (with attachments or not) - * Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); + * Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext); * $mailfile->sendfile(); */ class CMailFile @@ -41,49 +41,47 @@ public $sendmode; public $sendsetup; - public $subject; // Topic: Subject of email - public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). + public $subject; // Topic: Subject of email + public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). // Sender: Who send the email ("Sender" has sent emails on behalf of "From"). // Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain. // Return-Path: Email where to send bounds. - public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined) - public $errors_to; // Errors-To: Email where to send errors. - public $addr_to; - public $addr_cc; - public $addr_bcc; - public $trackid; - - public $mixed_boundary; - public $related_boundary; - public $alternative_boundary; - public $deliveryreceipt; - - public $atleastonefile; - - public $eol; - public $eol2; + public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined) + public $errors_to; // Errors-To: Email where to send errors. + public $addr_to; + public $addr_cc; + public $addr_bcc; + public $trackid; + + public $mixed_boundary; + public $related_boundary; + public $alternative_boundary; + public $deliveryreceipt; + + public $eol; + public $eol2; /** * @var string Error code (or message) */ public $error = ''; - public $smtps; // Contains SMTPs object (if this method is used) - public $phpmailer; // Contains PHPMailer object (if this method is used) + public $smtps; // Contains SMTPs object (if this method is used) + public $phpmailer; // Contains PHPMailer object (if this method is used) /** * @var string CSS */ public $css; //! Defined css style for body background - public $styleCSS; + public $styleCSS; //! Defined background directly in body tag - public $bodyCSS; - - public $msgid; - public $headers; - public $message; - /** + public $bodyCSS; + + public $msgid; + public $headers; + public $message; + /** * @var array fullfilenames list (full path of filename on file system) */ public $filename_list = array(); @@ -97,21 +95,21 @@ public $mimefilename_list = array(); // Image - public $html; - public $image_boundary; - public $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). - public $html_images = array(); - public $images_encoded = array(); - public $image_types = array( - 'gif' => 'image/gif', + public $html; + public $image_boundary; + public $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). + public $html_images = array(); + public $images_encoded = array(); + public $image_types = array( + 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'bmp' => 'image/bmp', 'png' => 'image/png', 'tif' => 'image/tiff', - 'tiff' => 'image/tiff', - ); + 'tiff' => 'image/tiff', + ); /** @@ -146,12 +144,10 @@ } } - // Add autocopy to if not already in $to (Note: Adding bcc for specific modules are also done from pages) - if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO) && !preg_match('/'.preg_quote($conf->global->MAIN_MAIL_AUTOCOPY_TO, '/').'/i', $to)) { - $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; - } - - $this->subject = $subject; + // Add autocopy to (Note: Adding bcc for specific modules are also done from pages) + if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + + $this->subject = $subject; $this->addr_to = $to; $this->addr_from = $from; $this->msg = $msg; @@ -172,13 +168,9 @@ // Define this->sendmode $this->sendmode = ''; - if (!empty($this->sendcontext)) { - $smtpContextKey = strtoupper($this->sendcontext); - $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; - $smtpContextSendMode = empty($conf->global->{$keyForSMTPSendMode}) ? '' : $conf->global->{$keyForSMTPSendMode}; - if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { - $this->sendmode = $smtpContextSendMode; - } + if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING; } if (empty($this->sendmode)) $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE; if (empty($this->sendmode)) $this->sendmode = 'mail'; @@ -203,7 +195,7 @@ // On defini alternative_boundary $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars) - dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, replyto=$replyto trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); + dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); if (empty($subject)) @@ -214,8 +206,8 @@ } if (empty($msg)) { - dol_syslog("CMailFile::CMailfile: Try to send an email with empty body"); - $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure) + dol_syslog("CMailFile::CMailfile: Try to send an email with empty body"); + $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure) } // Detect if message is HTML (use fast method) @@ -223,7 +215,9 @@ { $this->msgishtml = 0; if (dol_textishtml($msg)) $this->msgishtml = 1; - } else { + } + else + { $this->msgishtml = $msgishtml; } @@ -244,7 +238,6 @@ { $this->html = $msg; - $findimg = 0; if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) { $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias'); @@ -277,38 +270,6 @@ } } - // Add autocopy to if not already in $to (Note: Adding bcc for specific modules are also done from pages) - if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO) && !preg_match('/'.preg_quote($conf->global->MAIN_MAIL_AUTOCOPY_TO, '/').'/i', $to)) { - $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; - } - - $this->addr_to = $to; - $this->addr_cc = $addr_cc; - $this->addr_bcc = $addr_bcc; - $this->reply_to = $replyto; - $this->addr_from = $from; - $this->subject = $subject; - $this->errors_to = $errors_to; - $this->deliveryreceipt = $deliveryreceipt; - $this->trackid = $trackid; - - if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) - { - $this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO; - $this->addr_cc = ''; - $this->addr_bcc = ''; - } - - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED'; - if (!empty($this->sendcontext)) { - $smtpContextKey = strtoupper($this->sendcontext); - $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; - $smtpContextSendMode = empty($conf->global->{$keyForSMTPSendMode}) ? '' : $conf->global->{$keyForSMTPSendMode}; - if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey; - } - } - // We set all data according to choosed sending method. // We also set a value for ->msgid if ($this->sendmode == 'mail') @@ -343,7 +304,8 @@ $text_body = $this->write_body($msg); // Add attachments to text_encoded - if (!empty($this->atleastonefile)) { + if ($this->atleastonefile) + { $files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list); } @@ -357,7 +319,8 @@ $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol; $this->message .= $text_body.$files_encoded; $this->message .= "--".$this->mixed_boundary."--".$this->eol; - } elseif ($this->sendmode == 'smtps') + } + elseif ($this->sendmode == 'smtps') { // Use SMTPS library // ------------------------------------------ @@ -367,16 +330,16 @@ $smtps->setCharSet($conf->file->character_set_client); // Encode subject if required. - $subjecttouse = $this->subject; + $subjecttouse = $subject; if (!ascii_check($subjecttouse)) { $subjecttouse = $this->encodetorfc2822($subjecttouse); } $smtps->setSubject($subjecttouse); - $smtps->setTO($this->getValidAddress($this->addr_to, 0, 1)); - $smtps->setFrom($this->getValidAddress($this->addr_from, 0, 1)); - $smtps->setTrackId($this->trackid); - $smtps->setReplyTo($this->getValidAddress($this->reply_to, 0, 1)); + $smtps->setTO($this->getValidAddress($to, 0, 1)); + $smtps->setFrom($this->getValidAddress($from, 0, 1)); + $smtps->setTrackId($trackid); + $smtps->setReplyTo($this->getValidAddress($replyto, 0, 1)); if (!empty($moreinheader)) $smtps->setMoreInHeader($moreinheader); @@ -405,7 +368,7 @@ } } - if (!empty($this->atleastonefile)) + if ($this->atleastonefile) { foreach ($filename_list as $i => $val) { @@ -414,95 +377,83 @@ } } - $smtps->setCC($this->addr_cc); - $smtps->setBCC($this->addr_bcc); - $smtps->setErrorsTo($this->errors_to); - $smtps->setDeliveryReceipt($this->deliveryreceipt); - if (!empty($conf->global->$keyforsslseflsigned)) $smtps->setOptions(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true))); + $smtps->setCC($addr_cc); + $smtps->setBCC($addr_bcc); + $smtps->setErrorsTo($errors_to); + $smtps->setDeliveryReceipt($deliveryreceipt); $host = dol_getprefix('email'); - $this->msgid = time().'.SMTPs-dolibarr-'.$this->trackid.'@'.$host; + $this->msgid = time().'.SMTPs-dolibarr-'.$trackid.'@'.$host; $this->smtps = $smtps; - } elseif ($this->sendmode == 'swiftmailer') { + } + elseif ($this->sendmode == 'swiftmailer') + { // Use Swift Mailer library - $host = dol_getprefix('email'); - - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; - - // egulias autoloader lib - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php'; - - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; - - // Create the message - //$this->message = Swift_Message::newInstance(); - $this->message = new Swift_Message(); - //$this->message = new Swift_SignedMessage(); - // Adding a trackid header to a message - $headers = $this->message->getHeaders(); - $headers->addTextHeader('X-Dolibarr-TRACKID', $this->trackid.'@'.$host); - $this->msgid = time().'.swiftmailer-dolibarr-'.$this->trackid.'@'.$host; - $headerID = $this->msgid; - $msgid = $headers->get('Message-ID'); - $msgid->setId($headerID); - $headers->addIdHeader('References', $headerID); - // TODO if (! empty($moreinheader)) ... - - // Give the message a subject - try { - $result = $this->message->setSubject($this->subject); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - - // Set the From address with an associative array - //$this->message->setFrom(array('john@doe.com' => 'John Doe')); - if (!empty($this->addr_from)) { - try { - if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) { - // Prevent email spoofing for smtp server with a strict configuration - $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string - $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom); - $adressEmailFrom = reset($adressEmailFrom); - if ($emailMatchs !== false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) - { - $result = $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID); - } else { - $result = $this->message->setFrom($this->getArrayAddress($this->addr_from)); - } - } else { - $result = $this->message->setFrom($this->getArrayAddress($this->addr_from)); - } - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - // Set the To addresses with an associative array - if (!empty($this->addr_to)) { - try { - $result = $this->message->setTo($this->getArrayAddress($this->addr_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - if (!empty($this->reply_to)) { - try { - $result = $this->message->SetReplyTo($this->getArrayAddress($this->reply_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - try { - $result = $this->message->setCharSet($conf->file->character_set_client); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - - if (!empty($this->html)) { + $host = dol_getprefix('email'); + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + + // egulias autoloader lib + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; + + // Create the message + //$this->message = Swift_Message::newInstance(); + $this->message = new Swift_Message(); + //$this->message = new Swift_SignedMessage(); + // Adding a trackid header to a message + $headers = $this->message->getHeaders(); + $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid.'@'.$host); + $this->msgid = time().'.swiftmailer-dolibarr-'.$trackid.'@'.$host; + $headerID = $this->msgid; + $msgid = $headers->get('Message-ID'); + $msgid->setId($headerID); + $headers->addIdHeader('References', $headerID); + // TODO if (! empty($moreinheader)) ... + + // Give the message a subject + try { + $result = $this->message->setSubject($subject); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + + // Set the From address with an associative array + //$this->message->setFrom(array('john@doe.com' => 'John Doe')); + if (!empty($from)) { + try { + $result = $this->message->setFrom($this->getArrayAddress($from)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + // Set the To addresses with an associative array + if (!empty($to)) { + try { + $result = $this->message->setTo($this->getArrayAddress($to)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + if (!empty($replyto)) { + try { + $result = $this->message->SetReplyTo($this->getArrayAddress($replyto)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + + try { + $result = $this->message->setCharSet($conf->file->character_set_client); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + + if (!empty($this->html)) { if (!empty($css)) { $this->css = $css; $this->buildCSS(); @@ -534,24 +485,23 @@ $this->message->addPart(dol_nl2br($msg), 'text/html'); } - if (!empty($this->atleastonefile)) + if ($this->atleastonefile) { foreach ($filename_list as $i => $val) { //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i])); $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]); - if (!empty($mimefilename_list[$i])) { - $attachment->setFilename($mimefilename_list[$i]); - } $this->message->attach($attachment); } } - if (!empty($this->addr_cc)) $this->message->setCc($this->getArrayAddress($this->addr_cc)); - if (!empty($this->addr_bcc)) $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); - //if (! empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to)); - if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from)); - } else { + if (!empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc)); + if (!empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc)); + //if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to); + if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from)); + } + else + { // Send mail method not correctly defined // -------------------------------------- $this->error = 'Bad value for sendmode'; @@ -596,26 +546,26 @@ $sendingmode = $this->sendmode; if ($this->context == 'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') { - // List of sending methods - $listofmethods = array(); - $listofmethods['mail'] = 'PHP mail function'; - //$listofmethods['simplemail']='Simplemail class'; - $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; - - // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. - // You ensure that every user is using its own SMTP server when using the mass emailing module. - $linktoadminemailbefore = ''; - $linktoadminemailend = ''; - $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); - $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); - $this->error .= '
'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); - $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); - if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) - { - $this->error .= '
'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); - $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); - } - return false; + // List of sending methods + $listofmethods = array(); + $listofmethods['mail'] = 'PHP mail function'; + //$listofmethods['simplemail']='Simplemail class'; + $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; + + // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. + // You ensure that every user is using its own SMTP server when using the mass emailing module. + $linktoadminemailbefore = ''; + $linktoadminemailend = ''; + $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); + $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); + $this->error .= '
'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); + $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); + if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) + { + $this->error .= '
'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); + $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); + } + return false; } // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL @@ -657,20 +607,21 @@ $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW'; $keyfortls = 'MAIN_MAIL_EMAIL_TLS'; $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS'; - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED'; - if (!empty($this->sendcontext)) { - $smtpContextKey = strtoupper($this->sendcontext); - $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; - $smtpContextSendMode = empty($conf->global->{$keyForSMTPSendMode}) ? '' : $conf->global->{$keyForSMTPSendMode}; - if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { - $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey; - $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey; - $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey; - $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey; - $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey; - $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey; - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey; - } + if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') + { + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING'; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_EMAILING'; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_EMAILING'; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_EMAILING'; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS_EMAILING'; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; + } + + if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) + { + $this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO; + $this->addr_cc = ''; + $this->addr_bcc = ''; } // Action according to choosed sending method @@ -727,11 +678,7 @@ if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params - $linuxlike = 1; - if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; - if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; - - dol_syslog("CMailFile::sendfile: mail start".($linuxlike ? '' : " HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')).", additionnal_parameters=".$additionnalparam, LOG_DEBUG); + dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG); $this->message = stripslashes($this->message); @@ -750,13 +697,19 @@ { $langs->load("errors"); $this->error = "Failed to send mail with php mail"; - if (!$linuxlike) { + $linuxlike = 1; + if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; + if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; + if (!$linuxlike) + { $this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems } $this->error .= ".
"; $this->error .= $langs->trans("ErrorPhpMailDelivery"); dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - } else { + } + else + { dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG); } } @@ -769,7 +722,8 @@ // Restore parameters if (!empty($conf->global->$keyforsmtpserver)) ini_restore('SMTP'); if (!empty($conf->global->$keyforsmtpport)) ini_restore('smtp_port'); - } elseif ($this->sendmode == 'smtps') + } + elseif ($this->sendmode == 'smtps') { if (!is_object($this->smtps)) { @@ -814,14 +768,14 @@ $from = $this->smtps->getFrom('org'); if ($res && !$from) { - $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - Sender address '$from' invalid"; + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Sender address '$from' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; } $dest = $this->smtps->getTo(); if ($res && !$dest) { - $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - Recipient address '$dest' invalid"; + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; } @@ -840,17 +794,20 @@ { dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG); $res = true; - } else { + } + else + { if (empty($this->error)) $this->error = $result; - dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - ".$this->error, LOG_ERR); + dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
".$this->error, LOG_ERR); $res = false; } } - } elseif ($this->sendmode == 'swiftmailer') - { - // Use Swift Mailer library - // ------------------------------------------ - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; + } + elseif ($this->sendmode == 'swiftmailer') + { + // Use Swift Mailer library + // ------------------------------------------ + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Clean parameters if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); @@ -866,26 +823,25 @@ if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); - if (!empty($conf->global->$keyforsslseflsigned)) $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false))); //$smtps->_msgReplyTo = 'reply@web.com'; // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable - $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); - $this->message->setEncoder($contentEncoderBase64); + $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + $this->message->setEncoder($contentEncoderBase64); // Create the Mailer using your created Transport $this->mailer = new Swift_Mailer($this->transport); - // DKIM SIGN - if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { - $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; - $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; - $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; - $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); - $this->message->attachSigner($signer->ignoreHeader('Return-Path')); - } - - if (!empty($conf->global->MAIN_MAIL_DEBUG)) { + // DKIM SIGN + if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { + $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); + $this->message->attachSigner($signer->ignoreHeader('Return-Path')); + } + + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); // Or to use the Echo Logger @@ -904,10 +860,14 @@ if (!empty($this->error) || !$result) { dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; - } else { + } + else + { dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG); } - } else { + } + else + { // Send mail method not correctly defined // -------------------------------------- @@ -923,7 +883,9 @@ return $reshook; } - } else { + } + else + { $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING); } @@ -945,7 +907,7 @@ return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?='; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Read a file on disk and return encoded content for emails (mode = 'mail') * @@ -954,7 +916,7 @@ */ private function _encode_file($sourcefile) { - // phpcs:enable + // phpcs:enable $newsourcefile = dol_osencode($sourcefile); if (is_readable($newsourcefile)) @@ -962,7 +924,9 @@ $contents = file_get_contents($newsourcefile); // Need PHP 4.3 $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047 return $encoded; - } else { + } + else + { $this->error = "Error: Can't read file '".$sourcefile."' into _encode_file"; dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR); return -1; @@ -970,7 +934,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Write content of a SMTP request into a dump file (mode = all) * Used for debugging. @@ -980,7 +944,7 @@ */ public function dump_mail() { - // phpcs:enable + // phpcs:enable global $conf, $dolibarr_main_data_root; if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir @@ -993,10 +957,12 @@ fputs($fp, $this->headers); fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log fputs($fp, $this->message); - } elseif ($this->sendmode == 'smtps') + } + elseif ($this->sendmode == 'smtps') { fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on - } elseif ($this->sendmode == 'swiftmailer') + } + elseif ($this->sendmode == 'swiftmailer') { fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on } @@ -1025,7 +991,9 @@ $out .= ">"; $out .= $msg; $out .= ""; - } else { + } + else + { $out = $msg; } @@ -1061,7 +1029,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Create SMTP headers (mode = 'mail') * @@ -1069,7 +1037,7 @@ */ public function write_smtpheaders() { - // phpcs:enable + // phpcs:enable global $conf; $out = ""; @@ -1106,7 +1074,9 @@ $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail $out .= 'References: <'.$this->msgid.">".$this->eol2; $out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2; - } else { + } + else + { $this->msgid = time().'.phpmail@'.$host; $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; } @@ -1125,7 +1095,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Create header MIME (mode = 'mail') * @@ -1135,7 +1105,7 @@ */ public function write_mimeheaders($filename_list, $mimefilename_list) { - // phpcs:enable + // phpcs:enable $mimedone = 0; $out = ""; @@ -1156,7 +1126,7 @@ return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return email content (mode = 'mail') * @@ -1165,7 +1135,7 @@ */ public function write_body($msgtext) { - // phpcs:enable + // phpcs:enable global $conf; $out = ''; @@ -1235,7 +1205,9 @@ { $out .= "--".$this->alternative_boundary."--".$this->eol; } - } else { + } + else + { $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out .= $this->eol.$strContent.$this->eol; @@ -1256,7 +1228,7 @@ return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Attach file to email (mode = 'mail') * @@ -1267,7 +1239,7 @@ */ public function write_files($filename_list, $mimetype_list, $mimefilename_list) { - // phpcs:enable + // phpcs:enable $out = ''; $filename_list_size = count($filename_list); @@ -1293,7 +1265,9 @@ $out .= $encoded; $out .= $this->eol; //$out.= $this->eol; - } else { + } + else + { return $encoded; } } @@ -1303,7 +1277,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Attach an image to email (mode = 'mail') * @@ -1312,7 +1286,7 @@ */ public function write_images($images_list) { - // phpcs:enable + // phpcs:enable $out = ''; if (is_array($images_list)) @@ -1336,7 +1310,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Try to create a socket connection * @@ -1346,7 +1320,7 @@ */ public function check_server_port($host, $port) { - // phpcs:enable + // phpcs:enable global $conf; $_retVal = 0; @@ -1377,7 +1351,7 @@ dol_syslog("Try socket connection to host=".$host." port=".$port); //See if we can connect to the SMTP server - if ($socket = @fsockopen( + if ($socket = @fsockopen( $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS. $port, // which Port number to use $errno, // actual system level error @@ -1391,14 +1365,16 @@ // Check response from Server if ($_retVal = $this->server_parse($socket, "220")) $_retVal = $socket; - } else { + } + else + { $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr); } } return $_retVal; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * This function has been modified as provided by SirSir to allow multiline responses when * using SMTP Extensions. @@ -1409,7 +1385,7 @@ */ public function server_parse($socket, $response) { - // phpcs:enable + // phpcs:enable $_retVal = true; // Indicates if Object was created or not $server_response = ''; @@ -1511,12 +1487,16 @@ } $i++; } - } else { + } + else + { return -1; } return 1; - } else { + } + else + { return 0; } } @@ -1533,8 +1513,8 @@ * If format 2: 'john@doe.com' * If format 3: '' or '"John Doe" ' or '"=?UTF-8?B?Sm9obiBEb2U=?=" ' * If format 4: 'John Doe' or 'john@doe.com' if no label exists - * If format 5: John Doe or john@doe.com if no label exists - * @see getArrayAddress() + * If format 5: John Doe or john@doe.com if no label exists + * @see getArrayAddress() */ public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0) { @@ -1548,12 +1528,13 @@ $i = 0; foreach ($arrayaddress as $val) { - $regs = array(); if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { $name = trim($regs[1]); $email = trim($regs[2]); - } else { + } + else + { $name = ''; $email = trim($val); } @@ -1563,10 +1544,10 @@ $i++; $newemail = ''; - if ($format == 5) { - $newemail = $name ? $name : $email; - $newemail = ''.$newemail.''; - } + if ($format == 5) { + $newemail = $name ? $name : $email; + $newemail = ''.$newemail.''; + } if ($format == 4) { $newemail = $name ? $name : $email; @@ -1622,7 +1603,9 @@ { $name = trim($regs[1]); $email = trim($regs[2]); - } else { + } + else + { $name = null; $email = trim($val); } --- /tmp/dsg/dolibarr/htdocs/core/class/github_CSMSFile.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_CSMSFile.class.php @@ -34,7 +34,7 @@ */ class CSMSFile { - /** + /** * @var string Error code (or message) */ public $error = ''; @@ -76,21 +76,21 @@ // If ending method not defined if (empty($conf->global->MAIN_SMS_SENDMODE)) { - $this->error = 'No SMS Engine defined'; - return -1; + $this->error = 'No SMS Engine defined'; + return -1; } dol_syslog("CSMSFile::CSMSFile: MAIN_SMS_SENDMODE=".$conf->global->MAIN_SMS_SENDMODE." charset=".$conf->file->character_set_client." from=".$from.", to=".$to.", msg length=".count($msg), LOG_DEBUG); dol_syslog("CSMSFile::CSMSFile: deferred=".$deferred." priority=".$priority." class=".$class, LOG_DEBUG); // Action according to choosed sending method - $this->addr_from = $from; - $this->addr_to = $to; - $this->deferred = $deferred; - $this->priority = $priority; - $this->class = $class; - $this->message = $msg; - $this->nostop = false; + $this->addr_from = $from; + $this->addr_to = $to; + $this->deferred = $deferred; + $this->priority = $priority; + $this->class = $class; + $this->message = $msg; + $this->nostop = false; } @@ -108,17 +108,17 @@ $res = false; - dol_syslog("CSMSFile::sendfile addr_to=".$this->addr_to, LOG_DEBUG); - dol_syslog("CSMSFile::sendfile message=\n".$this->message); - - $this->message = stripslashes($this->message); - - if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms(); + dol_syslog("CSMSFile::sendfile addr_to=".$this->addr_to, LOG_DEBUG); + dol_syslog("CSMSFile::sendfile message=\n".$this->message); + + $this->message = stripslashes($this->message); + + if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms(); if (empty($conf->global->MAIN_DISABLE_ALL_SMS)) { - // Action according to choosed sending method - if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') // Backward compatibility @deprecated + // Action according to choosed sending method + if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') // Backward compatibility @deprecated { dol_include_once('/ovh/class/ovhsms.class.php'); $sms = new OvhSms($this->db); @@ -127,67 +127,78 @@ $sms->message = $this->message; $sms->deferred = $this->deferred; $sms->priority = $this->priority; - $sms->class = $this->class; - $sms->nostop = $this->nostop; - - $sms->socid = $this->socid; - $sms->contact_id = $this->contact_id; - $sms->project = $this->fk_project; - - $res = $sms->SmsSend(); + $sms->class = $this->class; + $sms->nostop = $this->nostop; + + $sms->socid = $this->socid; + $sms->contactid = $this->contactid; + $sms->project = $this->fk_project; + + $res = $sms->SmsSend(); if ($res <= 0) { $this->error = $sms->error; dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR); - } else { + } + else + { dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG); //var_dump($res); // 1973128 if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res); } - } elseif (!empty($conf->global->MAIN_SMS_SENDMODE)) // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module' + } + elseif (!empty($conf->global->MAIN_SMS_SENDMODE)) // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module' + { + $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE); + $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); + dol_include_once('/'.$module.'/class/'.$classfile.'.class.php'); + try + { + $classname = ucfirst($classfile); + $sms = new $classname($this->db); + $sms->expe = $this->addr_from; + $sms->dest = $this->addr_to; + $sms->deferred = $this->deferred; + $sms->priority = $this->priority; + $sms->class = $this->class; + $sms->message = $this->message; + $sms->nostop = $this->nostop; + + $sms->socid = $this->socid; + $sms->contactid = $this->contactid; + $sms->fk_project = $this->fk_project; + + $res = $sms->SmsSend(); + + $this->error = $sms->error; + $this->errors = $sms->errors; + if ($res <= 0) + { + dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR); + } + else + { + dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG); + //var_dump($res); // 1973128 + if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res); + } + } + catch (Exception $e) + { + dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); + } + } + else { - $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE); - $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); - dol_include_once('/'.$module.'/class/'.$classfile.'.class.php'); - try { - $classname = ucfirst($classfile); - $sms = new $classname($this->db); - $sms->expe = $this->addr_from; - $sms->dest = $this->addr_to; - $sms->deferred = $this->deferred; - $sms->priority = $this->priority; - $sms->class = $this->class; - $sms->message = $this->message; - $sms->nostop = $this->nostop; - - $sms->socid = $this->socid; - $sms->contact_id = $this->contact_id; - $sms->fk_project = $this->fk_project; - - $res = $sms->SmsSend(); - - $this->error = $sms->error; - $this->errors = $sms->errors; - if ($res <= 0) - { - dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR); - } else { - dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG); - //var_dump($res); // 1973128 - if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res); - } - } catch (Exception $e) - { - dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); - } - } else { // Send sms method not correctly defined // -------------------------------------- return 'Bad value for MAIN_SMS_SENDMODE constant'; } - } else { + } + else + { $this->error = 'No sms sent. Feature is disabled by option MAIN_DISABLE_ALL_SMS'; dol_syslog("CSMSFile::sendfile: ".$this->error, LOG_WARNING); } @@ -198,17 +209,17 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Write content of a SendSms request into a dump file (mode = all) - * Used for debugging. - * - * @return void - */ - public function dump_sms() - { - // phpcs:enable - global $conf, $dolibarr_main_data_root; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Write content of a SendSms request into a dump file (mode = all) + * Used for debugging. + * + * @return void + */ + public function dump_sms() + { + // phpcs:enable + global $conf, $dolibarr_main_data_root; if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir { @@ -229,29 +240,29 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Write content of a SendSms result into a dump file (mode = all) - * Used for debugging. - * - * @param int $result Result of sms sending - * @return void - */ - public function dump_sms_result($result) - { - // phpcs:enable - global $conf, $dolibarr_main_data_root; - - if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir - { - $outputfile = $dolibarr_main_data_root."/dolibarr_sms.log"; - $fp = fopen($outputfile, "a+"); - - fputs($fp, "\nResult id=".$result); - - fclose($fp); - if (!empty($conf->global->MAIN_UMASK)) - @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); - } - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Write content of a SendSms result into a dump file (mode = all) + * Used for debugging. + * + * @param int $result Result of sms sending + * @return void + */ + public function dump_sms_result($result) + { + // phpcs:enable + global $conf, $dolibarr_main_data_root; + + if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir + { + $outputfile = $dolibarr_main_data_root."/dolibarr_sms.log"; + $fp = fopen($outputfile, "a+"); + + fputs($fp, "\nResult id=".$result); + + fclose($fp); + if (!empty($conf->global->MAIN_UMASK)) + @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); + } + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_antivir.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_antivir.class.php @@ -45,9 +45,9 @@ public $output; /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * Constructor @@ -59,7 +59,7 @@ $this->db = $db; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Scan a file with antivirus. * This function runs the command defined in setup. This antivirus command must return 0 if OK. @@ -70,24 +70,24 @@ */ public function dol_avscan_file($file) { - // phpcs:enable + // phpcs:enable global $conf; $return = 0; if (preg_match('/\.virus$/i', $file)) { - $this->errors[] = 'File has an extension saying file is a virus'; - return -97; + $this->errors[] = 'File has an extension saying file is a virus'; + return -97; } $fullcommand = $this->getCliCommand($file); //$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"'; - $fullcommand .= ' 2>&1'; // This is to get error output + $fullcommand .= ' 2>&1'; // This is to get error output $output = array(); $return_var = 0; - $safemode = ini_get("safe_mode"); + $safemode = ini_get("safe_mode"); // Create a clean fullcommand dol_syslog("AntiVir::dol_avscan_file Run command=".$fullcommand." with safe_mode ".($safemode ? "on" : "off")); // Run CLI command. If run of Windows, you can get return with echo %ERRORLEVEL% @@ -95,7 +95,7 @@ if (is_null($output)) $output = array(); - //print "x".$lastline." - ".join(',',$output)." - ".$return_var."y";exit; + //print "x".$lastline." - ".join(',',$output)." - ".$return_var."y";exit; /* $outputfile=$conf->admin->dir_temp.'/dol_avscan_file.out.'.session_id(); @@ -181,7 +181,7 @@ $ret = $command.' '.$param; //$ret=$command.' '.$param.' 2>&1'; - //print "xx".$ret."xx";exit; + //print "xx".$ret."xx";exit; return $ret; } --- /tmp/dsg/dolibarr/htdocs/core/class/github_canvas.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_canvas.class.php @@ -29,9 +29,9 @@ class Canvas { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -45,16 +45,16 @@ public $actiontype; - public $dirmodule; // Module directory - public $targetmodule; // Module concerned by canvas (ex: thirdparty, contact, ...) - public $canvas; // Name of canvas (ex: company, individual, product, service, ...) - public $card; // Tab (sub-canvas) - - public $template_dir; // Initialized by getCanvas with templates directory - public $control; // Initialized by getCanvas with controller instance - - - /** + public $dirmodule; // Module directory + public $targetmodule; // Module concerned by canvas (ex: thirdparty, contact, ...) + public $canvas; // Name of canvas (ex: company, individual, product, service, ...) + public $card; // Tab (sub-canvas) + + public $template_dir; // Initialized by getCanvas with templates directory + public $control; // Initialized by getCanvas with controller instance + + + /** * Constructor * * @param DoliDB $db Database handler @@ -75,11 +75,11 @@ */ private function _cleanaction($action) { - $newaction = $action; - if ($newaction == 'add') $newaction = 'create'; - if ($newaction == 'update') $newaction = 'edit'; - if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction = 'view'; - return $newaction; + $newaction = $action; + if ($newaction == 'add') $newaction = 'create'; + if ($newaction == 'update') $newaction = 'edit'; + if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction = 'view'; + return $newaction; } @@ -96,45 +96,45 @@ global $conf, $langs; // Set properties with value specific to dolibarr core: this->targetmodule, this->card, this->canvas - $this->targetmodule = $module; - $this->canvas = $canvas; - $this->card = $card; - $this->dirmodule = $module; - // Correct values if canvas is into an external module + $this->targetmodule = $module; + $this->canvas = $canvas; + $this->card = $card; + $this->dirmodule = $module; + // Correct values if canvas is into an external module if (preg_match('/^([^@]+)@([^@]+)$/i', $canvas, $regs)) { - $this->canvas = $regs[1]; - $this->dirmodule = $regs[2]; + $this->canvas = $regs[1]; + $this->dirmodule = $regs[2]; } // For compatibility - if ($this->dirmodule == 'thirdparty') { $this->dirmodule = 'societe'; } - - // Control file + if ($this->dirmodule == 'thirdparty') { $this->dirmodule = 'societe'; } + + // Control file $controlclassfile = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/actions_'.$this->card.'_'.$this->canvas.'.class.php'); if (file_exists($controlclassfile)) { - // Include actions class (controller) - $this->control_file = $controlclassfile; - require_once $controlclassfile; - - // Instantiate actions class (controller) - $controlclassname = 'Actions'.ucfirst($this->card).ucfirst($this->canvas); - $this->control = new $controlclassname($this->db, $this->dirmodule, $this->targetmodule, $this->canvas, $this->card); + // Include actions class (controller) + $this->control_file = $controlclassfile; + require_once $controlclassfile; + + // Instantiate actions class (controller) + $controlclassname = 'Actions'.ucfirst($this->card).ucfirst($this->canvas); + $this->control = new $controlclassname($this->db, $this->dirmodule, $this->targetmodule, $this->canvas, $this->card); } // Template dir $this->template_dir = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/tpl/'); - if (!is_dir($this->template_dir)) - { - $this->template_dir = ''; - } - - //print 'dimodule='.$dirmodule.' canvas='.$this->canvas.'
'; - //print ' => template_dir='.$this->template_dir.'
'; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** + if (!is_dir($this->template_dir)) + { + $this->template_dir = ''; + } + + //print 'dimodule='.$dirmodule.' canvas='.$this->canvas.'
'; + //print ' => template_dir='.$this->template_dir.'
'; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** * Shared method for canvas to assign values for templates * * @param string $action Action string @@ -144,25 +144,25 @@ */ public function assign_values(&$action = 'view', $id = 0, $ref = '') { - // phpcs:enable + // phpcs:enable if (method_exists($this->control, 'assign_values')) $this->control->assign_values($action, $id, $ref); } - /** - * Return the template to display canvas (if it exists) + /** + * Return the template to display canvas (if it exists) * * @param string $action Action code - * @return int 0=Canvas template file does not exist, 1=Canvas template file exists - */ - public function displayCanvasExists($action) - { - if (empty($this->template_dir)) return 0; - - if (file_exists($this->template_dir.(!empty($this->card) ? $this->card.'_' : '').$this->_cleanaction($action).'.tpl.php')) return 1; - else return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + * @return int 0=Canvas template file does not exist, 1=Canvas template file exists + */ + public function displayCanvasExists($action) + { + if (empty($this->template_dir)) return 0; + + if (file_exists($this->template_dir.(!empty($this->card) ? $this->card.'_' : '').$this->_cleanaction($action).'.tpl.php')) return 1; + else return 0; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Display a canvas page. This will include the template for output. * Variables used by templates may have been defined or loaded before into the assign_values function. @@ -172,7 +172,7 @@ */ public function display_canvas($action) { - // phpcs:enable + // phpcs:enable global $db, $conf, $langs, $user, $canvas; global $form, $formfile; @@ -191,12 +191,12 @@ */ public function hasActions() { - return (is_object($this->control)); + return (is_object($this->control)); } /** * Shared method for canvas to execute actions. - * @deprecated Use the doActions of hooks instead of this. + * @deprecated Use the doActions of hooks instead of this. * This function is called if you add a doActions class inside your canvas. Try to not * do that and add action code into a hook instead. * --- /tmp/dsg/dolibarr/htdocs/core/class/github_ccountry.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_ccountry.class.php @@ -33,9 +33,9 @@ class Ccountry // extends CommonObject { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -50,7 +50,7 @@ public $element = 'ccountry'; //!< Id that identify managed objects public $table_element = 'c_country'; //!< Name of table without prefix where object is stored - /** + /** * @var int ID */ public $id; @@ -59,9 +59,9 @@ public $code_iso; /** - * @var string Countries label - */ - public $label; + * @var string Countries label + */ + public $label; public $active; @@ -70,27 +70,27 @@ ); - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Create object into database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + + /** + * Create object into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -102,14 +102,14 @@ // Check parameters // Put here code to add control on parameters values - // Insert request + // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country("; $sql .= "rowid,"; $sql .= "code,"; $sql .= "code_iso,"; $sql .= "label,"; $sql .= "active"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " ".(!isset($this->rowid) ? 'NULL' : "'".$this->db->escape($this->rowid)."'").","; $sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").","; $sql .= " ".(!isset($this->code_iso) ? 'NULL' : "'".$this->db->escape($this->code_iso)."'").","; @@ -120,90 +120,93 @@ $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_country"); - } - - // Commit or rollback - if ($error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_country"); + } + + // Commit or rollback + if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from database - * - * @param int $id Id object - * @param string $code Code - * @param string $code_iso Code ISO - * @return int >0 if OK, 0 if not found, <0 if KO - */ - public function fetch($id, $code = '', $code_iso = '') - { - $sql = "SELECT"; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param string $code Code + * @param string $code_iso Code ISO + * @return int >0 if OK, 0 if not found, <0 if KO + */ + public function fetch($id, $code = '', $code_iso = '') + { + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.code,"; $sql .= " t.code_iso,"; $sql .= " t.label,"; $sql .= " t.active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_country as t"; - if ($id) $sql .= " WHERE t.rowid = ".((int) $id); - elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape(strtoupper($code))."'"; - elseif ($code_iso) $sql .= " WHERE t.code_iso = '".$this->db->escape(strtoupper($code_iso))."'"; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - if ($obj) { - $this->id = $obj->rowid; - $this->code = $obj->code; - $this->code_iso = $obj->code_iso; - $this->label = $obj->label; - $this->active = $obj->active; - } - - $this->db->free($resql); - return 1; - } else { - return 0; - } - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Update object into database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) - { - global $conf, $langs; + $sql .= " FROM ".MAIN_DB_PREFIX."c_country as t"; + if ($id) $sql .= " WHERE t.rowid = ".$id; + elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; + elseif ($code_iso) $sql .= " WHERE t.code_iso = '".$this->db->escape($code_iso)."'"; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->code = $obj->code; + $this->code_iso = $obj->code_iso; + $this->label = $obj->label; + $this->active = $obj->active; + + $this->db->free($resql); + return 1; + } + else { + return 0; + } + } + else + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update object into database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -216,44 +219,46 @@ // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET"; $sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").","; $sql .= " code_iso=".(isset($this->code_iso) ? "'".$this->db->escape($this->code_iso)."'" : "null").","; $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " active=".(isset($this->active) ? $this->active : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } - } + } /** * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -266,37 +271,39 @@ dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } } - /** - * Return a link to the object card (with optionaly the picto) - * - * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) - * @param string $option On what the link point to ('nolink', ...) - * @param int $notooltip 1=Disable tooltip - * @param string $morecss Add more css on link - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) - { - global $langs; - return $langs->trans($this->label); - } + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $langs; + return $langs->trans($this->label); + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_comment.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_comment.class.php @@ -32,13 +32,10 @@ public $table_element = 'comment'; /** - * @var int ID of parent key (it's not the name of a field) - */ - public $fk_element; - - /** - * @var string element type - */ + * @var int Field with ID of parent key if this field has a parent + */ + public $fk_element = ''; + public $element_type; /** @@ -47,27 +44,27 @@ public $description; /** - * Date modification record (tms) - * - * @var integer - */ + * Date modification record (tms) + * + * @var integer + */ public $tms; /** - * Date creation record (datec) - * - * @var integer - */ - public $datec; - - /** - * @var int ID - */ + * Date creation record (datec) + * + * @var integer + */ + public $datec; + + /** + * @var int ID + */ public $fk_user_author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_modif; /** @@ -75,16 +72,10 @@ */ public $entity; - /** - * @var string import key - */ public $import_key; public $comments = array(); - /** - * @var Comment Object oldcopy - */ public $oldcopy; @@ -140,32 +131,34 @@ dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); - } - - if (!$error) { + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + if (!$error) + { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - if (!$notrigger) { + if (!$notrigger) + { // Call trigger $result = $this->call_trigger('TASK_COMMENT_CREATE', $user); - if ($result < 0) { - $error++; - } + if ($result < 0) { $error++; } // End call triggers } } // Commit or rollback - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return $this->id; } @@ -195,14 +188,16 @@ $sql .= " c.entity,"; $sql .= " c.import_key"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c"; - $sql .= " WHERE c.rowid = ".((int) $id); + $sql .= " WHERE c.rowid = ".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) { + if ($resql) + { $num_rows = $this->db->num_rows($resql); - if ($num_rows) { + if ($num_rows) + { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -219,12 +214,11 @@ $this->db->free($resql); - if ($num_rows) { - return 1; - } else { - return 0; - } - } else { + if ($num_rows) return 1; + else return 0; + } + else + { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -244,12 +238,8 @@ $error = 0; // Clean parameters - if (isset($this->fk_element)) { - $this->fk_project = (int) trim($this->fk_element); - } - if (isset($this->description)) { - $this->description = trim($this->description); - } + if (isset($this->fk_element)) $this->fk_project = (int) trim($this->fk_element); + if (isset($this->description)) $this->description = trim($this->description); // Update request @@ -267,30 +257,32 @@ dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); - } - - if (!$error) { - if (!$notrigger) { + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + if (!$error) + { + if (!$notrigger) + { // Call trigger $result = $this->call_trigger('TASK_COMMENT_MODIFY', $user); - if ($result < 0) { - $error++; - } + if ($result < 0) { $error++; } // End call triggers } } // Commit or rollback - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } @@ -317,24 +309,24 @@ $sql .= " WHERE rowid=".$this->id; $resql = $this->db->query($sql); - if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); - } - - if (!$error) { - if (!$notrigger) { + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + if (!$error) + { + if (!$notrigger) + { // Call trigger $result = $this->call_trigger('TASK_COMMENT_DELETE', $user); - if ($result < 0) { - $error++; - } + if ($result < 0) { $error++; } // End call triggers } } // Commit or rollback - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -363,22 +355,25 @@ $sql .= " c.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c"; $sql .= " WHERE c.fk_element = ".$fk_element; - $sql .= " AND c.element_type = '".$this->db->escape($element_type)."'"; + $sql .= " AND c.element_type = '".$db->escape($element_type)."'"; $sql .= " AND c.entity = ".$conf->entity; $sql .= " ORDER BY c.tms DESC"; dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num_rows = $this->db->num_rows($resql); - if ($num_rows > 0) { - while ($obj = $this->db->fetch_object($resql)) { + $resql = $db->query($sql); + if ($resql) + { + $num_rows = $db->num_rows($resql); + if ($num_rows > 0) + { + while ($obj = $db->fetch_object($resql)) + { $comment = new self($db); $comment->fetch($obj->rowid); $this->comments[] = $comment; } } - $this->db->free($resql); + $db->free($resql); } else { $this->errors[] = "Error ".$this->db->lasterror(); return -1; --- /tmp/dsg/dolibarr/htdocs/core/class/github_commondocgenerator.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commondocgenerator.class.php @@ -5,7 +5,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Marcos García * Copyright (C) 2016 Charlie Benke - * Copyright (C) 2018-2020 Frédéric France + * Copyright (C) 2018 Frédéric France * Copyright (C) 2020 Josep Lluís Amador * * This program is free software; you can redistribute it and/or modify @@ -40,250 +40,199 @@ */ public $error = ''; + /** + * @var string[] Array of error strings + */ + public $errors = array(); + /** - * @var string[] Array of error strings - */ - public $errors = array(); - - /** - * @var DoliDB Database handler. - */ + * @var DoliDB Database handler. + */ protected $db; - /** - * @var Extrafields object - */ + /** + * @var Extrafields object + */ public $extrafieldsCache; /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param User $user User - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_user($user, $outputlangs) - { - // phpcs:enable - global $conf, $extrafields; - - $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; - - $array_user = array( - 'myuser_lastname'=>$user->lastname, - 'myuser_firstname'=>$user->firstname, - 'myuser_fullname'=>$user->getFullName($outputlangs, 1), - 'myuser_login'=>$user->login, - 'myuser_phone'=>$user->office_phone, - 'myuser_address'=>$user->address, - 'myuser_zip'=>$user->zip, - 'myuser_town'=>$user->town, - 'myuser_country'=>$user->country, - 'myuser_country_code'=>$user->country_code, - 'myuser_state'=>$user->state, - 'myuser_state_code'=>$user->state_code, - 'myuser_fax'=>$user->office_fax, - 'myuser_mobile'=>$user->user_mobile, - 'myuser_email'=>$user->email, - 'myuser_logo'=>$logotouse, - 'myuser_job'=>$user->job, - 'myuser_web'=>'' // url not exist in $user object - ); - // Retrieve extrafields - if (is_array($user->array_options) && count($user->array_options)) { - $array_user = $this->fill_substitutionarray_with_extrafields($user, $array_user, $extrafields, 'myuser', $outputlangs); - } - return $array_user; - } - - - /** - * Define array with couple substitution key => substitution value - * - * @param Adherent $member Member - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function getSubstitutionarrayMember($member, $outputlangs) - { - global $conf, $extrafields; - - if ($member->photo) { - $logotouse = $conf->adherent->dir_output.'/'.get_exdir(0, 0, 0, 1, $member, 'user').'/photos/'.$member->photo; - } else { - $logotouse = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png'; - } - - $array_member = array( - 'mymember_lastname' => $member->lastname, - 'mymember_firstname' => $member->firstname, - 'mymember_fullname' => $member->getFullName($outputlangs, 1), - 'mymember_login' => $member->login, - 'mymember_address' => $member->address, - 'mymember_zip' => $member->zip, - 'mymember_town' => $member->town, - 'mymember_country_code' => $member->country_code, - 'mymember_country' => $member->country, - 'mymember_state_code' => $member->state_code, - 'mymember_state' => $member->state, - 'mymember_phone_perso' => $member->phone_perso, - 'mymember_phone_pro' => $member->phone, - 'mymember_phone_mobile' => $member->phone_mobile, - 'mymember_email' => $member->email, - 'mymember_logo' => $logotouse, - 'mymember_gender' => $member->gender, - 'mymember_birth_locale' => dol_print_date($member->birth, 'day', 'tzuser', $outputlangs), - 'mymember_birth' => dol_print_date($member->birth, 'day', 'tzuser'), - ); - // Retrieve extrafields - if (is_array($member->array_options) && count($member->array_options)) { - $array_member = $this->fill_substitutionarray_with_extrafields($member, $array_member, $extrafields, 'mymember', $outputlangs); - } - return $array_member; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Societe $mysoc Object thirdparty - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_mysoc($mysoc, $outputlangs) - { - // phpcs:enable - global $conf; - - if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) - { - $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); - } - if (empty($mysoc->country) && !empty($mysoc->country_code)) - { - $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); - } - if (empty($mysoc->state) && !empty($mysoc->state_code)) - { - $mysoc->state = getState($mysoc->state_code, 0); - } - - $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; - - return array( - 'mycompany_logo'=>$logotouse, - 'mycompany_name'=>$mysoc->name, - 'mycompany_email'=>$mysoc->email, - 'mycompany_phone'=>$mysoc->phone, - 'mycompany_fax'=>$mysoc->fax, - 'mycompany_address'=>$mysoc->address, - 'mycompany_zip'=>$mysoc->zip, - 'mycompany_town'=>$mysoc->town, - 'mycompany_country'=>$mysoc->country, - 'mycompany_country_code'=>$mysoc->country_code, - 'mycompany_state'=>$mysoc->state, - 'mycompany_state_code'=>$mysoc->state_code, - 'mycompany_web'=>$mysoc->url, - 'mycompany_juridicalstatus'=>$mysoc->forme_juridique, - 'mycompany_managers'=>$mysoc->managers, - 'mycompany_capital'=>$mysoc->capital, - 'mycompany_barcode'=>$mysoc->barcode, - 'mycompany_idprof1'=>$mysoc->idprof1, - 'mycompany_idprof2'=>$mysoc->idprof2, - 'mycompany_idprof3'=>$mysoc->idprof3, - 'mycompany_idprof4'=>$mysoc->idprof4, - 'mycompany_idprof5'=>$mysoc->idprof5, - 'mycompany_idprof6'=>$mysoc->idprof6, - 'mycompany_vatnumber'=>$mysoc->tva_intra, + */ + public function __construct($db) + { + $this->db = $db; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param User $user User + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_user($user, $outputlangs) + { + // phpcs:enable + global $conf; + + $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; + + return array( + 'myuser_lastname'=>$user->lastname, + 'myuser_firstname'=>$user->firstname, + 'myuser_fullname'=>$user->getFullName($outputlangs, 1), + 'myuser_login'=>$user->login, + 'myuser_phone'=>$user->office_phone, + 'myuser_address'=>$user->address, + 'myuser_zip'=>$user->zip, + 'myuser_town'=>$user->town, + 'myuser_country'=>$user->country, + 'myuser_country_code'=>$user->country_code, + 'myuser_state'=>$user->state, + 'myuser_state_code'=>$user->state_code, + 'myuser_fax'=>$user->office_fax, + 'myuser_mobile'=>$user->user_mobile, + 'myuser_email'=>$user->email, + 'myuser_logo'=>$logotouse, + 'myuser_job'=>$user->job, + 'myuser_web'=>'' // url not exist in $user object + ); + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Societe $mysoc Object thirdparty + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_mysoc($mysoc, $outputlangs) + { + // phpcs:enable + global $conf; + + if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) + { + $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); + } + if (empty($mysoc->country) && !empty($mysoc->country_code)) + { + $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); + } + if (empty($mysoc->state) && !empty($mysoc->state_code)) + { + $mysoc->state = getState($mysoc->state_code, 0); + } + + $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; + + return array( + 'mycompany_logo'=>$logotouse, + 'mycompany_name'=>$mysoc->name, + 'mycompany_email'=>$mysoc->email, + 'mycompany_phone'=>$mysoc->phone, + 'mycompany_fax'=>$mysoc->fax, + 'mycompany_address'=>$mysoc->address, + 'mycompany_zip'=>$mysoc->zip, + 'mycompany_town'=>$mysoc->town, + 'mycompany_country'=>$mysoc->country, + 'mycompany_country_code'=>$mysoc->country_code, + 'mycompany_state'=>$mysoc->state, + 'mycompany_state_code'=>$mysoc->state_code, + 'mycompany_web'=>$mysoc->url, + 'mycompany_juridicalstatus'=>$mysoc->forme_juridique, + 'mycompany_managers'=>$mysoc->managers, + 'mycompany_capital'=>$mysoc->capital, + 'mycompany_barcode'=>$mysoc->barcode, + 'mycompany_idprof1'=>$mysoc->idprof1, + 'mycompany_idprof2'=>$mysoc->idprof2, + 'mycompany_idprof3'=>$mysoc->idprof3, + 'mycompany_idprof4'=>$mysoc->idprof4, + 'mycompany_idprof5'=>$mysoc->idprof5, + 'mycompany_idprof6'=>$mysoc->idprof6, + 'mycompany_vatnumber'=>$mysoc->tva_intra, 'mycompany_object'=>$mysoc->object, - 'mycompany_note_private'=>$mysoc->note_private, - //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties - ); - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Societe $object Object - * @param Translate $outputlangs Language object for output - * @param string $array_key Name of the key for return array - * @return array Array of substitution key->code - */ - public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company') - { - // phpcs:enable - global $conf, $extrafields; - - if (empty($object->country) && !empty($object->country_code)) - { - $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); - } - if (empty($object->state) && !empty($object->state_code)) - { - $object->state = getState($object->state_code, 0); - } - - $array_thirdparty = array( - 'company_name'=>$object->name, - 'company_name_alias' => $object->name_alias, - 'company_email'=>$object->email, - 'company_phone'=>$object->phone, - 'company_fax'=>$object->fax, - 'company_address'=>$object->address, - 'company_zip'=>$object->zip, - 'company_town'=>$object->town, - 'company_country'=>$object->country, - 'company_country_code'=>$object->country_code, - 'company_state'=>$object->state, - 'company_state_code'=>$object->state_code, - 'company_web'=>$object->url, - 'company_barcode'=>$object->barcode, - 'company_vatnumber'=>$object->tva_intra, - 'company_customercode'=>$object->code_client, - 'company_suppliercode'=>$object->code_fournisseur, - 'company_customeraccountancycode'=>$object->code_compta, - 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, - 'company_juridicalstatus'=>$object->forme_juridique, - 'company_outstanding_limit'=>$object->outstanding_limit, - 'company_capital'=>$object->capital, - 'company_idprof1'=>$object->idprof1, - 'company_idprof2'=>$object->idprof2, - 'company_idprof3'=>$object->idprof3, - 'company_idprof4'=>$object->idprof4, - 'company_idprof5'=>$object->idprof5, - 'company_idprof6'=>$object->idprof6, - 'company_note_public'=>$object->note_public, - 'company_note_private'=>$object->note_private, - 'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''), - 'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '') - ); - - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); - - $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs); - } + 'mycompany_note_private'=>$mysoc->note_private, + //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties + ); + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Societe $object Object + * @param Translate $outputlangs Language object for output + * @param string $array_key Name of the key for return array + * @return array Array of substitution key->code + */ + public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company') + { + // phpcs:enable + global $conf, $extrafields; + + if (empty($object->country) && !empty($object->country_code)) + { + $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); + } + if (empty($object->state) && !empty($object->state_code)) + { + $object->state = getState($object->state_code, 0); + } + + $array_thirdparty = array( + 'company_name'=>$object->name, + 'company_name_alias' => $object->name_alias, + 'company_email'=>$object->email, + 'company_phone'=>$object->phone, + 'company_fax'=>$object->fax, + 'company_address'=>$object->address, + 'company_zip'=>$object->zip, + 'company_town'=>$object->town, + 'company_country'=>$object->country, + 'company_country_code'=>$object->country_code, + 'company_state'=>$object->state, + 'company_state_code'=>$object->state_code, + 'company_web'=>$object->url, + 'company_barcode'=>$object->barcode, + 'company_vatnumber'=>$object->tva_intra, + 'company_customercode'=>$object->code_client, + 'company_suppliercode'=>$object->code_fournisseur, + 'company_customeraccountancycode'=>$object->code_compta, + 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, + 'company_juridicalstatus'=>$object->forme_juridique, + 'company_outstanding_limit'=>$object->outstanding_limit, + 'company_capital'=>$object->capital, + 'company_idprof1'=>$object->idprof1, + 'company_idprof2'=>$object->idprof2, + 'company_idprof3'=>$object->idprof3, + 'company_idprof4'=>$object->idprof4, + 'company_idprof5'=>$object->idprof5, + 'company_idprof6'=>$object->idprof6, + 'company_note_public'=>$object->note_public, + 'company_note_private'=>$object->note_private, + 'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''), + 'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '') + ); + + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); + + $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs); + } return $array_thirdparty; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * @@ -292,9 +241,9 @@ * @param string $array_key Name of the key for return array * @return array Array of substitution key->code */ - public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable + public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable global $conf, $extrafields; if (empty($object->country) && !empty($object->country_code)) @@ -336,67 +285,67 @@ $array_key.'_civility' => $object->civility, ); - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); - - $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs); - } + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); + + $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs); + } return $array_contact; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_other($outputlangs) - { - // phpcs:enable - global $conf; - - $now = dol_now('gmt'); // gmt - $array_other = array( - // Date in default language - 'current_date'=>dol_print_date($now, 'day', 'tzuser'), - 'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'), + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_other($outputlangs) + { + // phpcs:enable + global $conf; + + $now = dol_now('gmt'); // gmt + $array_other = array( + // Date in default language + 'current_date'=>dol_print_date($now, 'day', 'tzuser'), + 'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'), 'current_server_date'=>dol_print_date($now, 'day', 'tzserver'), 'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'), - // Date in requested output language - 'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs), + // Date in requested output language + 'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs), 'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs), 'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs), 'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs), - ); - - - foreach ($conf->global as $key => $val) - { - if (isASecretKey($key)) $newval = '*****forbidden*****'; - else $newval = $val; - $array_other['__['.$key.']__'] = $newval; - } - - return $array_other; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + ); + + + foreach ($conf->global as $key => $val) + { + if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****'; + else $newval = $val; + $array_other['__['.$key.']__'] = $newval; + } + + return $array_other; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * * @param Object $object Main object to use as data source * @param Translate $outputlangs Lang object to use for output - * @param string $array_key Name of the key for return array + * @param string $array_key Name of the key for return array * @return array Array of substitution */ public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object') { - // phpcs:enable + // phpcs:enable global $conf, $extrafields; $sumpayed = $sumdeposit = $sumcreditnote = ''; @@ -432,11 +381,11 @@ $array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), $array_key.'_source_invoice_ref'=>$invoice_source->ref, // Dates - $array_key.'_hour'=>dol_print_date($date, 'hour'), + $array_key.'_hour'=>dol_print_date($date, 'hour'), $array_key.'_date'=>dol_print_date($date, 'day'), $array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'), $array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''), - $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), + $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), $array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''), $array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''), @@ -448,8 +397,6 @@ $array_key.'_payment_term_code'=>$object->cond_reglement_code, $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)), - $array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''), - $array_key.'_bank_iban'=>$bank_account->iban, $array_key.'_bank_bic'=>$bank_account->bic, @@ -467,8 +414,8 @@ $array_key.'_multicurrency_code' => price2num($object->multicurrency_code), $array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx), - $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht), - $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva), + $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht), + $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva), $array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc), $array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs), $array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs), @@ -523,11 +470,11 @@ $totalUp = 0; foreach ($object->lines as $line) { - // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility + // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0; $resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]); - // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) + // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) $vatformated = vatrate($line->tva_tx); if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0; $resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva; @@ -565,7 +512,7 @@ return $resarray; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * @@ -576,24 +523,21 @@ */ public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0) { - // phpcs:enable + // phpcs:enable global $conf; $resarray = array( 'line_pos' => $linenumber, 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), - - 'line_product_ref'=>(empty($line->product_ref) ? '' : $line->product_ref), - 'line_product_ref_fourn'=>(empty($line->ref_fourn) ? '' : $line->ref_fourn), // for supplier doc lines - 'line_product_label'=>(empty($line->product_label) ? '' : $line->product_label), - 'line_product_type'=>(empty($line->product_type) ? '' : $line->product_type), - 'line_product_barcode'=>(empty($line->product_barcode) ? '' : $line->product_barcode), - + 'line_product_ref'=>$line->product_ref, + 'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines + 'line_product_label'=>$line->product_label, + 'line_product_type'=>$line->product_type, 'line_desc'=>$line->desc, 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), - 'line_localtax1_rate'=>vatrate($line->localtax1_tx), - 'line_localtax2_rate'=>vatrate($line->localtax1_tx), - 'line_up'=>price2num($line->subprice), + 'line_localtax1_rate'=>vatrate($line->localtax1_tx), + 'line_localtax2_rate'=>vatrate($line->localtax1_tx), + 'line_up'=>price2num($line->subprice), 'line_up_locale'=>price($line->subprice, 0, $outputlangs), 'line_total_up'=>price2num($line->subprice * $line->qty), 'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs), @@ -605,31 +549,31 @@ 'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs), 'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs), 'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs), - // Dates + // Dates 'line_date_start'=>dol_print_date($line->date_start, 'day'), 'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs), - 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), - 'line_date_end'=>dol_print_date($line->date_end, 'day'), - 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), - 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), - - 'line_multicurrency_code' => price2num($line->multicurrency_code), - 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), - 'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht), - 'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva), - 'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc), - 'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs), - 'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs), - 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), - 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), + 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), + 'line_date_end'=>dol_print_date($line->date_end, 'day'), + 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), + 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), + + 'line_multicurrency_code' => price2num($line->multicurrency_code), + 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), + 'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht), + 'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva), + 'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc), + 'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs), + 'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs), + 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), + 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) + // Units + if ($conf->global->PRODUCT_USE_UNITS) { - $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); - $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); - } + $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); + } // Retrieve extrafields $extrafieldkey = $line->table_element; @@ -639,20 +583,20 @@ $extrafields->fetch_name_optionals_label($extrafieldkey, true); $line->fetch_optionals(); - $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); - - // Check if the current line belongs to a supplier order - if (get_class($line) == 'CommandeFournisseurLigne') - { - // Add the product supplier extrafields to the substitutions - $extrafields->fetch_name_optionals_label("product_fournisseur_price"); - $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; + $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + + // Check if the current line belongs to a supplier order + if (get_class($line) == 'CommandeFournisseurLigne') + { + // Add the product supplier extrafields to the substitutions + $extrafields->fetch_name_optionals_label("product_fournisseur_price"); + $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; if (!empty($extralabels) && is_array($extralabels)) { $columns = ""; - foreach ($extralabels as $key => $label) + foreach ($extralabels as $key) { $columns .= "$key, "; } @@ -660,20 +604,20 @@ if ($columns != "") { $columns = substr($columns, 0, strlen($columns) - 2); - $resql = $this->db->query("SELECT ".$columns." FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields AS ex INNER JOIN ".MAIN_DB_PREFIX."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$this->db->escape($line->ref_supplier)."'"); + $resql = $this->db->query("SELECT $columns FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields AS ex INNER JOIN ".MAIN_DB_PREFIX."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$line->ref_supplier."'"); if ($this->db->num_rows($resql) > 0) { $resql = $this->db->fetch_object($resql); - foreach ($extralabels as $key => $label) + foreach ($extralabels as $key) { $resarray['line_product_supplier_'.$key] = $resql->{$key}; } } } } - } + } // Load product data optional fields to the line -> enables to use "line_options_{extrafield}" if (isset($line->fk_product) && $line->fk_product > 0) @@ -687,173 +631,158 @@ return $resarray; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Expedition $object Main object to use as data source - * @param Translate $outputlangs Lang object to use for output - * @param array $array_key Name of the key for return array - * @return array Array of substitution - */ - public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable - global $conf, $extrafields; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Expedition $object Main object to use as data source + * @param Translate $outputlangs Lang object to use for output + * @param array $array_key Name of the key for return array + * @return array Array of substitution + */ + public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable + global $conf, $extrafields; dol_include_once('/core/lib/product.lib.php'); $object->list_delivery_methods($object->shipping_method_id); $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); - $array_shipment = array( - $array_key.'_id'=>$object->id, - $array_key.'_ref'=>$object->ref, - $array_key.'_ref_ext'=>$object->ref_ext, - $array_key.'_ref_customer'=>$object->ref_customer, - $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'), - $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'), - $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), - $array_key.'_total_ht'=>price($object->total_ht), - $array_key.'_total_vat'=>price($object->total_tva), - $array_key.'_total_ttc'=>price($object->total_ttc), - $array_key.'_total_discount_ht' => price($object->getTotalDiscount()), - $array_key.'_note_private'=>$object->note_private, - $array_key.'_note'=>$object->note_public, - $array_key.'_tracking_number'=>$object->tracking_number, - $array_key.'_tracking_url'=>$object->tracking_url, - $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'], - $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units), - $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units), - $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units), - $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units), - $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'), - ); - - // Add vat by rates - foreach ($object->lines as $line) - { - if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; - $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; - } - - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); - - $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs); - } - - // Add infor from $object->xxx where xxx has been loaded by fetch_origin() of shipment - if (!empty($object->commande) && is_object($object->commande)) { - $array_shipment['order_ref'] = $object->commande->ref; - $array_shipment['order_ref_customer'] = $object->commande->ref_customer; - } - - return $array_shipment; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param ExpeditionLigne $line Object line - * @param Translate $outputlangs Lang object to use for output - * @return array Substitution array - */ - public function get_substitutionarray_shipment_lines($line, $outputlangs) - { - // phpcs:enable - global $conf; - dol_include_once('/core/lib/product.lib.php'); - - $resarray = array( - 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), - 'line_product_ref'=>$line->product_ref, - 'line_product_label'=>$line->product_label, - 'line_desc'=>$line->desc, - 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), - 'line_up'=>price($line->subprice), - 'line_total_up'=>price($line->subprice * $line->qty), - 'line_qty'=>$line->qty, - 'line_qty_shipped'=>$line->qty_shipped, - 'line_qty_asked'=>$line->qty_asked, - 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), - 'line_price_ht'=>price($line->total_ht), - 'line_price_ttc'=>price($line->total_ttc), - 'line_price_vat'=>price($line->total_tva), - 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), - 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), - 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), - 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), - ); - - // Retrieve extrafields - $extrafieldkey = $line->element; - $array_key = "line"; - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $extrafields->fetch_name_optionals_label($extrafieldkey, true); - $line->fetch_optionals(); - - $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); - - // Load product data optional fields to the line -> enables to use "line_product_options_{extrafield}" - if (isset($line->fk_product) && $line->fk_product > 0) - { - $tmpproduct = new Product($this->db); - $result = $tmpproduct->fetch($line->fk_product); - foreach ($tmpproduct->array_options as $key=>$label) - $resarray["line_product_".$key] = $label; - } - - return $resarray; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Object $object Dolibarr Object - * @param Translate $outputlangs Language object for output - * @param boolean $recursive Want to fetch child array or child object - * @return array Array of substitution key->code - */ - public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true) - { - // phpcs:enable - $array_other = array(); - if (!empty($object)) { - foreach ($object as $key => $value) { - if (!empty($value)) { - if (!is_array($value) && !is_object($value)) { - $array_other['object_'.$key] = $value; - } - if (is_array($value) && $recursive) { - $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false); - } - } - } - } - return $array_other; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Fill array with couple extrafield key => extrafield value - * - * @param Object $object Object with extrafields (must have $object->array_options filled) - * @param array $array_to_fill Substitution array - * @param Extrafields $extrafields Extrafields object - * @param string $array_key Prefix for name of the keys into returned array - * @param Translate $outputlangs Lang object to use for output - * @return array Substitution array - */ - public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs) - { - // phpcs:enable + $array_shipment = array( + $array_key.'_id'=>$object->id, + $array_key.'_ref'=>$object->ref, + $array_key.'_ref_ext'=>$object->ref_ext, + $array_key.'_ref_customer'=>$object->ref_customer, + $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'), + $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'), + $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), + $array_key.'_total_ht'=>price($object->total_ht), + $array_key.'_total_vat'=>price($object->total_tva), + $array_key.'_total_ttc'=>price($object->total_ttc), + $array_key.'_total_discount_ht' => price($object->getTotalDiscount()), + $array_key.'_note_private'=>$object->note_private, + $array_key.'_note'=>$object->note_public, + $array_key.'_tracking_number'=>$object->tracking_number, + $array_key.'_tracking_url'=>$object->tracking_url, + $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'], + $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units), + $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units), + $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units), + $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units), + $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'), + ); + + // Add vat by rates + foreach ($object->lines as $line) + { + if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; + $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; + } + + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); + + $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs); + } + + return $array_shipment; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param ExpeditionLigne $line Object line + * @param Translate $outputlangs Lang object to use for output + * @return array Substitution array + */ + public function get_substitutionarray_shipment_lines($line, $outputlangs) + { + // phpcs:enable + global $conf; + dol_include_once('/core/lib/product.lib.php'); + + $resarray = array( + 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), + 'line_product_ref'=>$line->product_ref, + 'line_product_label'=>$line->product_label, + 'line_desc'=>$line->desc, + 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), + 'line_up'=>price($line->subprice), + 'line_total_up'=>price($line->subprice * $line->qty), + 'line_qty'=>$line->qty, + 'line_qty_shipped'=>$line->qty_shipped, + 'line_qty_asked'=>$line->qty_asked, + 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), + 'line_price_ht'=>price($line->total_ht), + 'line_price_ttc'=>price($line->total_ttc), + 'line_price_vat'=>price($line->total_tva), + 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), + 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), + 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), + 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), + ); + + // Retrieve extrafields + $extrafieldkey = $line->element; + $array_key = "line"; + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $extrafields->fetch_name_optionals_label($extrafieldkey, true); + $line->fetch_optionals(); + + $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + + return $resarray; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Object $object Dolibarr Object + * @param Translate $outputlangs Language object for output + * @param boolean $recursive Want to fetch child array or child object + * @return array Array of substitution key->code + */ + public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true) + { + // phpcs:enable + $array_other = array(); + if (!empty($object)) { + foreach ($object as $key => $value) { + if (!empty($value)) { + if (!is_array($value) && !is_object($value)) { + $array_other['object_'.$key] = $value; + } + if (is_array($value) && $recursive) { + $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false); + } + } + } + } + return $array_other; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Fill array with couple extrafield key => extrafield value + * + * @param Object $object Object with extrafields (must have $object->array_options filled) + * @param array $array_to_fill Substitution array + * @param Extrafields $extrafields Extrafields object + * @param string $array_key Prefix for name of the keys into returned array + * @param Translate $outputlangs Lang object to use for output + * @return array Substitution array + */ + public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs) + { + // phpcs:enable global $conf; if (is_array($extrafields->attributes[$object->table_element]['label'])) { @@ -865,10 +794,12 @@ $object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency); //Add value to store price with currency $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency'])); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') { $object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]]; - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { $valArray = explode(',', $object->array_options['options_'.$key]); $output = array(); foreach ($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt=>$valopt) { @@ -877,7 +808,8 @@ } } $object->array_options['options_'.$key] = implode(', ', $output); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') { if (strlen($object->array_options['options_'.$key]) > 0) { @@ -885,14 +817,17 @@ $object->array_options['options_'.$key] = dol_print_date($date, 'day'); // using company output language $object->array_options['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format $object->array_options['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format - } else { + } + else + { $object->array_options['options_'.$key] = ''; $object->array_options['options_'.$key.'_locale'] = ''; $object->array_options['options_'.$key.'_rfc'] = ''; } $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale'])); $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc'])); - } elseif ($extrafields->attributes[$object->table_element]['label'][$key] == 'datetime') + } + elseif ($extrafields->attributes[$object->table_element]['label'][$key] == 'datetime') { $datetime = $object->array_options['options_'.$key]; $object->array_options['options_'.$key] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour') : ''); // using company output language @@ -900,7 +835,8 @@ $object->array_options['options_'.$key.'_rfc'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhourrfc') : ''); // international format $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale'])); $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc'])); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'link') + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'link') { $id = $object->array_options['options_'.$key]; if ($id != "") @@ -944,671 +880,676 @@ * @param int $hidebottom Hide bottom * @return void */ - public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) + public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) + { + if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); + $pdf->line($x + $l, $y, $x + $l, $y + $h); + if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); + $pdf->line($x, $y + $h, $x, $y); + } + + + /** + * uasort callback function to Sort columns fields + * + * @param array $a PDF lines array fields configs + * @param array $b PDF lines array fields configs + * @return int Return compare result + */ + public function columnSort($a, $b) + { + if (empty($a['rank'])) { $a['rank'] = 0; } + if (empty($b['rank'])) { $b['rank'] = 0; } + if ($a['rank'] == $b['rank']) { + return 0; + } + return ($a['rank'] > $b['rank']) ? -1 : 1; + } + + /** + * Prepare Array Column Field + * + * @param object $object common object + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return null + */ + public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + global $conf; + + $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); + + + // Sorting + uasort($this->cols, array($this, 'columnSort')); + + // Positionning + $curX = $this->page_largeur - $this->marge_droite; // start from right + + // Array width + $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; + + // Count flexible column + $totalDefinedColWidth = 0; + $countFlexCol = 0; + foreach ($this->cols as $colKey =>& $colDef) + { + if (!$this->getColumnStatus($colKey)) continue; // continue if disabled + + if (!empty($colDef['scale'])) { + // In case of column width is defined by percentage + $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); + } + + if (empty($colDef['width'])) { + $countFlexCol++; + } + else { + $totalDefinedColWidth += $colDef['width']; + } + } + + foreach ($this->cols as $colKey =>& $colDef) + { + // setting empty conf with default + if (!empty($colDef['title'])) { + $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); + } + else { + $colDef['title'] = $this->defaultTitlesFieldsStyle; + } + + // setting empty conf with default + if (!empty($colDef['content'])) { + $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); + } + else { + $colDef['content'] = $this->defaultContentsFieldsStyle; + } + + if ($this->getColumnStatus($colKey)) + { + // In case of flexible column + if (empty($colDef['width'])) { + $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; + } + + // Set positions + $lastX = $curX; + $curX = $lastX - $colDef['width']; + $colDef['xStartPos'] = $curX; + $colDef['xEndPos'] = $lastX; + } + } + } + + /** + * get column content width from column key + * + * @param string $colKey the column key + * @return float width in mm + */ + public function getColumnContentWidth($colKey) + { + $colDef = $this->cols[$colKey]; + return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1]; + } + + + /** + * get column content X (abscissa) left position from column key + * + * @param string $colKey the column key + * @return float X position in mm + */ + public function getColumnContentXStart($colKey) + { + $colDef = $this->cols[$colKey]; + return $colDef['xStartPos'] + $colDef['content']['padding'][3]; + } + + /** + * get column position rank from column key + * + * @param string $colKey the column key + * @return int rank on success and -1 on error + */ + public function getColumnRank($colKey) + { + if (!isset($this->cols[$colKey]['rank'])) return -1; + return $this->cols[$colKey]['rank']; + } + + /** + * get column position rank from column key + * + * @param string $newColKey the new column key + * @param array $defArray a single column definition array + * @param string $targetCol target column used to place the new column beside + * @param bool $insertAfterTarget insert before or after target column ? + * @return int new rank on success and -1 on error + */ + public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) + { + // prepare wanted rank + $rank = -1; + + // try to get rank from target column + if (!empty($targetCol)) { + $rank = $this->getColumnRank($targetCol); + if ($rank >= 0 && $insertAfterTarget) { $rank++; } + } + + // get rank from new column definition + if ($rank < 0 && !empty($defArray['rank'])) { + $rank = $defArray['rank']; + } + + // error: no rank + if ($rank < 0) { return -1; } + + foreach ($this->cols as $colKey =>& $colDef) + { + if ($rank <= $colDef['rank']) + { + $colDef['rank'] = $colDef['rank'] + 1; + } + } + + $defArray['rank'] = $rank; + $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys + + return $rank; + } + + + /** + * print standard column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param string $columnText column text + * @return null + */ + public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') + { + global $hookmanager; + + $parameters = array( + 'curY' => &$curY, + 'columnText' => $columnText, + 'colKey' => $colKey + ); + $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if (!$reshook) + { + if (empty($columnText)) return; + $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + } + } + + + /** + * print description column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param object $object CommonObject + * @param int $i the $object->lines array key + * @param Translate $outputlangs Output language + * @param int $hideref hide ref + * @param int $hidedesc hide desc + * @param int $issupplierline if object need supplier product + * @return null + */ + public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) { - if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); - $pdf->line($x + $l, $y, $x + $l, $y + $h); - if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); - $pdf->line($x, $y + $h, $x, $y); - } - - - /** - * uasort callback function to Sort columns fields - * - * @param array $a PDF lines array fields configs - * @param array $b PDF lines array fields configs - * @return int Return compare result - */ - public function columnSort($a, $b) - { - if (empty($a['rank'])) { $a['rank'] = 0; } - if (empty($b['rank'])) { $b['rank'] = 0; } - if ($a['rank'] == $b['rank']) { - return 0; - } - return ($a['rank'] > $b['rank']) ? -1 : 1; - } - - /** - * Prepare Array Column Field - * - * @param object $object common object - * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return null - */ - public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - global $conf; - - $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - - - // Sorting - uasort($this->cols, array($this, 'columnSort')); - - // Positionning - $curX = $this->page_largeur - $this->marge_droite; // start from right - - // Array width - $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; - - // Count flexible column - $totalDefinedColWidth = 0; - $countFlexCol = 0; - foreach ($this->cols as $colKey =>& $colDef) - { - if (!$this->getColumnStatus($colKey)) continue; // continue if disabled - - if (!empty($colDef['scale'])) { - // In case of column width is defined by percentage - $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); - } - - if (empty($colDef['width'])) { - $countFlexCol++; - } else { - $totalDefinedColWidth += $colDef['width']; - } - } - - foreach ($this->cols as $colKey =>& $colDef) - { - // setting empty conf with default - if (!empty($colDef['title'])) { - $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); - } else { - $colDef['title'] = $this->defaultTitlesFieldsStyle; - } - - // setting empty conf with default - if (!empty($colDef['content'])) { - $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); - } else { - $colDef['content'] = $this->defaultContentsFieldsStyle; - } - - if ($this->getColumnStatus($colKey)) - { - // In case of flexible column - if (empty($colDef['width'])) { - $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; - } - - // Set positions - $lastX = $curX; - $curX = $lastX - $colDef['width']; - $colDef['xStartPos'] = $curX; - $colDef['xEndPos'] = $lastX; - } - } - } - - /** - * get column content width from column key - * - * @param string $colKey the column key - * @return float width in mm - */ - public function getColumnContentWidth($colKey) - { - $colDef = $this->cols[$colKey]; - return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1]; - } - - - /** - * get column content X (abscissa) left position from column key - * - * @param string $colKey the column key - * @return float X position in mm - */ - public function getColumnContentXStart($colKey) - { - $colDef = $this->cols[$colKey]; - return $colDef['xStartPos'] + $colDef['content']['padding'][3]; - } - - /** - * get column position rank from column key - * - * @param string $colKey the column key - * @return int rank on success and -1 on error - */ - public function getColumnRank($colKey) - { - if (!isset($this->cols[$colKey]['rank'])) return -1; - return $this->cols[$colKey]['rank']; - } - - /** - * get column position rank from column key - * - * @param string $newColKey the new column key - * @param array $defArray a single column definition array - * @param string $targetCol target column used to place the new column beside - * @param bool $insertAfterTarget insert before or after target column ? - * @return int new rank on success and -1 on error - */ - public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) - { - // prepare wanted rank - $rank = -1; - - // try to get rank from target column - if (!empty($targetCol)) { - $rank = $this->getColumnRank($targetCol); - if ($rank >= 0 && $insertAfterTarget) { $rank++; } - } - - // get rank from new column definition - if ($rank < 0 && !empty($defArray['rank'])) { - $rank = $defArray['rank']; - } - - // error: no rank - if ($rank < 0) { return -1; } - - foreach ($this->cols as $colKey =>& $colDef) - { - if ($rank <= $colDef['rank']) - { - $colDef['rank'] = $colDef['rank'] + 1; - } - } - - $defArray['rank'] = $rank; - $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys - - return $rank; - } - - - /** - * print standard column content - * - * @param TCPDF $pdf pdf object - * @param float $curY curent Y position - * @param string $colKey the column key - * @param string $columnText column text - * @return null - */ - public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') - { - global $hookmanager; - - $parameters = array( - 'curY' => &$curY, - 'columnText' => $columnText, - 'colKey' => $colKey, - 'pdf' => &$pdf, - ); - $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (!$reshook) - { - if (empty($columnText)) return; - $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position - $colDef = $this->cols[$colKey]; - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - // set cell padding with column content definition - $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); - $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - } - - - /** - * print description column content - * - * @param TCPDF $pdf pdf object - * @param float $curY curent Y position - * @param string $colKey the column key - * @param object $object CommonObject - * @param int $i the $object->lines array key - * @param Translate $outputlangs Output language - * @param int $hideref hide ref - * @param int $hidedesc hide desc - * @param int $issupplierline if object need supplier product - * @return null - */ - public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) - { - // load desc col params - $colDef = $this->cols[$colKey]; - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - // set cell padding with column content definition - $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); - - // line description - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); - $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - - // Display extrafield if needed - $params = array( - 'display' => 'list', - 'printableEnable' => array(3), - 'printableEnableNotEmpty' => array(4) - ); - $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); - if (!empty($extrafieldDesc)) { - $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); - } - } - - /** - * get extrafield content for pdf writeHtmlCell compatibility - * usage for PDF line columns and object note block - * - * @param object $object common object - * @param string $extrafieldKey the extrafield key - * @return string - */ - public function getExtrafieldContent($object, $extrafieldKey) - { - global $hookmanager; - - if (empty($object->table_element)) { return; } - - $extrafieldsKeyPrefix = "options_"; - - // Cleanup extrafield key to remove prefix if present - $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); - if ($pos === 0) { - $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); - } - - $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; - - - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; - - $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); - - // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... - if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { - // for lack of anything better we cleanup all html tags - $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); - } - - $parameters = array( - 'object' => $object, - 'extrafields' => $extrafields, - 'extrafieldKey' => $extrafieldKey, - 'extrafieldOutputContent' =>& $extrafieldOutputContent - ); - $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if ($reshook) - { - $extrafieldOutputContent = $hookmanager->resPrint; - } - - return $extrafieldOutputContent; - } - - - /** - * display extrafields columns content - * - * @param object $object line of common object - * @param Translate $outputlangs Output language - * @param array $params array of additionals parameters - * @return double max y value - */ - public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) - { - global $hookmanager; - - if (empty($object->table_element)) { - return; - } - - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; - - $defaultParams = array( - 'style' => '', - 'display' => 'auto', // auto, table, list - 'printableEnable' => array(1), - 'printableEnableNotEmpty' => array(2), - - 'table' => array( - 'maxItemsInRow' => 2, - 'cellspacing' => 0, - 'cellpadding' => 0, - 'border' => 0, - 'labelcolwidth' => '25%', - 'arrayOfLineBreakType' => array('text', 'html') - ), - - 'list' => array( - 'separator' => '
' - ), - - 'auto' => array( - 'list' => 0, // 0 for default - 'table' => 4 // if there more than x extrafield to display - ), - ); - - $params = $params + $defaultParams; - - - /** - * @var $extrafields ExtraFields - */ - - $html = ''; - $fields = array(); - - if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) - { - // Enable extrafield ? - $enabled = 0; - $disableOnEmpty = 0; - if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { - $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); - if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { - $enabled = 1; - } - - if (in_array($printable, $params['printableEnableNotEmpty'])) { - $disableOnEmpty = 1; - } - } - - if (empty($enabled)) { - continue; - } - - $field = new stdClass(); - $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); - $field->content = $this->getExtrafieldContent($object, $key); - $field->label = $outputlangs->transnoentities($label); - $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; - - // dont display if empty - if ($disableOnEmpty && empty($field->content)) { - continue; - } - - $fields[] = $field; - } - } - - if (!empty($fields)) - { - // Sort extrafields by rank - uasort($fields, function ($a, $b) { - return ($a->rank > $b->rank) ? 1 : -1; + // load desc col params + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + + // line description + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); + $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + + // Display extrafield if needed + $params = array( + 'display' => 'list', + 'printableEnable' => array(3), + 'printableEnableNotEmpty' => array(4) + ); + $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); + if (!empty($extrafieldDesc)) { + $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); + } + } + + /** + * get extrafield content for pdf writeHtmlCell compatibility + * usage for PDF line columns and object note block + * + * @param object $object common object + * @param string $extrafieldKey the extrafield key + * @return string + */ + public function getExtrafieldContent($object, $extrafieldKey) + { + global $hookmanager; + + if (empty($object->table_element)) { return; } + + $extrafieldsKeyPrefix = "options_"; + + // Cleanup extrafield key to remove prefix if present + $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); + if ($pos === 0) { + $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); + } + + $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; + + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); + + // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... + if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { + // for lack of anything better we cleanup all html tags + $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); + } + + $parameters = array( + 'object' => $object, + 'extrafields' => $extrafields, + 'extrafieldKey' => $extrafieldKey, + 'extrafieldOutputContent' =>& $extrafieldOutputContent + ); + $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook) + { + $extrafieldOutputContent = $hookmanager->resPrint; + } + + return $extrafieldOutputContent; + } + + + /** + * display extrafields columns content + * + * @param object $object line of common object + * @param Translate $outputlangs Output language + * @param array $params array of additionals parameters + * @return double max y value + */ + public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) + { + global $hookmanager; + + if (empty($object->table_element)) { + return; + } + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $defaultParams = array( + 'style' => '', + 'display' => 'auto', // auto, table, list + 'printableEnable' => array(1), + 'printableEnableNotEmpty' => array(2), + + 'table' => array( + 'maxItemsInRow' => 2, + 'cellspacing' => 0, + 'cellpadding' => 0, + 'border' => 0, + 'labelcolwidth' => '25%', + 'arrayOfLineBreakType' => array('text', 'html') + ), + + 'list' => array( + 'separator' => '
' + ), + + 'auto' => array( + 'list' => 0, // 0 for default + 'table' => 4 // if there more than x extrafield to display + ), + ); + + $params = $params + $defaultParams; + + + /** + * @var $extrafields ExtraFields + */ + + $html = ''; + $fields = array(); + + if (is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Enable extrafield ? + $enabled = 0; + $disableOnEmpty = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { + $enabled = 1; + } + + if (in_array($printable, $params['printableEnableNotEmpty'])) { + $disableOnEmpty = 1; + } + } + + if (empty($enabled)) { + continue; + } + + $field = new stdClass(); + $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); + $field->content = $this->getExtrafieldContent($object, $key); + $field->label = $outputlangs->transnoentities($label); + $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; + + // dont display if empty + if ($disableOnEmpty && empty($field->content)) { + continue; + } + + $fields[] = $field; + } + } + + if (!empty($fields)) + { + // Sort extrafields by rank + uasort($fields, function ($a, $b) { + return ($a->rank > $b->rank) ? -1 : 1; }); - // define some HTML content with style - $html .= !empty($params['style']) ? '' : ''; - - // auto select display format - if ($params['display'] == 'auto') { - $lastNnumbItems = 0; - foreach ($params['auto'] as $display => $numbItems) { - if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { - $lastNnumbItems = $numbItems; - $params['display'] = $display; - } - } - } - - if ($params['display'] == 'list') { - // Display in list format - $i = 0; - foreach ($fields as $field) { - $html .= !empty($i) ? $params['list']['separator'] : ''; - $html .= ''.$field->label.' : '; - $html .= $field->content; - $i++; - } - } elseif ($params['display'] == 'table') { - // Display in table format - $html .= ''; - - $html .= ""; - $itemsInRow = 0; - $maxItemsInRow = $params['table']['maxItemsInRow']; - foreach ($fields as $field) { - //$html.= !empty($html)?'
':''; - if ($itemsInRow >= $maxItemsInRow) { - // start a new line - $html .= ""; - $itemsInRow = 0; - } - - // for some type we need line break - if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { - if ($itemsInRow > 0) { - // close table row and empty cols - for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { - $html .= ""; - } - $html .= ""; - - // start a new line - $html .= ""; - } - - $itemsInRow = $maxItemsInRow; - $html .= '"; - } else { - $itemsInRow++; - $html .= '"; - - - $html .= '"; - } - } - $html .= ""; - - $html .= '
'; - $html .= ''.$field->label.' : '; - $html .= $field->content; - $html .= "'; - $html .= ''.$field->label.' :'; - $html .= "'; - $html .= $field->content; - $html .= "
'; - } - } - - return $html; - } - - - /** - * get column status from column key - * - * @param string $colKey the column key - * @return float width in mm - */ - public function getColumnStatus($colKey) - { - if (!empty($this->cols[$colKey]['status'])) { - return true; - } else return false; - } - - /** - * Print standard column content - * - * @param TCPDI $pdf Pdf object - * @param float $tab_top Tab top position - * @param float $tab_height Default tab height - * @param Translate $outputlangs Output language - * @param int $hidetop Hide top - * @return float Height of col tab titles - */ - public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0) - { - global $hookmanager, $conf; - - foreach ($this->cols as $colKey => $colDef) { - $parameters = array( - 'colKey' => $colKey, - 'pdf' => $pdf, - 'outputlangs' => $outputlangs, - 'tab_top' => $tab_top, - 'tab_height' => $tab_height, - 'hidetop' => $hidetop - ); - - $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) { - if (!$this->getColumnStatus($colKey)) continue; - - // get title label - $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); - - // Add column separator - if (!empty($colDef['border-left'])) { - $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); - } - - if (empty($hidetop)) { - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - - // Add space for lines (more if we need to show a second alternative language) - global $outputlangsbis; - if (is_object($outputlangsbis)) { - // set cell padding with column title definition - $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); - } else { - // set cell padding with column title definition - $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); - } - - $pdf->SetXY($colDef['xStartPos'], $tab_top); - $textWidth = $colDef['width']; - $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); - - // Add variant of translation if $outputlangsbis is an object - if (is_object($outputlangsbis) && trim($colDef['title']['label'])) { - $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); - $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); - $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); - $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); - } - - $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - } - } - - return $this->tabTitleHeight; - } - - - - /** - * Define Array Column Field for extrafields - * - * @param object $object common object det - * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @return null - */ - public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) - { - global $conf; - - if (!empty($hidedetails)) { - return; - } - - if (empty($object->table_element)) { - return; - } - - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; - - - if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) - { - // Dont display separator yet even is set to be displayed (not compatible yet) - if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') - { - continue; - } - - // Enable extrafield ? - $enabled = 0; - if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { - $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); - if ($printable === 1 || $printable === 2) { - $enabled = 1; - } - // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols - } - - if (!$enabled) { continue; } // don't wast resourses if we don't need them... - - // Load language if required - if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); - - // TODO : add more extrafield customisation capacities for PDF like width, rank... - - // set column definition - $def = array( - 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), - 'width' => 25, // in mm - 'status' => boolval($enabled), - 'title' => array( - 'label' => $outputlangs->transnoentities($label) - ), - 'content' => array( - 'align' => 'C' - ), - 'border-left' => true, // add left line separator - ); - - $alignTypeRight = array('double', 'int', 'price'); - if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { - $def['content']['align'] = 'R'; - } - - $alignTypeLeft = array('text', 'html'); - if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { - $def['content']['align'] = 'L'; - } - - - // for extrafields we use rank of extrafield to place it on PDF - $this->insertNewColumnDef("options_".$key, $def); - } - } - } + // define some HTML content with style + $html .= !empty($params['style']) ? '' : ''; + + // auto select display format + if ($params['display'] == 'auto') { + $lastNnumbItems = 0; + foreach ($params['auto'] as $display => $numbItems) { + if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { + $lastNnumbItems = $numbItems; + $params['display'] = $display; + } + } + } + + if ($params['display'] == 'list') { + // Display in list format + $i = 0; + foreach ($fields as $field) { + $html .= !empty($i) ? $params['list']['separator'] : ''; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $i++; + } + } + elseif ($params['display'] == 'table') { + // Display in table format + $html .= ''; + + $html .= ""; + $itemsInRow = 0; + $maxItemsInRow = $params['table']['maxItemsInRow']; + foreach ($fields as $field) { + //$html.= !empty($html)?'
':''; + if ($itemsInRow >= $maxItemsInRow) { + // start a new line + $html .= ""; + $itemsInRow = 0; + } + + // for some type we need line break + if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { + if ($itemsInRow > 0) { + // close table row and empty cols + for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { + $html .= ""; + } + $html .= ""; + + // start a new line + $html .= ""; + } + + $itemsInRow = $maxItemsInRow; + $html .= '"; + } else { + $itemsInRow++; + $html .= '"; + + + $html .= '"; + } + } + $html .= ""; + + $html .= '
'; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $html .= "'; + $html .= ''.$field->label.' :'; + $html .= "'; + $html .= $field->content; + $html .= "
'; + } + } + + return $html; + } + + + /** + * get column status from column key + * + * @param string $colKey the column key + * @return float width in mm + */ + public function getColumnStatus($colKey) + { + if (!empty($this->cols[$colKey]['status'])) { + return true; + } + else return false; + } + + /** + * Print standard column content + * + * @param TCPDI $pdf Pdf object + * @param float $tab_top Tab top position + * @param float $tab_height Default tab height + * @param Translate $outputlangs Output language + * @param int $hidetop Hide top + * @return float Height of col tab titles + */ + public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0) + { + global $hookmanager, $conf; + + foreach ($this->cols as $colKey => $colDef) { + $parameters = array( + 'colKey' => $colKey, + 'pdf' => $pdf, + 'outputlangs' => $outputlangs, + 'tab_top' => $tab_top, + 'tab_height' => $tab_height, + 'hidetop' => $hidetop + ); + + $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } elseif (empty($reshook)) { + if (!$this->getColumnStatus($colKey)) continue; + + // get title label + $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); + + // Add column separator + if (!empty($colDef['border-left'])) { + $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); + } + + if (empty($hidetop)) { + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + + // Add space for lines (more if we need to show a second alternative language) + global $outputlangsbis; + if (is_object($outputlangsbis)) { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); + } + else { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + } + + $pdf->SetXY($colDef['xStartPos'], $tab_top); + $textWidth = $colDef['width']; + $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); + + // Add variant of translation if $outputlangsbis is an object + if (is_object($outputlangsbis) && trim($colDef['title']['label'])) { + $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); + $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); + $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); + } + + $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + } + } + } + + return $this->tabTitleHeight; + } + + + + /** + * Define Array Column Field for extrafields + * + * @param object $object common object det + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @return null + */ + public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) + { + global $conf; + + if (!empty($hidedetails)) { + return; + } + + if (empty($object->table_element)) { + return; + } + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + + if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Dont display separator yet even is set to be displayed (not compatible yet) + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') + { + continue; + } + + // Enable extrafield ? + $enabled = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if ($printable === 1 || $printable === 2) { + $enabled = 1; + } + // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols + } + + if (!$enabled) { continue; } // don't wast resourses if we don't need them... + + // Load language if required + if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); + + // TODO : add more extrafield customisation capacities for PDF like width, rank... + + // set column definition + $def = array( + 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), + 'width' => 25, // in mm + 'status' => boolval($enabled), + 'title' => array( + 'label' => $outputlangs->transnoentities($label) + ), + 'content' => array( + 'align' => 'C' + ), + 'border-left' => true, // add left line separator + ); + + $alignTypeRight = array('double', 'int', 'price'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { + $def['content']['align'] = 'R'; + } + + $alignTypeLeft = array('text', 'html'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { + $def['content']['align'] = 'L'; + } + + + // for extrafields we use rank of extrafield to place it on PDF + $this->insertNewColumnDef("options_".$key, $def); + } + } + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_commoninvoice.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commoninvoice.class.php @@ -24,45 +24,42 @@ */ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; /** * Superclass for invoices classes */ abstract class CommonInvoice extends CommonObject { - use CommonIncoterm; - - /** - * Standard invoice - */ - const TYPE_STANDARD = 0; - - /** - * Replacement invoice - */ - const TYPE_REPLACEMENT = 1; - - /** - * Credit note invoice - */ - const TYPE_CREDIT_NOTE = 2; - - /** - * Deposit invoice - */ - const TYPE_DEPOSIT = 3; - - /** - * Proforma invoice. - * @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice ! - */ - const TYPE_PROFORMA = 4; - - /** - * Situation invoice - */ - const TYPE_SITUATION = 5; + /** + * Standard invoice + */ + const TYPE_STANDARD = 0; + + /** + * Replacement invoice + */ + const TYPE_REPLACEMENT = 1; + + /** + * Credit note invoice + */ + const TYPE_CREDIT_NOTE = 2; + + /** + * Deposit invoice + */ + const TYPE_DEPOSIT = 3; + + /** + * Proforma invoice. + * @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice ! + */ + const TYPE_PROFORMA = 4; + + /** + * Situation invoice + */ + const TYPE_SITUATION = 5; /** * Draft status @@ -98,20 +95,20 @@ * This does not include open direct debit requests. * * @param int $multicurrency Return multicurrency_amount instead of amount - * @return float Remain of amount to pay + * @return double Remain of amount to pay */ public function getRemainToPay($multicurrency = 0) { - $alreadypaid = 0.0; - $alreadypaid += $this->getSommePaiement($multicurrency); - $alreadypaid += $this->getSumDepositsUsed($multicurrency); - $alreadypaid += $this->getSumCreditNotesUsed($multicurrency); - - $remaintopay = price2num($this->total_ttc - $alreadypaid, 'MT'); - if ($this->statut == self::STATUS_CLOSED && $this->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment - $remaintopay = 0.0; - } - return $remaintopay; + $alreadypaid = 0; + $alreadypaid += $this->getSommePaiement($multicurrency); + $alreadypaid += $this->getSumDepositsUsed($multicurrency); + $alreadypaid += $this->getSumCreditNotesUsed($multicurrency); + + $remaintopay = price2num($this->total_ttc - $alreadypaid, 'MT'); + if ($this->statut == self::STATUS_CLOSED && $this->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment + $remaintopay = 0; + } + return $remaintopay; } /** @@ -119,7 +116,7 @@ * Payments dones using discounts, credit notes, etc are not included. * * @param int $multicurrency Return multicurrency_amount instead of amount - * @return float Amount of payment already done, <0 if KO + * @return int Amount of payment already done, <0 if KO */ public function getSommePaiement($multicurrency = 0) { @@ -143,7 +140,9 @@ $this->db->free($resql); if ($multicurrency) return $obj->multicurrency_amount; else return $obj->amount; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } @@ -151,69 +150,78 @@ /** * Return amount (with tax) of all deposits invoices used by invoice. - * Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended). + * Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended). * * @param int $multicurrency Return multicurrency_amount instead of amount - * @return float <0 if KO, Sum of deposits amount otherwise + * @return int <0 if KO, Sum of deposits amount otherwise */ public function getSumDepositsUsed($multicurrency = 0) { if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') - { - // TODO - return 0.0; - } - - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - $discountstatic = new DiscountAbsolute($this->db); - $result = $discountstatic->getSumDepositsUsed($this, $multicurrency); - if ($result >= 0) { - return $result; - } else { - $this->error = $discountstatic->error; - return -1; - } + { + // TODO + return 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $discountstatic = new DiscountAbsolute($this->db); + $result = $discountstatic->getSumDepositsUsed($this, $multicurrency); + if ($result >= 0) + { + return $result; + } + else + { + $this->error = $discountstatic->error; + return -1; + } } /** * Return amount (with tax) of all credit notes invoices + excess received used by invoice * * @param int $multicurrency Return multicurrency_amount instead of amount - * @return float <0 if KO, Sum of credit notes and deposits amount otherwise + * @return int <0 if KO, Sum of credit notes and deposits amount otherwise */ public function getSumCreditNotesUsed($multicurrency = 0) { - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - $discountstatic = new DiscountAbsolute($this->db); - $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency); - if ($result >= 0) { - return $result; - } else { - $this->error = $discountstatic->error; - return -1; - } + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $discountstatic = new DiscountAbsolute($this->db); + $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency); + if ($result >= 0) + { + return $result; + } + else + { + $this->error = $discountstatic->error; + return -1; + } } /** * Return amount (with tax) of all converted amount for this credit note * * @param int $multicurrency Return multicurrency_amount instead of amount - * @return float <0 if KO, Sum of credit notes and deposits amount otherwise + * @return int <0 if KO, Sum of credit notes and deposits amount otherwise */ public function getSumFromThisCreditNotesNotUsed($multicurrency = 0) { - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - $discountstatic = new DiscountAbsolute($this->db); - $result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency); - if ($result >= 0) { - return $result; - } else { - $this->error = $discountstatic->error; - return -1; - } + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $discountstatic = new DiscountAbsolute($this->db); + $result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency); + if ($result >= 0) + { + return $result; + } + else + { + $this->error = $discountstatic->error; + return -1; + } } /** @@ -240,7 +248,9 @@ $idarray[] = $row[0]; $i++; } - } else { + } + else + { dol_print_error($this->db); } return $idarray; @@ -274,11 +284,15 @@ { // If there is any return $obj->rowid; - } else { + } + else + { // If no invoice replaces it return 0; } - } else { + } + else + { return -1; } } @@ -297,7 +311,6 @@ $table2 = 'paiement'; $field = 'fk_facture'; $field2 = 'fk_paiement'; - $field3 = ', p.ref_ext'; $sharedentity = 'facture'; if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { @@ -305,11 +318,10 @@ $table2 = 'paiementfourn'; $field = 'fk_facturefourn'; $field2 = 'fk_paiementfourn'; - $field3 = ''; $sharedentity = 'facture_fourn'; } - $sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code'.$field3; + $sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code'; $sql .= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t'; $sql .= ' WHERE pf.'.$field.' = '.$this->id; //$sql.= ' WHERE pf.'.$field.' = 1'; @@ -327,11 +339,7 @@ while ($i < $num) { $obj = $this->db->fetch_object($resql); - $tmp = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); - if (!empty($field3)) { - $tmp['ref_ext'] = $obj->ref_ext; - } - $retarray[] = $tmp; + $retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); $i++; } $this->db->free($resql); @@ -344,7 +352,8 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$this->id; $sql .= ' AND (f.type = 2 OR f.type = 0 OR f.type = 3)'; // Find discount coming from credit note or excess received or deposits (payments from deposits are always null except if FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is set) - } elseif ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + } + elseif ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { $sql = 'SELECT rc.amount_ttc as amount, rc.multicurrency_amount_ttc as multicurrency_amount, rc.datec as date, f.ref as ref, rc.description as type'; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; @@ -363,12 +372,15 @@ $obj = $this->db->fetch_object($resql); if ($multicurrency) { $retarray[] = array('amount'=>$obj->multicurrency_amount, 'type'=>$obj->type, 'date'=>$obj->date, 'num'=>'0', 'ref'=>$obj->ref); - } else { + } + else { $retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->type, 'date'=>$obj->date, 'num'=>'', 'ref'=>$obj->ref); } $i++; } - } else { + } + else + { $this->error = $this->db->lasterror(); dol_print_error($this->db); return array(); @@ -377,7 +389,9 @@ } return $retarray; - } else { + } + else + { $this->error = $this->db->lasterror(); dol_print_error($this->db); return array(); @@ -385,7 +399,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return if an invoice can be deleted * Rule is: @@ -399,9 +413,9 @@ * * @return int <=0 if no, >0 if yes */ - public function is_erasable() - { - // phpcs:enable + public function is_erasable() + { + // phpcs:enable global $conf; // We check if invoice is a temporary number (PROVxxxx) @@ -459,7 +473,7 @@ $type = 'customer_invoice'; if ($this->element == 'invoice_supplier') $type = 'supplier_invoice'; - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".$this->id; + $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; $resql = $this->db->query($sql); if ($resql) { @@ -468,7 +482,9 @@ { $alreadydispatched = $obj->nb; } - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } @@ -486,15 +502,15 @@ * * @return string Label of type of invoice */ - public function getLibType() + public function getLibType() { global $langs; - if ($this->type == CommonInvoice::TYPE_STANDARD) return $langs->trans("InvoiceStandard"); - elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement"); - elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir"); - elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit"); - elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); // Not used. - elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation"); + if ($this->type == CommonInvoice::TYPE_STANDARD) return $langs->trans("InvoiceStandard"); + elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement"); + elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir"); + elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit"); + elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); // Not used. + elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation"); return $langs->trans("Unknown"); } @@ -510,7 +526,7 @@ return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return label of a status * @@ -518,59 +534,65 @@ * @param int $status Id status * @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 * @param integer $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, -1 otherwise) - * @param int $type Type invoice. If -1, we use $this->type + * @param int $type Type invoice * @return string Label of status */ - public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = -1) - { - // phpcs:enable + public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0) + { + // phpcs:enable global $langs; $langs->load('bills'); - - if ($type == -1) $type = $this->type; $statusType = 'status0'; $prefix = 'Short'; if (!$paye) { - if ($status == 0) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft'); - } elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid'); - $statusType = 'status5'; - } elseif (($status == 3 || $status == 2) && $alreadypaid > 0) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially'); - $statusType = 'status9'; - } elseif ($alreadypaid == 0) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid'); - $statusType = 'status1'; - } else { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted'); - $statusType = 'status3'; - } - } else { - $statusType = 'status6'; - - if ($type == self::TYPE_CREDIT_NOTE) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note - } elseif ($type == self::TYPE_DEPOSIT) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice - } else { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid'); - } + if ($status == 0) { + $labelStatus = $langs->trans('BillStatusDraft'); + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusDraft'); + } + elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) { + $labelStatus = $langs->trans('BillStatusClosedUnpaid'); + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusClosedUnpaid'); + $statusType = 'status5'; + } + elseif (($status == 3 || $status == 2) && $alreadypaid > 0) { + $labelStatus = $langs->trans('BillStatusClosedPaidPartially'); + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially'); + $statusType = 'status9'; + } + elseif ($alreadypaid <= 0) { + $labelStatus = $langs->trans('BillStatusNotPaid'); + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusNotPaid'); + $statusType = 'status1'; + } + else { + $labelStatus = $langs->trans('BillStatusStarted'); + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusStarted'); + $statusType = 'status3'; + } + } + else + { + $statusType = 'status6'; + + if ($type == self::TYPE_CREDIT_NOTE) { + $labelStatus = $langs->trans('BillStatusPaidBackOrConverted'); // credit note + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note + } + elseif ($type == self::TYPE_DEPOSIT) { + $labelStatus = $langs->trans('BillStatusConverted'); // deposit invoice + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusConverted'); // deposit invoice + } + else { + $labelStatus = $langs->trans('BillStatusPaid'); + $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusPaid'); + } } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns an invoice payment deadline based on the invoice settlement * conditions and billing date. @@ -578,15 +600,15 @@ * @param integer $cond_reglement Condition of payment (code or id) to use. If 0, we use current condition. * @return integer Date limite de reglement si ok, <0 si ko */ - public function calculate_date_lim_reglement($cond_reglement = 0) - { - // phpcs:enable + public function calculate_date_lim_reglement($cond_reglement = 0) + { + // phpcs:enable if (!$cond_reglement) $cond_reglement = $this->cond_reglement_code; if (!$cond_reglement) $cond_reglement = $this->cond_reglement_id; $cdr_nbjour = 0; - $cdr_type = 0; - $cdr_decalage = 0; + $cdr_type = 0; + $cdr_decalage = 0; $sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage'; $sqltemp .= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; @@ -607,7 +629,9 @@ $cdr_type = $obj->type_cdr; $cdr_decalage = $obj->decalage; } - } else { + } + else + { $this->error = $this->db->error(); return -1; } @@ -633,7 +657,9 @@ { $mois = 1; $annee += 1; - } else { + } + else + { $mois += 1; } // We move at the beginning of the next month, and we take a day off @@ -645,7 +671,7 @@ // 2 : application of the rule, the N of the current or next month elseif ($cdr_type == 2 && !empty($cdr_decalage)) { - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $datelim = $this->date + ($cdr_nbjour * 3600 * 24); $date_piece = dol_mktime(0, 0, 0, date('m', $datelim), date('d', $datelim), date('Y', $datelim)); // Sans les heures minutes et secondes @@ -656,9 +682,8 @@ if ($diff < 0) $datelim = $date_lim_current; else $datelim = $date_lim_next; - } else { - return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement; - } + } + else return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement; return $datelim; } @@ -696,7 +721,7 @@ } else { $sql .= ' WHERE fk_facture = '.$this->id; } - $sql .= ' AND ext_payment_id IS NULL'; // To exclude record done for some online payments + $sql .= ' AND ext_payment_id IS NULL'; // To exclude record done for some online payments $sql .= ' AND traite = 0'; dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); @@ -742,38 +767,49 @@ dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { + if (!$resql) + { $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::demandeprelevement Erreur'); $error++; } - } else { + } + else + { $this->error = 'WithdrawRequestErrorNilAmount'; dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount'); $error++; } - if (!$error) { + if (!$error) + { // Force payment mode of invoice to withdraw - $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1); - if ($payment_mode_id > 0) { + $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement', 'code', 'id', 1); + if ($payment_mode_id > 0) + { $result = $this->setPaymentMethods($payment_mode_id); } } if ($error) return -1; return 1; - } else { + } + else + { $this->error = "A request already exists"; dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours'); return 0; } - } else { + } + else + { $this->error = $this->db->error(); dol_syslog(get_class($this).'::demandeprelevement Erreur -2'); return -2; } - } else { + } + else + { $this->error = "Status of invoice does not allow this"; dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id"); return -3; @@ -797,7 +833,9 @@ if ($this->db->query($sql)) { return 0; - } else { + } + else + { $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error); return -1; @@ -815,21 +853,16 @@ abstract class CommonInvoiceLine extends CommonObjectLine { /** - * Custom label of line. Not used by default. - * @deprecated - */ - public $label; - - /** - * @deprecated - * @see $product_ref - */ - public $ref; // Product ref (deprecated) - /** - * @deprecated - * @see $product_label - */ - public $libelle; // Product label (deprecated) + * Quantity + * @var double + */ + public $qty; + + /** + * Unit price before taxes + * @var float + */ + public $subprice; /** * Type of the product. 0 for product 1 for service @@ -838,36 +871,6 @@ public $product_type = 0; /** - * Product ref - * @var string - */ - public $product_ref; - - /** - * Product label - * @var string - */ - public $product_label; - - /** - * Product description - * @var string - */ - public $product_desc; - - /** - * Quantity - * @var double - */ - public $qty; - - /** - * Unit price before taxes - * @var float - */ - public $subprice; - - /** * Id of corresponding product * @var int */ @@ -933,23 +936,21 @@ */ public $total_ttc; - public $date_start_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_start at creation - public $date_end_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_end at creation - /** * List of cumulative options: - * Bit 0: 0 for common VAT - 1 if VAT french NPR + * Bit 0: 0 si TVA normal - 1 si TVA NPR * Bit 1: 0 si ligne normal - 1 si bit discount (link to line into llx_remise_except) * @var int */ public $info_bits = 0; - public $special_code = 0; - - public $fk_multicurrency; - public $multicurrency_code; - public $multicurrency_subprice; - public $multicurrency_total_ht; - public $multicurrency_total_tva; - public $multicurrency_total_ttc; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_commonobject.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commonobject.class.php @@ -1,7 +1,7 @@ * Copyright (C) 2005-2013 Regis Houssin - * Copyright (C) 2010-2020 Juanjo Menent + * Copyright (C) 2010-2015 Juanjo Menent * Copyright (C) 2012-2013 Christophe Battarel * Copyright (C) 2011-2019 Philippe Grand * Copyright (C) 2012-2015 Marcos García @@ -12,7 +12,7 @@ * Copyright (C) 2017 ATM Consulting * Copyright (C) 2017-2019 Nicolas ZABOURI * Copyright (C) 2017 Rui Strecht - * Copyright (C) 2018-2020 Frédéric France + * Copyright (C) 2018-2019 Frédéric France * Copyright (C) 2018 Josep Lluís Amador * * This program is free software; you can redistribute it and/or modify @@ -52,22 +52,12 @@ public $id; /** - * @var int The environment ID when using a multicompany module - */ - public $entity; - - /** * @var string Error string * @see $errors */ public $error; /** - * @var string Error string that is hidden but can be used to store complementatry technical code. - */ - public $errorhidden; - - /** * @var string[] Array of error strings */ public $errors = array(); @@ -196,24 +186,19 @@ public $ref; /** + * @var string The object's previous reference + */ + public $ref_previous; + + /** + * @var string The object's next reference + */ + public $ref_next; + + /** * @var string An external reference for the object */ public $ref_ext; - - /** - * @var string The object's previous reference - */ - public $ref_previous; - - /** - * @var string The object's next reference - */ - public $ref_next; - - /** - * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object - */ - public $newref; /** * @var int The object's status @@ -222,12 +207,6 @@ public $statut; /** - * @var int The object's status - * @see setStatut() - */ - public $status; - - /** * @var string * @see getFullAddress() */ @@ -243,9 +222,9 @@ * @var string * @see getFullAddress(), isInEEC(), country */ - public $country_code; - - /** + public $country_code; + + /** * @var string * @see getFullAddress() */ @@ -259,27 +238,21 @@ /** * @var string - * @see getFullAddress(), $state - */ - public $state_code; - - /** - * @var int - * @see getFullAddress(), $region_code, $region - */ - public $region_id; - - /** + * @see getFullAddress(), state + */ + public $state_code; + + /** * @var string - * @see getFullAddress(), $region_id, $region - */ - public $region_code; + * @see getFullAddress(), region + */ + public $region; /** * @var string - * @see getFullAddress(), $region_id, $region_code - */ - public $region; + * @see getFullAddress(), region + */ + public $region_code; /** * @var int @@ -316,17 +289,6 @@ * @see setPaymentTerms() */ public $cond_reglement_id; - - /** - * @var int Demand reason ID - */ - public $demand_reason_id; - - /** - * @var int Transport mode ID (For module intracomm report) - * @see setTransportMode() - */ - public $transport_mode_id; /** * @var int Payment terms ID @@ -352,7 +314,7 @@ * @var string * @see SetDocModel() */ - public $model_pdf; + public $modelpdf; /** * @var string @@ -361,24 +323,12 @@ public $last_main_doc; /** - * @var int Bank account ID sometimes, ID of record into llx_bank sometimes - * @deprecated - * @see $fk_account - */ - public $fk_bank; - - /** * @var int Bank account ID * @see SetBankAccount() */ public $fk_account; /** - * @var string Open ID - */ - public $openid; - - /** * @var string Public note * @see update_note() */ @@ -438,29 +388,47 @@ public $comments = array(); /** + * @var int + * @see setIncoterms() + */ + public $fk_incoterms; + + /** + * @var string + * @see SetIncoterms() + */ + public $label_incoterms; + + /** + * @var string + * @see display_incoterms() + */ + public $location_incoterms; + + /** * @var string The name */ public $name; - /** - * @var string The lastname - */ + /** + * @var string The lastname + */ public $lastname; - /** - * @var string The firstname - */ + /** + * @var string The firstname + */ public $firstname; - /** - * @var string The civility code, not an integer - */ + /** + * @var string The civility code, not an integer + */ public $civility_id; // Dates /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; /** @@ -474,21 +442,6 @@ public $date_modification; // Date last change (tms field) public $next_prev_filter; - - /** - * @var int 1 if object is specimen - */ - public $specimen = 0; - - /** - * @var int Id of contact to send object (used by the trigger of module Agenda) - */ - public $sendtoid; - - /** - * @var float Amount already paid (used to show correct status) - */ - public $alreadypaid; /** * @var array List of child tables. To test if we can delete object. @@ -562,16 +515,16 @@ */ public function getFormatedCustomerRef($objref) { - global $hookmanager; - - $parameters = array('objref'=>$objref); - $action = ''; - $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) - { - return $hookmanager->resArray['objref']; - } - return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); + global $hookmanager; + + $parameters = array('objref'=>$objref); + $action = ''; + $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) + { + return $hookmanager->resArray['objref']; + } + return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); } /** @@ -582,16 +535,16 @@ */ public function getFormatedSupplierRef($objref) { - global $hookmanager; - - $parameters = array('objref'=>$objref); - $action = ''; - $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) - { - return $hookmanager->resArray['objref']; - } - return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); + global $hookmanager; + + $parameters = array('objref'=>$objref); + $action = ''; + $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) + { + return $hookmanager->resArray['objref']; + } + return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); } /** @@ -599,7 +552,7 @@ * * @param Translate $langs Language object for translation of civility (used only if option is 1) * @param int $option 0=No option, 1=Add civility - * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname + * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname * @param int $maxlen Maximum length * @return string String with full name */ @@ -620,28 +573,6 @@ $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder); return dol_trunc($ret, $maxlen); - } - - /** - * Set to upper or ucwords/lower if needed - * - * @return void; - */ - public function setUpperOrLowerCase() - { - global $conf; - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) { - $this->lastname = dol_ucwords(dol_strtolower($this->lastname)); - $this->firstname = dol_ucwords(dol_strtolower($this->firstname)); - $this->name = dol_ucwords(dol_strtolower($this->name)); - } - if (!empty($conf->global->MAIN_ALL_TO_UPPER)) { - $this->lastname = dol_strtoupper($this->lastname); - $this->name = dol_strtoupper($this->name); - } - if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) { - $this->town = dol_strtoupper($this->town); - } } /** @@ -685,15 +616,15 @@ $this->country = $tmparray['label']; } - if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $tmparray = getState($this->state_id, 'all', 0, 1); + if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + $tmparray = getState($this->state_id, 'all', 0, 1); $this->state_code = $tmparray['code']; $this->state = $tmparray['label']; $this->region_code = $tmparray['region_code']; $this->region = $tmparray['region']; - } + } return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode); } @@ -715,14 +646,17 @@ $contactid = 0; $thirdpartyid = 0; $elementforaltlanguage = $this->element; - if ($this->element == 'societe') { + if ($this->element == 'societe') + { $thirdpartyid = $this->id; } - if ($this->element == 'contact') { + if ($this->element == 'contact') + { $contactid = $this->id; $thirdpartyid = $object->fk_soc; } - if ($this->element == 'user') { + if ($this->element == 'user') + { $contactid = $this->contact_id; $thirdpartyid = $object->fk_soc; } @@ -763,7 +697,7 @@ if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) { - $out .= "\n"; + $out .= "\n"; $this->fetchValuesForExtraLanguages(); if (!is_object($form)) $form = new Form($this->db); $htmltext = ''; @@ -781,72 +715,65 @@ if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { - $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state; - } else { - $out .= ($outdone ? ' - ' : '').$this->state; - } + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { + $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state; + } + else { + $out .= ($outdone ? ' - ' : '').$this->state; + } $outdone++; } if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) $out .= ($outdone ? '
' : ''); if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone - $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); - $outdone++; + $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; } if (!empty($this->phone_pro)) { - $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); - $outdone++; + $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; } if (!empty($this->phone_mobile)) { - $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); - $outdone++; + $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); $outdone++; } if (!empty($this->phone_perso)) { - $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso")); - $outdone++; + $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso")); $outdone++; } if (!empty($this->office_phone)) { - $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); - $outdone++; + $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; } if (!empty($this->user_mobile)) { - $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); - $outdone++; + $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); $outdone++; } if (!empty($this->fax)) { - $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); - $outdone++; + $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); $outdone++; } if (!empty($this->office_fax)) { - $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); - $outdone++; + $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); $outdone++; } if ($out) $out .= '
'; $outdone = 0; - if (!empty($this->email)) { + if (!empty($this->email)) + { $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1); $outdone++; } - if (!empty($this->url)) { - //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank - $out .= dol_print_url($this->url, '_blank', 0, 1); + if (!empty($this->url)) + { + //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank + $out .= dol_print_url($this->url, '_blank', 0, 1); $outdone++; } - if (!empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) + { $outsocialnetwork = ''; if (is_array($this->socialnetworks) && count($this->socialnetworks) > 0) { - $socialnetworksdict = getArrayOfSocialNetworks(); foreach ($this->socialnetworks as $key => $value) { - if ($value) { - $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict); - } + $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key); $outdone++; } - } else { // Old code to remove + } else { if ($this->skype) $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype'); $outdone++; if ($this->jabberid) $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber'); @@ -918,8 +845,10 @@ $this->errors = $ecmfile->errors; } */ - } else return ''; - } elseif (empty($ecmfile->share)) + } + else return ''; + } + elseif (empty($ecmfile->share)) { // Add entry into index if ($initsharekey) @@ -927,7 +856,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $ecmfile->share = getRandomPassword(true); $ecmfile->update($user); - } else return ''; + } + else return ''; } // Define $urlwithroot $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); @@ -949,7 +879,9 @@ if ($relativelink) { $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : ''); - } else { + } + else + { $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : ''); } @@ -958,19 +890,19 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add a link between element $this->element and a contact * - * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link - * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL - * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) - * @param int $notrigger Disable all triggers - * @return int <0 if KO, >0 if OK + * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link + * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL + * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) + * @param int $notrigger Disable all triggers + * @return int <0 if KO, >0 if OK */ public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user, $langs; @@ -996,7 +928,9 @@ if (is_numeric($type_contact)) { $id_type_contact = $type_contact; - } else { + } + else + { // We look for id type_contact $sql = "SELECT tc.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; @@ -1059,13 +993,18 @@ $this->db->commit(); return 1; - } else { + } + else + { if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error = $this->db->errno(); $this->db->rollback(); + echo 'err rollback'; return -2; - } else { + } + else + { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -1074,7 +1013,7 @@ } else return 0; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Copy contact from one element to current * @@ -1084,7 +1023,7 @@ */ public function copy_linked_contact($objFrom, $source = 'internal') { - // phpcs:enable + // phpcs:enable $contacts = $objFrom->liste_contact(-1, $source); foreach ($contacts as $contact) { @@ -1097,7 +1036,7 @@ return 1; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update a link to contact line * @@ -1109,24 +1048,26 @@ */ public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0) { - // phpcs:enable + // phpcs:enable // Insert into database $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; $sql .= " statut = ".$statut; - if ($type_contact_id) $sql .= ", fk_c_type_contact = ".((int) $type_contact_id); - if ($fk_socpeople) $sql .= ", fk_socpeople = ".((int) $fk_socpeople); + if ($type_contact_id) $sql .= ", fk_c_type_contact = '".$type_contact_id."'"; + if ($fk_socpeople) $sql .= ", fk_socpeople = '".$fk_socpeople."'"; $sql .= " where rowid = ".$rowid; $resql = $this->db->query($sql); if ($resql) { return 0; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete a link to contact line * @@ -1136,7 +1077,7 @@ */ public function delete_contact($rowid, $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user; @@ -1156,14 +1097,16 @@ $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete all links between an object $this and all its contacts * @@ -1173,7 +1116,7 @@ */ public function delete_linked_contact($source = '', $code = '') { - // phpcs:enable + // phpcs:enable $temp = array(); $typeContact = $this->liste_type_contact($source, '', 0, 0, $code); @@ -1192,13 +1135,15 @@ if ($this->db->query($sql)) { return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get array of all contacts for an object * @@ -1210,7 +1155,7 @@ */ public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '') { - // phpcs:enable + // phpcs:enable global $langs; $tab = array(); @@ -1252,7 +1197,9 @@ 'nom'=>$obj->lastname, // For backward compatibility 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); - } else { + } + else + { $tab[$i] = $obj->id; } @@ -1260,7 +1207,9 @@ } return $tab; - } else { + } + else + { $this->error = $this->db->lasterror(); dol_print_error($this->db); return -1; @@ -1278,7 +1227,9 @@ { $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; $sql .= " tc.code, tc.libelle"; + //$sql.= ", s.fk_soc"; $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; + //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe $sql .= " WHERE ec.rowid =".$rowid; $sql .= " AND ec.fk_c_type_contact=tc.rowid"; $sql .= " AND tc.element = '".$this->db->escape($this->element)."'"; @@ -1292,14 +1243,16 @@ $result = $this->update_contact($rowid, $newstatut); $this->db->free($resql); return $result; - } else { + } + else + { $this->error = $this->db->error(); dol_print_error($this->db); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return array with list of possible values for type of contacts * @@ -1312,7 +1265,7 @@ */ public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '') { - // phpcs:enable + // phpcs:enable global $langs; if (empty($order)) $order = 'position'; @@ -1344,7 +1297,9 @@ $i++; } return $tab; - } else { + } + else + { $this->error = $this->db->lasterror(); //dol_print_error($this->db); return null; @@ -1368,8 +1323,6 @@ // phpcs:enable global $langs, $conf; - $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda')); - $tab = array(); $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element"; @@ -1403,8 +1356,6 @@ if ($resql) { $num = $this->db->num_rows($resql); if ($num > 0) { - $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal")); - while ($obj = $this->db->fetch_object($resql)) { $modulename = $obj->element; if (strpos($obj->element, 'project') !== false) { @@ -1420,20 +1371,18 @@ } if ($conf->{$modulename}->enabled) { $libelle_element = $langs->trans('ContactDefault_'.$obj->element); - $tmpelement = $obj->element; - $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code; + $transkey = "TypeContact_".$obj->element."_".$source."_".$obj->code; $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); - if (empty($option)) { + if (empty($option)) $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; - } - else { - $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; - } + else $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; } } } return $tab; - } else { + } + else + { $this->error = $this->db->lasterror(); return null; } @@ -1478,9 +1427,9 @@ if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")"; if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")"; $sql .= " AND ec.fk_c_type_contact = tc.rowid"; - $sql .= " AND tc.element = '".$this->db->escape($element)."'"; - $sql .= " AND tc.source = '".$this->db->escape($source)."'"; - if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'"; + $sql .= " AND tc.element = '".$element."'"; + $sql .= " AND tc.source = '".$source."'"; + if ($code) $sql .= " AND tc.code = '".$code."'"; $sql .= " AND tc.active = 1"; if ($status) $sql .= " AND ec.statut = ".$status; @@ -1493,7 +1442,9 @@ $result[$i] = $obj->fk_socpeople; $i++; } - } else { + } + else + { $this->error = $this->db->error(); return null; } @@ -1501,17 +1452,17 @@ return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load object contact with id=$this->contact_id into $this->contact - * - * @param int $contactid Id du contact. Use this->contact_id if empty. + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load object contact with id=$this->contactid into $this->contact + * + * @param int $contactid Id du contact. Use this->contactid if empty. * @return int <0 if KO, >0 if OK */ public function fetch_contact($contactid = null) { - // phpcs:enable - if (empty($contactid)) $contactid = $this->contact_id; + // phpcs:enable + if (empty($contactid)) $contactid = $this->contactid; if (empty($contactid)) return 0; @@ -1522,7 +1473,7 @@ return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty * @@ -1531,7 +1482,7 @@ */ public function fetch_thirdparty($force_thirdparty_id = 0) { - // phpcs:enable + // phpcs:enable global $conf; if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) @@ -1554,7 +1505,8 @@ } return $result; - } else return -1; + } else + return -1; } @@ -1584,7 +1536,7 @@ return $this->fetch($result->rowid); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load data for barcode into properties ->barcode_type* * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but @@ -1594,7 +1546,7 @@ */ public function fetch_barcode() { - // phpcs:enable + // phpcs:enable global $conf; dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); @@ -1624,7 +1576,9 @@ $this->barcode_type_label = $obj->label; $this->barcode_type_coder = $obj->coder; return 1; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -1633,7 +1587,7 @@ return 0; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the project with id $this->fk_project into this->project * @@ -1641,7 +1595,7 @@ */ public function fetch_projet() { - // phpcs:enable + // phpcs:enable include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility @@ -1655,7 +1609,7 @@ return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the product with id $this->fk_product into this->product * @@ -1663,7 +1617,7 @@ */ public function fetch_product() { - // phpcs:enable + // phpcs:enable include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (empty($this->fk_product)) return 0; @@ -1675,7 +1629,7 @@ return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the user with id $userid into this->user * @@ -1684,14 +1638,14 @@ */ public function fetch_user($userid) { - // phpcs:enable + // phpcs:enable $user = new User($this->db); $result = $user->fetch($userid); $this->user = $user; return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Read linked origin object * @@ -1699,10 +1653,10 @@ */ public function fetch_origin() { - // phpcs:enable + // phpcs:enable if ($this->origin == 'shipping') $this->origin = 'expedition'; if ($this->origin == 'delivery') $this->origin = 'livraison'; - if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur'; + if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur'; $origin = $this->origin; @@ -1712,14 +1666,14 @@ } /** - * Load object from specific field - * - * @param string $table Table element or element line - * @param string $field Field selected - * @param string $key Import key - * @param string $element Element name - * @return int <0 if KO, >0 if OK - */ + * Load object from specific field + * + * @param string $table Table element or element line + * @param string $field Field selected + * @param string $key Import key + * @param string $element Element name + * @return int <0 if KO, >0 if OK + */ public function fetchObjectFrom($table, $field, $key, $element = null) { global $conf; @@ -1831,7 +1785,9 @@ if (empty($this->fields) && method_exists($this, 'fetch')) { $result = $this->fetch($id); - } else { + } + else + { $result = $this->fetchCommon($id); } if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors @@ -1843,22 +1799,22 @@ if (property_exists($this, $field)) $this->$field = $value; $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); return -2; } - } else { - if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS'; - } else { - $this->error = $this->db->lasterror(); - } + } + else + { + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load properties id_previous and id_next by comparing $fieldid with $this->ref * @@ -1869,7 +1825,7 @@ */ public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user; if (!$this->table_element) @@ -1896,10 +1852,11 @@ if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { $tmparray = explode('@', $this->ismultientitymanaged); $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity - } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid + } + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc"; - $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)'; if (!empty($filter)) @@ -1910,7 +1867,8 @@ if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { $tmparray = explode('@', $this->ismultientitymanaged); $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity - } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid + } + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { @@ -1941,18 +1899,17 @@ $row = $this->db->fetch_row($result); $this->ref_previous = $row[0]; + $sql = "SELECT MIN(te.".$fieldid.")"; $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te"; if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug"; } - if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { - $tmparray = explode('@', $this->ismultientitymanaged); - $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity - } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 'fk_soc@societe') $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc"; - $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)'; if (!empty($filter)) @@ -1960,10 +1917,8 @@ if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility $sql .= $filter; } - if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { - $tmparray = explode('@', $this->ismultientitymanaged); - $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity - } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 'fk_soc@societe') $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { @@ -1976,10 +1931,6 @@ $sql .= ' AND te.entity IN ('.getEntity($this->element).')'; } } - if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') { - $tmparray = explode('@', $this->ismultientitymanaged); - $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')'; - } if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid; if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)'; if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid; @@ -2015,7 +1966,7 @@ while ($i < $num) { if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; - else $contactAlreadySelected[$i] = $tab[$i]['id']; + else $contactAlreadySelected[$i] = $tab[$i]['id']; $i++; } return $contactAlreadySelected; @@ -2042,12 +1993,14 @@ if ($projectid) $sql .= ' SET fk_project = '.$projectid; else $sql .= ' SET fk_project = NULL'; $sql .= ' WHERE rowid = '.$this->id; - } elseif ($this->table_element == 'actioncomm') // Special case for actioncomm + } + elseif ($this->table_element == 'actioncomm') // Special case for actioncomm { if ($projectid) $sql .= ' SET fk_project = '.$projectid; else $sql .= ' SET fk_project = NULL'; $sql .= ' WHERE id = '.$this->id; - } else // Special case for old architecture objects + } + else // Special case for old architecture objects { if ($projectid) $sql .= ' SET fk_projet = '.$projectid; else $sql .= ' SET fk_projet = NULL'; @@ -2059,7 +2012,9 @@ { $this->fk_project = $projectid; return 1; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -2091,12 +2046,16 @@ // for supplier if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; return 1; - } else { - dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); $this->error = $this->db->error(); return -1; } - } else { + } + else + { dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); $this->error = 'Status of the object is incompatible '.$this->statut; return -2; @@ -2128,12 +2087,16 @@ if ($rate) $this->setMulticurrencyRate($rate, 2); return 1; - } else { - dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); $this->error = $this->db->error(); return -1; } - } else { + } + else + { dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); $this->error = 'Status of the object is incompatible '.$this->statut; return -2; @@ -2214,16 +2177,14 @@ $this->updateline( $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, - $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice, - $line->ref_supplier + $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice ); break; case 'invoice_supplier': $this->updateline( $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, - $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice, - $line->ref_supplier + $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice ); break; default: @@ -2234,12 +2195,16 @@ } return 1; - } else { - dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); $this->error = $this->db->error(); return -1; } - } else { + } + else + { dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); $this->error = 'Status of the object is incompatible '.$this->statut; return -2; @@ -2273,54 +2238,22 @@ if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; $this->cond_reglement = $id; // for compatibility return 1; - } else { - dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); $this->error = $this->db->error(); return -1; } - } else { + } + else + { dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); $this->error = 'Status of the object is incompatible '.$this->statut; return -2; } } - /** - * Change the transport mode methods - * - * @param int $id Id of new payment method - * @return int >0 if OK, <0 if KO - */ - public function setTransportMode($id) - { - dol_syslog(get_class($this).'::setTransportMode('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'fk_transport_mode'; - if ($this->element == 'societe') $fieldname = 'transport_mode'; - if (get_class($this) == 'Fournisseur') $fieldname = 'transport_mode_supplier'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL'); - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->transport_mode_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->transport_mode_supplier_id = $id; - return 1; - } else { - dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } - } /** * Change the retained warranty payments terms @@ -2330,29 +2263,33 @@ */ public function setRetainedWarrantyPaymentTerms($id) { - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'retained_warranty_fk_cond_reglement'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->retained_warranty_fk_cond_reglement = $id; - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + $fieldname = 'retained_warranty_fk_cond_reglement'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$id; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->retained_warranty_fk_cond_reglement = $id; + return 1; + } + else + { + dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } /** @@ -2374,9 +2311,11 @@ { $this->fk_delivery_address = $id; return 1; - } else { + } + else + { $this->error = $this->db->error(); - dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error); + dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); return -1; } } @@ -2489,15 +2428,18 @@ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; $sql .= " WHERE rowid = ".$this->id; + // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; + // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->model_pdf = $modelpdf; - $this->modelpdf = $modelpdf; // For bakward compatibility + $this->modelpdf = $modelpdf; return 1; - } else { + } + else + { dol_print_error($this->db); return 0; } @@ -2539,7 +2481,9 @@ dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); $this->error = $this->db->lasterror(); $error++; - } else { + } + else + { if (!$notrigger) { // Call trigger @@ -2553,7 +2497,9 @@ { $this->db->rollback(); return -1; - } else { + } + else + { $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account; $this->db->commit(); return 1; @@ -2563,7 +2509,7 @@ // TODO: Move line related operations to CommonObjectLine? - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Save a new position (field rang) for details lines. * You can choose to set position for lines with already a position or lines without any position defined. @@ -2575,7 +2521,7 @@ */ public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true) { - // phpcs:enable + // phpcs:enable if (!$this->table_element_line) { dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR); @@ -2600,10 +2546,12 @@ { $row = $this->db->fetch_row($resql); $nl = $row[0]; - } else dol_print_error($this->db); + } + else dol_print_error($this->db); if ($nl > 0) { - // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents. + // The goal of this part is to reorder all lines, with all children lines sharing the same + // counter that parents. $rows = array(); // We first search all lines that are parent lines (for multilevel details lines) @@ -2641,7 +2589,9 @@ $this->updateRangOfLine($row, ($key + 1)); } } - } else { + } + else + { dol_print_error($this->db); } } @@ -2651,11 +2601,10 @@ /** * Get children of line * - * @param int $id Id of parent line - * @param int $includealltree 0 = 1st level child, 1 = All level child - * @return array Array with list of children lines id - */ - public function getChildrenOfLine($id, $includealltree = 0) + * @param int $id Id of parent line + * @return array Array with list of children lines id + */ + public function getChildrenOfLine($id) { $rows = array(); @@ -2668,17 +2617,20 @@ $resql = $this->db->query($sql); if ($resql) { - if ($this->db->num_rows($resql) > 0) { - while ($row = $this->db->fetch_row($resql)) { - $rows[] = $row[0]; - if (!empty($includealltree)) $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree); - } - } - } + $i = 0; + $num = $this->db->num_rows($resql); + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + $rows[$i] = $row[0]; + $i++; + } + } + return $rows; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update a line to have a lower rank * @@ -2688,7 +2640,7 @@ */ public function line_up($rowid, $fk_parent_line = true) { - // phpcs:enable + // phpcs:enable $this->line_order(false, 'ASC', $fk_parent_line); // Get rang of line @@ -2698,7 +2650,7 @@ $this->updateLineUp($rowid, $rang); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update a line to have a higher rank * @@ -2708,7 +2660,7 @@ */ public function line_down($rowid, $fk_parent_line = true) { - // phpcs:enable + // phpcs:enable $this->line_order(false, 'ASC', $fk_parent_line); // Get rang of line @@ -2743,7 +2695,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update position of line with ajax (rang) * @@ -2752,7 +2704,7 @@ */ public function line_ajaxorder($rows) { - // phpcs:enable + // phpcs:enable $num = count($rows); for ($i = 0; $i < $num; $i++) { @@ -2785,7 +2737,9 @@ { dol_print_error($this->db); } - } else { + } + else + { dol_print_error($this->db); } } @@ -2817,7 +2771,9 @@ { dol_print_error($this->db); } - } else { + } + else + { dol_print_error($this->db); } } @@ -2862,7 +2818,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get max value used for position of line (rang) * @@ -2871,9 +2827,9 @@ */ public function line_max($fk_parent_line = 0) { - // phpcs:enable - $positionfield = 'rang'; - if ($this->table_element == 'bom_bom') $positionfield = 'position'; + // phpcs:enable + $positionfield = 'rang'; + if ($this->table_element == 'bom') $positionfield = 'position'; // Search the last rang with fk_parent_line if ($fk_parent_line) @@ -2890,13 +2846,16 @@ if (!empty($row[0])) { return $row[0]; - } else { + } + else + { return $this->getRangOfLine($fk_parent_line); } } } // If not, search the last rang of element - else { + else + { $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line; $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; @@ -2910,7 +2869,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update external ref of element * @@ -2919,7 +2878,7 @@ */ public function update_ref_ext($ref_ext) { - // phpcs:enable + // phpcs:enable if (!$this->table_element) { dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); @@ -2935,13 +2894,15 @@ { $this->ref_ext = $ref_ext; return 1; - } else { + } + else + { $this->error = $this->db->error(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update note of element * @@ -2951,7 +2912,7 @@ */ public function update_note($note, $suffix = '') { - // phpcs:enable + // phpcs:enable global $user; if (!$this->table_element) @@ -2966,14 +2927,12 @@ dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); return -2; } - - $newsuffix = $suffix; - // Special cas - if ($this->table_element == 'product' && $newsuffix == '_private') $newsuffix = ''; + //var_dump($this->table_element);exit; + if ($this->table_element == 'product') $suffix = ''; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL"); + $sql .= " SET note".$suffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL"); $sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id; $sql .= " WHERE rowid =".$this->id; @@ -2982,18 +2941,21 @@ { if ($suffix == '_public') $this->note_public = $note; elseif ($suffix == '_private') $this->note_private = $note; - else { + else + { $this->note = $note; // deprecated $this->note_private = $note; } return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update public note (kept for backward compatibility) * @@ -3004,11 +2966,11 @@ */ public function update_note_public($note) { - // phpcs:enable + // phpcs:enable return $this->update_note($note, '_public'); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). * Must be called at end of methods addline or updateline. @@ -3021,16 +2983,16 @@ */ public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null) { - // phpcs:enable + // phpcs:enable global $conf, $hookmanager, $action; - $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller); - $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - return 1; // replacement code - } elseif ($reshook < 0) { - return -1; // failure - } // reshook = 0 => execute normal code + $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller); + $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + return 1; // replacement code + } elseif ($reshook < 0) { + return -1; // failure + } // reshook = 0 => execute normal code // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield) $MODULE = ""; @@ -3194,7 +3156,7 @@ $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0; // Situations totals - if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) + if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) { $prev_sits = $this->get_prev_sits(); @@ -3252,10 +3214,14 @@ if (!$error) { return 1; - } else { + } + else + { return -1; } - } else { + } + else + { dol_print_error($this->db, 'Bad request in update_price'); return -1; } @@ -3300,7 +3266,9 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; @@ -3309,7 +3277,7 @@ /** * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into - * this->linkedObjectsIds array + + * this->linkedObjectsIds array and * this->linkedObjects array if $loadalsoobjects = 1 * Possible usage for parameters: * - all parameters empty -> we look all link to current object (current object can be source or target) @@ -3371,16 +3339,19 @@ { if ($justsource) { - $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; - if ($withtargettype) $sql .= " AND targettype = '".$this->db->escape($targettype)."'"; - } elseif ($justtarget) - { - $sql .= "fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; - if ($withsourcetype) $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'"; - } - } else { - $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."')"; - $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."')"; + $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; + if ($withtargettype) $sql .= " AND targettype = '".$targettype."'"; + } + elseif ($justtarget) + { + $sql .= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; + if ($withsourcetype) $sql .= " AND sourcetype = '".$sourcetype."'"; + } + } + else + { + $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; + $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; } $sql .= ' ORDER BY '.$orderby; @@ -3398,11 +3369,14 @@ if ($justsource) { $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target; - } elseif ($justtarget) + } + elseif ($justtarget) { $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source; } - } else { + } + else + { if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) { $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target; @@ -3422,7 +3396,6 @@ { // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) $module = $element = $subelement = $objecttype; - $regs = array(); if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) { @@ -3434,23 +3407,32 @@ // To work with non standard classpath or module name if ($objecttype == 'facture') { $classpath = 'compta/facture/class'; - } elseif ($objecttype == 'facturerec') { + } + elseif ($objecttype == 'facturerec') { $classpath = 'compta/facture/class'; $module = 'facture'; - } elseif ($objecttype == 'propal') { + } + elseif ($objecttype == 'propal') { $classpath = 'comm/propal/class'; - } elseif ($objecttype == 'supplier_proposal') { + } + elseif ($objecttype == 'supplier_proposal') { $classpath = 'supplier_proposal/class'; - } elseif ($objecttype == 'shipping') { + } + elseif ($objecttype == 'shipping') { $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; - } elseif ($objecttype == 'delivery') { - $classpath = 'delivery/class'; $subelement = 'delivery'; $module = 'delivery_note'; - } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { + } + elseif ($objecttype == 'delivery') { + $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; + } + elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { $classpath = 'fourn/class'; $module = 'fournisseur'; - } elseif ($objecttype == 'fichinter') { + } + elseif ($objecttype == 'fichinter') { $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; - } elseif ($objecttype == 'subscription') { + } + elseif ($objecttype == 'subscription') { $classpath = 'adherents/class'; $module = 'adherent'; - } elseif ($objecttype == 'contact') { + } + elseif ($objecttype == 'contact') { $module = 'societe'; } @@ -3459,17 +3441,23 @@ if ($objecttype == 'order') { $classfile = 'commande'; $classname = 'Commande'; - } elseif ($objecttype == 'invoice_supplier') { + } + elseif ($objecttype == 'invoice_supplier') { $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; - } elseif ($objecttype == 'order_supplier') { + } + elseif ($objecttype == 'order_supplier') { $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; - } elseif ($objecttype == 'supplier_proposal') { + } + elseif ($objecttype == 'supplier_proposal') { $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; - } elseif ($objecttype == 'facturerec') { + } + elseif ($objecttype == 'facturerec') { $classfile = 'facture-rec'; $classname = 'FactureRec'; - } elseif ($objecttype == 'subscription') { + } + elseif ($objecttype == 'subscription') { $classfile = 'subscription'; $classname = 'Subscription'; - } elseif ($objecttype == 'project' || $objecttype == 'projet') { + } + elseif ($objecttype == 'project' || $objecttype == 'projet') { $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project'; } @@ -3493,13 +3481,17 @@ } } } - } else { + } + else + { unset($this->linkedObjectsIds[$objecttype]); } } } return 1; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -3530,7 +3522,8 @@ $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'"; $sql .= " WHERE fk_target = ".$this->id; $sql .= " AND targettype = '".$this->db->escape($this->element)."'"; - } elseif ($updatetarget) + } + elseif ($updatetarget) { $sql .= "fk_target = ".$targetid; $sql .= ", targettype = '".$this->db->escape($targettype)."'"; @@ -3542,7 +3535,9 @@ if ($this->db->query($sql)) { return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } @@ -3577,16 +3572,21 @@ if ($rowid > 0) { $sql .= " rowid = ".$rowid; - } else { + } + else + { if ($deletesource) { $sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; $sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'"; - } elseif ($deletetarget) + } + elseif ($deletetarget) { $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'"; - } else { + } + else + { $sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')"; $sql .= " OR"; $sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')"; @@ -3597,7 +3597,9 @@ if ($this->db->query($sql)) { return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; return -1; @@ -3674,12 +3676,16 @@ } return 1; - } else { + } + else + { $this->db->rollback(); dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR); return -1; } - } else { + } + else + { $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; @@ -3718,8 +3724,11 @@ { $this->canvas = $obj->canvas; return 1; - } else return 0; - } else { + } + else return 0; + } + else + { dol_print_error($this->db); return -1; } @@ -3792,13 +3801,16 @@ if (is_numeric($elementname)) // old usage { $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table); - } else // new usage: $elementname=Translation key + } + else // new usage: $elementname=Translation key { $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); } break; // We found at least one, we stop here } - } else { + } + else + { $this->errors[] = $this->db->lasterror(); return -1; } @@ -3807,7 +3819,8 @@ { $this->errors[] = "ErrorRecordHasChildren"; return $haschild; - } else return 0; + } + else return 0; } /** @@ -3899,7 +3912,8 @@ { if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is '' $totalToShip += $line->qty_shipped; // defined for shipment only - } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) + } + elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) { if (empty($totalToShip)) $totalToShip = 0; $totalToShip += $line->qty; // defined for reception only @@ -3909,12 +3923,13 @@ if ($this->element == 'shipping') { // for shipments $qty = $line->qty_shipped ? $line->qty_shipped : 0; - } else { + } + else { $qty = $line->qty ? $line->qty : 0; } $weight = $line->weight ? $line->weight : 0; - ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; + ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; $volume = $line->volume ? $line->volume : 0; ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0; @@ -3936,7 +3951,8 @@ { $trueWeightUnit = pow(10, $weightUnit); $totalWeight += $weight * $qty * $trueWeightUnit; - } else { + } + else { if ($weight_units == 99) { // conversion 1 Pound = 0.45359237 KG $trueWeightUnit = 0.45359237; @@ -3945,7 +3961,8 @@ // conversion 1 Ounce = 0.0283495 KG $trueWeightUnit = 0.0283495; $totalWeight += $weight * $qty * $trueWeightUnit; - } else { + } + else { $totalWeight += $weight * $qty; // This may be wrong if we mix different units } } @@ -3955,7 +3972,9 @@ $trueVolumeUnit = pow(10, $volumeUnit); //print $line->volume; $totalVolume += $volume * $qty * $trueVolumeUnit; - } else { + } + else + { $totalVolume += $volume * $qty; // This may be wrong if we mix different units } } @@ -3986,10 +4005,110 @@ $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; - } else { + } + else + { $this->db->commit(); return 1; } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return incoterms informations + * TODO Use a cache for label get + * + * @return string incoterms info + */ + public function display_incoterms() + { + // phpcs:enable + $out = ''; + $this->label_incoterms = ''; + if (!empty($this->fk_incoterms)) + { + $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; + $result = $this->db->query($sql); + if ($result) + { + $res = $this->db->fetch_object($result); + $out .= $res->code; + } + } + + $out .= (($res->code && $this->location_incoterms) ? ' - ' : '').$this->location_incoterms; + + return $out; + } + + /** + * Return incoterms informations for pdf display + * + * @return string incoterms info + */ + public function getIncotermsForPDF() + { + $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num > 0) + { + $res = $this->db->fetch_object($resql); + return 'Incoterm : '.$res->code.' - '.$this->location_incoterms; + } + else + { + return ''; + } + } + else + { + $this->errors[] = $this->db->lasterror(); + return false; + } + } + + /** + * Define incoterms values of current object + * + * @param int $id_incoterm Id of incoterm to set or '' to remove + * @param string $location location of incoterm + * @return int <0 if KO, >0 if OK + */ + public function setIncoterms($id_incoterm, $location) + { + if ($this->id && $this->table_element) + { + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); + $sql .= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); + $sql .= " WHERE rowid = ".$this->id; + dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->fk_incoterms = $id_incoterm; + $this->location_incoterms = $location; + + $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; + $res = $this->db->query($sql); + if ($res) + { + $obj = $this->db->fetch_object($res); + $this->label_incoterms = $obj->libelle; + } + return 1; + } + else + { + $this->errors[] = $this->db->lasterror(); + return -1; + } + } + else return -1; } @@ -4030,7 +4149,9 @@ if (!empty($module)) { $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php'); - } else { + } + else + { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php'; } @@ -4095,7 +4216,9 @@ if (!empty($module)) { $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php'); - } else { + } + else + { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php'; } if (empty($conf->file->strict_mode)) { @@ -4122,7 +4245,9 @@ { $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element); $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - } else { + } + else + { $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line); $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } @@ -4203,7 +4328,9 @@ } $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label; - } else { + } + else + { $label = $line->product_label; } @@ -4222,7 +4349,9 @@ if (!empty($module)) { $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php'); - } else { + } + else + { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php'; } @@ -4251,7 +4380,9 @@ if (!empty($module)) { $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php'); - } else { + } + else + { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php'; } @@ -4290,13 +4421,13 @@ print ''.$langs->trans('PriceUHT').''; if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency').''; print ''.$langs->trans('Qty').''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) + if ($conf->global->PRODUCT_USE_UNITS) { print ''.$langs->trans('Unit').''; } print ''.$langs->trans('ReductionShort').''; - print ''.$form->showCheckAddButtons('checkforselect', 1).''; - print ''; + print ''.$form->showCheckAddButtons('checkforselect', 1).''; + print ''; $i = 0; if (!empty($this->lines)) @@ -4311,7 +4442,9 @@ $action = ''; $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } - } else { + } + else + { $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines); } @@ -4341,19 +4474,23 @@ if (!empty($line->date_start)) { $date_start = $line->date_start; - } else { + } + else + { $date_start = $line->date_debut_prevue; if ($line->date_debut_reel) $date_start = $line->date_debut_reel; } if (!empty($line->date_end)) { $date_end = $line->date_end; - } else { + } + else + { $date_end = $line->date_fin_prevue; if ($line->date_fin_reel) $date_end = $line->date_fin_reel; } - $this->tpl['id'] = $line->id; + $this->tpl['id'] = $line->id; $this->tpl['label'] = ''; if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow'); @@ -4363,7 +4500,8 @@ $discount = new DiscountAbsolute($this->db); $discount->fk_soc = $this->socid; $this->tpl['label'] .= $discount->getNomUrl(0, 'discount'); - } elseif (!empty($line->fk_product)) + } + elseif (!empty($line->fk_product)) { $productstatic = new Product($this->db); $productstatic->id = $line->fk_product; @@ -4381,7 +4519,9 @@ { $this->tpl['label'] .= get_date_range($date_start, $date_end); } - } else { + } + else + { $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product'))); if (!empty($line->desc)) { $this->tpl['label'] .= $line->desc; @@ -4403,37 +4543,44 @@ $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); - } elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object + } + elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); - } elseif ($line->desc == '(EXCESS RECEIVED)') + } + elseif ($line->desc == '(EXCESS RECEIVED)') { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); - } elseif ($line->desc == '(EXCESS PAID)') + } + elseif ($line->desc == '(EXCESS PAID)') { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); - } else { + } + else + { $this->tpl['description'] = dol_trunc($line->desc, 60); } - } else { + } + else + { $this->tpl['description'] = ' '; } - // VAT Rate - $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); - $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : ''; - if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')'; + // VAT Rate + $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); + $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : ''; + if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')'; $this->tpl['price'] = price($line->subprice); $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; - if (!empty($conf->global->PRODUCT_USE_UNITS)) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long')); + if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long')); $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; // Is the line strike or not @@ -4448,7 +4595,9 @@ if (!empty($module)) { $tpl = dol_buildpath($reldir.'/originproductline.tpl.php'); - } else { + } + else + { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php'; } @@ -4462,7 +4611,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add resources to the current object : add entry into llx_element_resources * Need $this->element & $this->id @@ -4475,7 +4624,7 @@ */ public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0) { - // phpcs:enable + // phpcs:enable $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources ("; @@ -4499,14 +4648,16 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete a link to resource line * @@ -4517,7 +4668,7 @@ */ public function delete_resource($rowid, $element, $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user; $this->db->begin(); @@ -4533,7 +4684,9 @@ $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; - } else { + } + else + { if (!$notrigger) { $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); @@ -4567,7 +4720,7 @@ * Common function for all objects extending CommonObject for generating documents * * @param string $modelspath Relative folder where generators are placed - * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example. + * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf','alpha') for example. * @param Translate $outputlangs Output language to use * @param int $hidedetails 1 to hide details. 0 by default * @param int $hidedesc 1 to hide product description. 0 by default @@ -4587,255 +4740,255 @@ if (empty($reshook)) { - dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - - if (empty($modele)) { - $this->error = 'BadValueForParameterModele'; - return -1; - } - - // Increase limit for PDF build - $err = error_reporting(); - error_reporting(0); - @set_time_limit(120); - error_reporting($err); - - // If selected model is a filename template (then $modele="modelname" or "modelname:filename") - $tmp = explode(':', $modele, 2); - if (!empty($tmp[1])) - { - $modele = $tmp[0]; - $srctemplatepath = $tmp[1]; - } - - // Search template files + dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); + + // Increase limit for PDF build + $err = error_reporting(); + error_reporting(0); + @set_time_limit(120); + error_reporting($err); + + // If selected model is a filename template (then $modele="modelname" or "modelname:filename") + $tmp = explode(':', $modele, 2); + if (!empty($tmp[1])) + { + $modele = $tmp[0]; + $srctemplatepath = $tmp[1]; + } + + // Search template files $file = ''; $classname = ''; $filefound = ''; - $dirmodels = array('/'); - if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { - foreach (array('doc', 'pdf') as $prefix) - { - if (in_array(get_class($this), array('Adherent'))) { - // Member module use prefix_modele.class.php - $file = $prefix."_".$modele.".class.php"; - } else { - // Other module use prefix_modele.modules.php - $file = $prefix."_".$modele.".modules.php"; - } - - // On verifie l'emplacement du modele - $file = dol_buildpath($reldir.$modelspath.$file, 0); - if (file_exists($file)) { - $filefound = $file; - $classname = $prefix.'_'.$modele; - break; - } - } - if ($filefound) break; - } - - // If generator was found - if ($filefound) - { - global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. - - require_once $file; - - $obj = new $classname($this->db); - - // If generator is ODT, we must have srctemplatepath defined, if not we set it. - if ($obj->type == 'odt' && empty($srctemplatepath)) - { - $varfortemplatedir = $obj->scandir; - if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) - { - $dirtoscan = $conf->global->$varfortemplatedir; - - $listoffiles = array(); - - // Now we add first model found in directories scanned - $listofdir = explode(',', $dirtoscan); - foreach ($listofdir as $key => $tmpdir) - { - $tmpdir = trim($tmpdir); - $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); - if (!$tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { - $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); - } - } - - if (count($listoffiles)) - { - foreach ($listoffiles as $record) - { - $srctemplatepath = $record['fullname']; - break; - } - } - } - - if (empty($srctemplatepath)) - { - $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; - return -1; - } - } - - if ($obj->type == 'odt' && !empty($srctemplatepath)) - { - if (!dol_is_file($srctemplatepath)) - { - dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); - $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; - return -1; - } - } - - // We save charset_output to restore it because write_file can change it if needed for - // output format that does not support UTF8. - $sav_charset_output = $outputlangs->charset_output; - - if (in_array(get_class($this), array('Adherent'))) - { - $arrayofrecords = array(); // The write_file of templates of adherent class need this var - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); - } else { - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); - } - // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. - - if ($resultwritefile > 0) - { - $outputlangs->charset_output = $sav_charset_output; - - // We delete old preview - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_delete_preview($this); - - // Index file in database - if (!empty($obj->result['fullpath'])) - { - $destfull = $obj->result['fullpath']; - $upload_dir = dirname($destfull); - $destfile = basename($destfull); - $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); - - if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir - { - $filename = basename($destfile); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile = new EcmFiles($this->db); - $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); - - // Set the public "share" key - $setsharekey = false; - if ($this->element == 'propal') - { - $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok - if ($useonlinesignature) $setsharekey = true; - if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; - } - if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - - if ($setsharekey) { - if (empty($ecmfile->share)) // Because object not found or share not set yet - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $ecmfile->share = getRandomPassword(true); - } - } - - if ($result > 0) - { - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $result = $ecmfile->update($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } else { - $ecmfile->entity = $conf->entity; - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $ecmfile->src_object_type = $this->table_element; - $ecmfile->src_object_id = $this->id; - - $result = $ecmfile->create($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } - - /*$this->result['fullname']=$destfull; + $dirmodels = array('/'); + if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + foreach (array('doc', 'pdf') as $prefix) + { + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + else $file = $prefix."_".$modele.".modules.php"; + + // On verifie l'emplacement du modele + $file = dol_buildpath($reldir.$modelspath.$file, 0); + if (file_exists($file)) + { + $filefound = $file; + $classname = $prefix.'_'.$modele; + break; + } + } + if ($filefound) break; + } + + // If generator was found + if ($filefound) + { + global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. + + require_once $file; + + $obj = new $classname($this->db); + + // If generator is ODT, we must have srctemplatepath defined, if not we set it. + if ($obj->type == 'odt' && empty($srctemplatepath)) + { + $varfortemplatedir = $obj->scandir; + if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) + { + $dirtoscan = $conf->global->$varfortemplatedir; + + $listoffiles = array(); + + // Now we add first model found in directories scanned + $listofdir = explode(',', $dirtoscan); + foreach ($listofdir as $key => $tmpdir) + { + $tmpdir = trim($tmpdir); + $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); + if (!$tmpdir) { unset($listofdir[$key]); continue; } + if (is_dir($tmpdir)) + { + $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); + if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + } + } + + if (count($listoffiles)) + { + foreach ($listoffiles as $record) + { + $srctemplatepath = $record['fullname']; + break; + } + } + } + + if (empty($srctemplatepath)) + { + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; + return -1; + } + } + + if ($obj->type == 'odt' && !empty($srctemplatepath)) + { + if (!dol_is_file($srctemplatepath)) + { + dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; + return -1; + } + } + + // We save charset_output to restore it because write_file can change it if needed for + // output format that does not support UTF8. + $sav_charset_output = $outputlangs->charset_output; + + if (in_array(get_class($this), array('Adherent'))) + { + $arrayofrecords = array(); // The write_file of templates of adherent class need this var + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); + } + else + { + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); + } + // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. + + if ($resultwritefile > 0) + { + $outputlangs->charset_output = $sav_charset_output; + + // We delete old preview + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + dol_delete_preview($this); + + // Index file in database + if (!empty($obj->result['fullpath'])) + { + $destfull = $obj->result['fullpath']; + $upload_dir = dirname($destfull); + $destfile = basename($destfull); + $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); + + if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + { + $filename = basename($destfile); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile = new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); + + // Set the public "share" key + $setsharekey = false; + if ($this->element == 'propal') + { + $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok + if ($useonlinesignature) $setsharekey = true; + if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; + } + if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + + if ($setsharekey) { + if (empty($ecmfile->share)) // Because object not found or share not set yet + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } + + if ($result > 0) + { + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $result = $ecmfile->update($user); + if ($result < 0) { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } + else + { + $ecmfile->entity = $conf->entity; + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $ecmfile->src_object_type = $this->table_element; + $ecmfile->src_object_id = $this->id; + + $result = $ecmfile->create($user); + if ($result < 0) { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } + + /*$this->result['fullname']=$destfull; $this->result['filepath']=$ecmfile->filepath; $this->result['filename']=$ecmfile->filename;*/ - //var_dump($obj->update_main_doc_field);exit; - - // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) - $update_main_doc_field = 0; - if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; - if ($update_main_doc_field && !empty($this->table_element)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; - $sql .= ' WHERE rowid = '.$this->id; - - $resql = $this->db->query($sql); - if (!$resql) { + //var_dump($obj->update_main_doc_field);exit; + + // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) + $update_main_doc_field = 0; + if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; + if ($update_main_doc_field && !empty($this->table_element)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; + $sql .= ' WHERE rowid = '.$this->id; + + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); } else { - $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; - } - } - } - } else { - dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); - } - - // Success in building document. We build meta file. - dol_meta_create($this); - - return 1; - } else { - $outputlangs->charset_output = $sav_charset_output; - dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); - return -1; - } - } else { - if (!$filefound) { - $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; - dol_print_error('', $this->error); - } else { - $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound); - dol_print_error('', $this->error); - } - return -1; - } - } else return $reshook; + $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; + } + } + } + } + else + { + dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); + } + + // Success in building document. We build meta file. + dol_meta_create($this); + + return 1; + } + else + { + $outputlangs->charset_output = $sav_charset_output; + dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); + return -1; + } + } else { + if (! $filefound) { + $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; + dol_print_error('', $this->error); + } else { + $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound); + dol_print_error('', $this->error); + } + return -1; + } + } + else return $reshook; } /** @@ -4940,7 +5093,9 @@ if (!empty($this->errors)) { $this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. - } else { + } + else + { $this->errors = $interface->errors; } } @@ -4979,7 +5134,7 @@ // Request to get translation values for object $sql = "SELECT rowid, property, lang , value"; $sql .= " FROM ".MAIN_DB_PREFIX."object_lang"; - $sql .= " WHERE type_object = '".$this->db->escape($element)."'"; + $sql .= " WHERE type_object = '".$element."'"; $sql .= " AND fk_object = ".$this->id; //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose @@ -5001,7 +5156,9 @@ if (preg_match('/date/', $type)) { $this->array_languages[$key][$codelang] = $this->db->jdate($value); - } else { + } + else + { $this->array_languages[$key][$codelang] = $value; } @@ -5013,7 +5170,9 @@ if ($numrows) return $numrows; else return 0; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -5062,24 +5221,29 @@ // Clean parameters // TODO GMT date in memory must be GMT so we should add gm=true in parameters $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]); - } elseif (in_array($key_type, array('datetime'))) + } + elseif (in_array($key_type, array('datetime'))) { // Clean parameters // TODO GMT date in memory must be GMT so we should add gm=true in parameters $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]); - } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) + } + elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) { $value_arr = GETPOST($postfieldkey, 'array'); // check if an array if (!empty($value_arr)) { - $value_key = implode(',', $value_arr); + $value_key = implode($value_arr, ','); } else { $value_key = ''; } - } elseif (in_array($key_type, array('price', 'double'))) + } + elseif (in_array($key_type, array('price', 'double'))) { $value_arr = GETPOST($postfieldkey, 'alpha'); $value_key = price2num($value_arr); - } else { + } + else + { $value_key = GETPOST($postfieldkey); if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = ''; } @@ -5135,7 +5299,7 @@ global $conf, $extrafields; if (empty($rowid)) $rowid = $this->id; - if (empty($rowid) && isset($this->rowid)) $rowid = $this->rowid; // deprecated + if (empty($rowid)) $rowid = $this->rowid; // To avoid SQL errors. Probably not the better solution though if (!$this->table_element) { @@ -5159,7 +5323,9 @@ $extrafields->fetch_name_optionals_label($this->table_element); } $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null); - } else { + } + else + { global $extrafields; dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING); } @@ -5179,7 +5345,7 @@ } } $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; - $sql .= " WHERE fk_object = ".((int) $rowid); + $sql .= " WHERE fk_object = ".$rowid; //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose $resql = $this->db->query($sql); @@ -5200,7 +5366,9 @@ { //var_dump($extrafields->attributes[$this->table_element]['type'][$key]); $this->array_options["options_".$key] = $this->db->jdate($value); - } else { + } + else + { $this->array_options["options_".$key] = $value; } @@ -5224,7 +5392,9 @@ if ($numrows) return $numrows; else return 0; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -5257,7 +5427,9 @@ $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; - } else { + } + else + { $this->db->commit(); return 1; } @@ -5291,7 +5463,7 @@ $extrafields = new ExtraFields($this->db); $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element); - // Eliminate copied source object extra fields that do not exist in target object + //Eliminate copied source object extra_fields that do not exist in target object $new_array_options = array(); foreach ($this->array_options as $key => $value) { if (in_array(substr($key, 8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test @@ -5309,16 +5481,14 @@ $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey]; $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey]; - // Similar code than into insertExtraFields - if ($attributeRequired) + if ($attributeRequired) { $mandatorypb = false; if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true; if ($this->array_options[$key] === '') $mandatorypb = true; - if ($attributeType == 'sellist' && $this->array_options[$key] == '0') $mandatorypb = true; if ($mandatorypb) { - dol_syslog("Mandatory extra field ".$key." is empty"); + dol_syslog("Mandatory extra field ".$key." is empty"); $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); return -1; } @@ -5332,34 +5502,37 @@ if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) { $value = dol_eval($attrfieldcomputed, 1, 0); - dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); - $new_array_options[$key] = $value; - } else { + dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); + $new_array_options[$key] = $value; + } + else + { $new_array_options[$key] = null; } } - switch ($attributeType) + switch ($attributeType) { case 'int': if (!is_numeric($value) && $value != '') { $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; - } elseif ($value == '') + } + elseif ($value == '') { $new_array_options[$key] = null; } break; - case 'price': - case 'double': + case 'double': $value = price2num($value); if (!is_numeric($value) && $value != '') { - dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); + dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; - } elseif ($value == '') + } + elseif ($value == '') { $new_array_options[$key] = null; } @@ -5390,20 +5563,28 @@ if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update. { $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } else { + } + else + { // var_dump($algo); $newvalue = dol_hash($this->array_options[$key], $algo); $new_array_options[$key] = $newvalue; } - } else { + } + else + { $new_array_options[$key] = $this->array_options[$key]; // Value is kept } } - } else // Common usage + } + else // Common usage { $new_array_options[$key] = $this->array_options[$key]; } break; + case 'price': + $new_array_options[$key] = price2num($this->array_options[$key]); + break; case 'date': case 'datetime': // If data is a string instead of a timestamp, we convert it @@ -5423,19 +5604,24 @@ if ($value == '-1') // -1 is key for no defined in combo list of objects { $new_array_options[$key] = ''; - } elseif ($value) { + } + elseif ($value) + { $object = new $InfoFieldList[0]($this->db); - if (is_numeric($value)) $res = $object->fetch($value); // Common case - else $res = $object->fetch('', $value); // For compatibility + if (is_numeric($value)) $res = $object->fetch($value); + else $res = $object->fetch('', $value); if ($res > 0) $new_array_options[$key] = $object->id; - else { + else + { $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found"; $this->db->rollback(); return -1; } } - } else { + } + else + { dol_syslog('Error bad setup of extrafield', LOG_WARNING); } break; @@ -5461,39 +5647,51 @@ $sql .= ",".$attributeKey; } // We must insert a default value for fields for other entities that are mandatory to avoid not null error - if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) { - foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) { - if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously - $sql .= ",".$tmpkey; - } - } + if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) + { + foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) + { + if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously + { + $sql .= ",".$tmpkey; + } + } } $sql .= ") VALUES (".$this->id; - foreach ($new_array_options as $key => $value) { + foreach ($new_array_options as $key => $value) + { $attributeKey = substr($key, 8); // Remove 'options_' prefix // Add field of attribute - if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator) - if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') { + if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator) + { + if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') + { $sql .= ",'".$this->db->escape($new_array_options[$key])."'"; - } else { + } + else + { $sql .= ",null"; } } } // We must insert a default value for fields for other entities that are mandatory to avoid not null error - if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) { - foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) { - if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously - if (in_array($tmpval, array('int', 'double', 'price'))) $sql .= ", 0"; - else $sql .= ", ''"; - } - } + if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) + { + foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) + { + if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously + { + if (in_array($tmpval, array('int', 'double'))) $sql .= ", 0"; + else $sql .= ", ''"; + } + } } $sql .= ")"; $resql = $this->db->query($sql); + if (!$resql) { $this->error = $this->db->lasterror(); @@ -5513,11 +5711,14 @@ { $this->db->rollback(); return -1; - } else { + } + else + { $this->db->commit(); return 1; } - } else return 0; + } + else return 0; } /** @@ -5560,7 +5761,8 @@ { $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel); return -1; - } elseif ($value == '') + } + elseif ($value == '') { $new_array_languages[$key] = null; } @@ -5572,7 +5774,8 @@ dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel); return -1; - } elseif ($value == '') + } + elseif ($value == '') { $new_array_languages[$key] = null; } @@ -5631,15 +5834,18 @@ { $this->db->rollback(); return -1; - } else { + } + else + { $this->db->commit(); return 1; } - } else return 0; - } - - /** - * Update 1 extra field value for the current object. Keep other fields unchanged. + } + else return 0; + } + + /** + * Update an extra field value for the current object. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) * * @param string $key Key of the extrafield to update (without starting 'options_') @@ -5672,36 +5878,9 @@ $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key]; $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key]; $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key]; - $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key]; - - // Similar code than into insertExtraFields - if ($attributeRequired) - { - $mandatorypb = false; - if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') $mandatorypb = true; - if ($this->array_options["options_".$key] === '') $mandatorypb = true; - if ($mandatorypb) - { - dol_syslog("Mandatory extra field options_".$key." is empty"); - $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); - return -1; - } - } //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG); //dol_syslog("attributeType=".$attributeType, LOG_DEBUG); - - if (!empty($attrfieldcomputed)) - { - if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) - { - $value = dol_eval($attrfieldcomputed, 1, 0); - dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); - $this->array_options["options_".$key] = $value; - } else { - $this->array_options["options_".$key] = null; - } - } switch ($attributeType) { @@ -5710,7 +5889,8 @@ { $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; - } elseif ($value === '') + } + elseif ($value === '') { $this->array_options["options_".$key] = null; } @@ -5722,7 +5902,8 @@ dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; - } elseif ($value === '') + } + elseif ($value === '') { $this->array_options["options_".$key] = null; } @@ -5744,65 +5925,31 @@ case 'datetime': $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); break; - /* case 'link': $param_list = array_keys($attributeParam['options']); // 0 : ObjectName // 1 : classPath $InfoFieldList = explode(":", $param_list[0]); dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) + if ($value) { - if ($value == '-1') // -1 is key for no defined in combo list of objects - { - $new_array_options[$key] = ''; - } elseif ($value) { - $object = new $InfoFieldList[0]($this->db); - if (is_numeric($value)) $res = $object->fetch($value); // Common case - else $res = $object->fetch('', $value); // For compatibility - - if ($res > 0) $new_array_options[$key] = $object->id; - else { - $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found"; - $this->db->rollback(); - return -1; - } - } - } else { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); + $object = new $InfoFieldList[0]($this->db); + $object->fetch(0, $value); + $this->array_options["options_".$key] = $object->id; } break; - */ } $this->db->begin(); - - $linealreadyfound = 0; - - // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload) - $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id; - $resql = $this->db->query($sql); - if ($resql) { - $tmpobj = $this->db->fetch_object($resql); - if ($tmpobj) { - $linealreadyfound = $tmpobj->nb; - } - } - - if ($linealreadyfound) { - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'"; - $sql .= " WHERE fk_object = ".$this->id; - } else { - $result = $this->insertExtraFields('', $user); - if ($result < 0) $error++; - } - + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; + $sql .= " WHERE fk_object = ".$this->id; $resql = $this->db->query($sql); if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$error && $trigger) { // Call trigger @@ -5817,11 +5964,14 @@ dol_syslog(__METHOD__.$this->error, LOG_ERR); $this->db->rollback(); return -1; - } else { + } + else + { $this->db->commit(); return 1; } - } else return 0; + } + else return 0; } /** @@ -5854,7 +6004,7 @@ * * @param array $val Array of properties for field to show (used only if ->fields not defined) * @param string $key Key of attribute - * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value, for array type must be array) + * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) * @param string $moreparam To add more parameters on html input tag * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) @@ -5877,46 +6027,38 @@ } $out = ''; - $type = ''; - $isDependList=0; - $param = array(); - $param['options'] = array(); - $reg = array(); - $size = $this->fields[$key]['size']; - // Because we work on extrafields - if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); - $type = 'link'; - } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type = 'link'; - } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3] => 'N'); - $type = 'link'; - } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); - $type = 'sellist'; - } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type = 'sellist'; - } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3] => 'N'); - $type = 'sellist'; - } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { - $param['options'] = array(); - $type = 'varchar'; - $size = $reg[1]; - } elseif (preg_match('/varchar/', $val['type'])) { - $param['options'] = array(); - $type = 'varchar'; - } elseif (is_array($this->fields[$key]['arrayofkeyval'])) { - $param['options'] = $this->fields[$key]['arrayofkeyval']; - $type = 'select'; - } else { - $param['options'] = array(); - $type = $this->fields[$key]['type']; - } - + $type = ''; + $param = array(); + $param['options'] = array(); + $reg = array(); + $size = $this->fields[$key]['size']; + // Because we work on extrafields + if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); + $type = 'link'; + } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'link'; + } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3] => 'N'); + $type = 'link'; + } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'sellist'; + } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { + $param['options'] = array(); + $type = 'varchar'; + $size = $reg[1]; + } elseif (preg_match('/varchar/', $val['type'])) { + $param['options'] = array(); + $type = 'varchar'; + } elseif (is_array($this->fields[$key]['arrayofkeyval'])) { + $param['options'] = $this->fields[$key]['arrayofkeyval']; + $type = 'select'; + } else { + $param['options'] = array(); + $type = $this->fields[$key]['type']; + } $label = $this->fields[$key]['label']; //$elementtype=$this->fields[$key]['elementtype']; // Seems not used @@ -5932,86 +6074,117 @@ $objectid = $this->id; - if ($computed) { + if ($computed) + { if (!preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; else return ''; } // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine - if (empty($morecss) && !empty($val['css'])) { - $morecss = $val['css']; - } elseif (empty($morecss)) { - if ($type == 'date') { + if (empty($morecss) && !empty($val['css'])) + { + $morecss = $val['css']; + } + elseif (empty($morecss)) + { + if ($type == 'date') + { $morecss = 'minwidth100imp'; - } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id + } + elseif ($type == 'datetime' || $type == 'link') // link means an foreign key to another primary id + { $morecss = 'minwidth200imp'; - } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) { + } + elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) + { $morecss = 'maxwidth75'; } elseif ($type == 'url') { $morecss = 'minwidth400'; - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { $morecss = ''; - } else { - if (round($size) < 12) { + } + else + { + if (round($size) < 12) + { $morecss = 'minwidth100'; - } elseif (round($size) <= 48) { + } + elseif (round($size) <= 48) + { $morecss = 'minwidth200'; - } else { + } + else + { $morecss = 'minwidth400'; } } } - if (in_array($type, array('date'))) { + if (in_array($type, array('date', 'datetime'))) + { $tmp = explode(',', $size); $newsize = $tmp[0]; - $showtime = 0; + + $showtime = in_array($type, array('datetime')) ? 1 : 0; // Do not show current date when field not required (see selectDate() method) if (!$required && $value == '') $value = '-1'; // TODO Must also support $moreparam $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); - } elseif (in_array($type, array('datetime'))) { + } + elseif (in_array($type, array('duration'))) + { + $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1); + } + elseif (in_array($type, array('int', 'integer'))) + { $tmp = explode(',', $size); $newsize = $tmp[0]; - $showtime = 1; - - // Do not show current date when field not required (see selectDate() method) - if (!$required && $value == '') $value = '-1'; - - // TODO Must also support $moreparam - $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel'); - } elseif (in_array($type, array('duration'))) { - $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1); - } elseif (in_array($type, array('int', 'integer'))) { - $tmp = explode(',', $size); - $newsize = $tmp[0]; - $out = ''; - } elseif (in_array($type, array('real'))) { - $out = ''; - } elseif (preg_match('/varchar/', $type)) { - $out = ''; - } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out = ''; - } elseif (preg_match('/^text/', $type)) { + $out = ''; + } + elseif (in_array($type, array('real'))) + { + $out = ''; + } + elseif (preg_match('/varchar/', $type)) + { + $out = ''; + } + elseif (in_array($type, array('mail', 'phone', 'url'))) + { + $out = ''; + } + elseif ($type == 'text') + { if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); $out = $doleditor->Create(1); - } else { + } + else + { $out = ''; } - } elseif (preg_match('/^html/', $type)) { - if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field + } + elseif ($type == 'html') + { + if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field + { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); $out = $doleditor->Create(1); - } else { + } + else + { $out = ''; } - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { $checked = ''; if (!empty($value)) { $checked = ' checked value="1" '; @@ -6019,17 +6192,23 @@ $checked = ' value="1" '; } $out = ''; - } elseif ($type == 'price') { + } + elseif ($type == 'price') + { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value = price($value); } $out = ' '.$langs->getCurrencySymbol($conf->currency); - } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) { + } + elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) + { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value = price($value); } $out = ' '; - } elseif ($type == 'select') { + } + elseif ($type == 'select') + { $out = ''; if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { @@ -6038,7 +6217,7 @@ } $out .= ''; - } elseif ($type == 'sellist') { + } + elseif ($type == 'sellist') + { $out = ''; - if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } $out .= ''; - } elseif ($type == 'checkbox') { + } + elseif ($type == 'checkbox') + { $value_arr = explode(',', $value); $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); - } elseif ($type == 'radio') { + } + elseif ($type == 'radio') + { $out = ''; foreach ($param['options'] as $keyopt => $val) { @@ -6212,10 +6413,13 @@ $out .= ($value == $keyopt ? 'checked' : ''); $out .= '/>
'; } - } elseif ($type == 'chkbxlst') { + } + elseif ($type == 'chkbxlst') + { if (is_array($value)) { $value_arr = $value; - } else { + } + else { $value_arr = explode(',', $value); } @@ -6339,7 +6543,6 @@ if (!empty($InfoFieldList[3]) && $parentField) { $parent = $parentName.':'.$obj->{$parentField}; - $isDependList=1; } $data[$obj->rowid] = $labeltoshow; @@ -6354,23 +6557,14 @@ print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; } } - } elseif ($type == 'link') { + } + elseif ($type == 'link') + { $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]' $param_list_array = explode(':', $param_list[0]); $showempty = (($required && $default != '') ? 0 : 1); - - if (!preg_match('/search_/', $keyprefix)) { - if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button - if (!empty($this->fields[$key]['picto'])) { - $morecss .= ' widthcentpercentminusxx'; - } else { - $morecss .= ' widthcentpercentminusx'; - } - } else { - if (!empty($this->fields[$key]['picto'])) { - $morecss .= ' widthcentpercentminusx'; - } - } + if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button + $morecss .= ' widthcentpercentminusx'; } $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1); @@ -6389,20 +6583,27 @@ $out .= ''; } } - } elseif ($type == 'password') { + } + elseif ($type == 'password') + { // If prefix is 'search_', field is used as a filter, we use a common text field. $out = ''; - } elseif ($type == 'array') { + } + elseif ($type == 'array') + { $newval = $val; $newval['type'] = 'varchar(256)'; $out = ''; + + $inputs = array(); if (!empty($value)) { foreach ($value as $option) { $out .= ' '; $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'
'; } } + $out .= ''; $newInput = ' '; @@ -6425,10 +6626,6 @@ } if (!empty($hidden)) { $out = ''; - } - - if ($isDependList==1) { - $out .= $this->getJSListDependancies('_common'); } /* Add comments if ($type == 'date') $out.=' (YYYY-MM-DD)'; @@ -6471,8 +6668,9 @@ { $type = 'varchar'; // convert varchar(xx) int varchar $size = $reg[1]; - } elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $type = 'select'; + } + elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar + if (is_array($val['arrayofkeyval'])) $type = 'select'; if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link'; $default = $val['default']; @@ -6482,20 +6680,16 @@ $param = array(); $param['options'] = array(); - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; - if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) { + if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) + { $type = 'link'; $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); - } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type = 'sellist'; - } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N'); - $type = 'sellist'; - } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[1].':'.$reg[2] => 'N'); - $type = 'sellist'; - } + } + elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'sellist'; + } $langfile = $val['langfile']; $list = $val['list']; @@ -6514,22 +6708,38 @@ if (empty($morecss)) { - if ($type == 'date') { + if ($type == 'date') + { $morecss = 'minwidth100imp'; - } elseif ($type == 'datetime' || $type == 'timestamp') { + } + elseif ($type == 'datetime' || $type == 'timestamp') + { $morecss = 'minwidth200imp'; - } elseif (in_array($type, array('int', 'double', 'price'))) { + } + elseif (in_array($type, array('int', 'double', 'price'))) + { $morecss = 'maxwidth75'; - } elseif ($type == 'url') { + } + elseif ($type == 'url') + { $morecss = 'minwidth400'; - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { $morecss = ''; - } else { - if (round($size) < 12) { + } + else + { + if (round($size) < 12) + { $morecss = 'minwidth100'; - } elseif (round($size) <= 48) { + } + elseif (round($size) <= 48) + { $morecss = 'minwidth200'; - } else { + } + else + { $morecss = 'minwidth400'; } } @@ -6538,54 +6748,75 @@ // Format output value differently according to properties of field if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1); elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3); - elseif ($type == 'date') { + elseif ($type == 'date') + { if (!empty($value)) { - $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output) + $value = dol_print_date($value, 'day'); } else { $value = ''; } - } elseif ($type == 'datetime' || $type == 'timestamp') { + } + elseif ($type == 'datetime' || $type == 'timestamp') + { if (!empty($value)) { - $value = dol_print_date($value, 'dayhour', 'tzuserrel'); + $value = dol_print_date($value, 'dayhour'); } else { $value = ''; } - } elseif ($type == 'duration') { + } + elseif ($type == 'duration') + { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; if (!is_null($value) && $value !== '') { $value = convertSecondToTime($value, 'allhourmin'); } - } elseif ($type == 'double' || $type == 'real') { + } + elseif ($type == 'double' || $type == 'real') + { if (!is_null($value) && $value !== '') { $value = price($value); } - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { $checked = ''; if (!empty($value)) { $checked = ' checked '; } $value = ''; - } elseif ($type == 'mail') { + } + elseif ($type == 'mail') + { $value = dol_print_email($value, 0, 0, 0, 64, 1, 1); - } elseif ($type == 'url') { + } + elseif ($type == 'url') + { $value = dol_print_url($value, '_blank', 32, 1); - } elseif ($type == 'phone') { + } + elseif ($type == 'phone') + { $value = dol_print_phone($value, '', 0, 0, '', ' ', 1); - } elseif ($type == 'price') + } + elseif ($type == 'price') { if (!is_null($value) && $value !== '') { $value = price($value, 0, $langs, 0, 0, -1, $conf->currency); } - } elseif ($type == 'select') { + } + elseif ($type == 'select') + { $value = $param['options'][$value]; - } elseif ($type == 'sellist') { + } + elseif ($type == 'sellist') + { $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); $selectkey = "rowid"; $keyList = 'rowid'; - if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { + if (count($InfoFieldList) >= 3) + { $selectkey = $InfoFieldList[2]; $keyList = $InfoFieldList[2].' as rowid'; } @@ -6637,7 +6868,9 @@ $value .= $obj->$field_toshow.' '; } } - } else { + } + else + { $translabel = ''; if (!empty($obj->{$InfoFieldList[1]})) { $translabel = $langs->trans($obj->{$InfoFieldList[1]}); @@ -6648,21 +6881,28 @@ $value = $obj->{$InfoFieldList[1]}; } } - } else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); - } elseif ($type == 'radio') { + } + else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); + } + elseif ($type == 'radio') + { $value = $param['options'][$value]; - } elseif ($type == 'checkbox') { + } + elseif ($type == 'checkbox') + { $value_arr = explode(',', $value); $value = ''; if (is_array($value_arr) && count($value_arr) > 0) { $toprint = array(); foreach ($value_arr as $keyval=>$valueval) { - $toprint[] = '
  • '.$param['options'][$valueval].'
  • '; + $toprint[] = '
  • '.$param['options'][$valueval].'
  • '; } $value = '
      '.implode(' ', $toprint).'
    '; } - } elseif ($type == 'chkbxlst') { + } + elseif ($type == 'chkbxlst') + { $value_arr = explode(',', $value); $param_list = array_keys($param['options']); @@ -6706,9 +6946,9 @@ $translabel = $langs->trans($obj->$field_toshow); } if ($translabel != $field_toshow) { - $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; + $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; } else { - $toprint[] = '
  • '.$obj->$field_toshow.'
  • '; + $toprint[] = '
  • '.$obj->$field_toshow.'
  • '; } } } else { @@ -6717,9 +6957,9 @@ $translabel = $langs->trans($obj->{$InfoFieldList[1]}); } if ($translabel != $obj->{$InfoFieldList[1]}) { - $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; + $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; } else { - $toprint[] = '
  • '.$obj->{$InfoFieldList[1]}.'
  • '; + $toprint[] = '
  • '.$obj->{$InfoFieldList[1]}.'
  • '; } } } @@ -6728,7 +6968,9 @@ } else { dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); } - } elseif ($type == 'link') { + } + elseif ($type == 'link') + { $out = ''; // only if something to display (perf) @@ -6749,20 +6991,29 @@ $object->fetch($value); $value = $object->getNomUrl($getnomurlparam); } - } else { + } + else + { dol_syslog('Error bad setup of extrafield', LOG_WARNING); return 'Error bad setup of extrafield'; } - } else $value = ''; - } elseif (preg_match('/^(text|html)/', $type)) { + } + else $value = ''; + } + elseif ($type == 'text' || $type == 'html') + { $value = dol_htmlentitiesbr($value); - } elseif ($type == 'password') { + } + elseif ($type == 'password') + { $value = preg_replace('/./i', '*', $value); - } elseif ($type == 'array') { + } + elseif ($type == 'array') + { $value = implode('
    ', $value); } - //print $type.'-'.$size.'-'.$value; + //print $type.'-'.$size; $out = $value; return $out; @@ -6778,288 +7029,248 @@ * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan) * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names) * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names) - * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example. + * @param string $onetrtd All fields in same tr td (TODO field not used ?) * @return string */ public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0) { - global $db, $conf, $langs, $action, $form, $hookmanager; + global $db, $conf, $langs, $action, $form; if (!is_object($form)) $form = new Form($db); $out = ''; - $parameters = array(); - $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) - { - $out .= "\n"; - $out .= ' '; - $out .= "\n"; - - $extrafields_collapse_num = ''; - $e = 0; - foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label) + if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) + { + $out .= "\n"; + $out .= ' '; + $out .= "\n"; + + $extrafields_collapse_num = ''; + $e = 0; + foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label) + { + // Show only the key field in params + if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue; + + // @todo Add test also on 'enabled' (different than 'list' that is 'visibility') + $enabled = 1; + if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) { - // Show only the key field in params - if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue; - - // Test on 'enabled' ('enabled' is different than 'list' = 'visibility') - $enabled = 1; - if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) + $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1); + } + if (empty($enabled)) continue; + + $visibility = 1; + if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) + { + $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1); + } + + $perms = 1; + if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) + { + $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1); + } + + if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list + elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation + elseif ($mode == 'view' && empty($visibility)) continue; + if (empty($perms)) continue; + // Load language if required + if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) { + $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); + } + + $colspan = ''; + if (is_array($params) && count($params) > 0) { + if (array_key_exists('cols', $params)) { + $colspan = $params['cols']; + } + elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now. + $reg = array(); + if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) { + $colspan = $reg[1]; + } + else { + $colspan = $params['colspan']; + } + } + } + + switch ($mode) { + case "view": + $value = $this->array_options["options_".$key.$keysuffix]; + break; + case "create": + case "edit": + $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values. + // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc') + if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) + { + if (is_array($getposttemp)) { + // $getposttemp is an array but following code expects a comma separated string + $value = implode(",", $getposttemp); + } else { + $value = $getposttemp; + } + } else { + $value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object. + } + //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value); + break; + } + + if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') + { + $extrafields_collapse_num = ''; + $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key]; + if (!empty($extrafield_param) && is_array($extrafield_param)) { + $extrafield_param_list = array_keys($extrafield_param['options']); + + if (count($extrafield_param_list) > 0) { + $extrafield_collapse_display_value = intval($extrafield_param_list[0]); + + if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) { + $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key]; + } + } + } + + $out .= $extrafields->showSeparator($key, $this, ($colspan + 1)); + } + else + { + $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : ''); + $csstyle = ''; + if (is_array($params) && count($params) > 0) { + if (array_key_exists('class', $params)) { + $class .= $params['class'].' '; + } + if (array_key_exists('style', $params)) { + $csstyle = $params['style']; + } + } + + // add html5 elements + $domData = ' data-element="extrafield"'; + $domData .= ' data-targetelement="'.$this->element.'"'; + $domData .= ' data-targetid="'.$this->id.'"'; + + $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id); + + if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; } + + if ($action == 'selectlines') { $colspan++; } + + // Convert date into timestamp format (value in memory must be a timestamp) + if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) { - $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1); - } - if (empty($enabled)) continue; - - $visibility = 1; - if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) + $datenotinstring = $this->array_options['options_'.$key]; + if (!is_numeric($this->array_options['options_'.$key])) // For backward compatibility + { + $datenotinstring = $this->db->jdate($datenotinstring); + } + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) ?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring; + } + // Convert float submited string into real php numeric (value in memory must be a php numeric) + if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) { - $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1); - } - - $perms = 1; - if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) ?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)) : $this->array_options['options_'.$key]; + } + // HTML, select, integer and text add default value + if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'select', 'int'))) { - $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1); - } - - if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list - elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation - elseif ($mode == 'view' && empty($visibility)) continue; - if (empty($perms)) continue; - // Load language if required - if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) { - $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); - } - - $colspan = ''; - if (is_array($params) && count($params) > 0) { - if (array_key_exists('cols', $params)) { - $colspan = $params['cols']; - } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now. - $reg = array(); - if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) { - $colspan = $reg[1]; - } else { - $colspan = $params['colspan']; - } - } - } + if ($action == 'create') $value = $extrafields->attributes[$this->table_element]['default'][$key]; + else $value = $this->array_options['options_'.$key]; + } + + $labeltoshow = $langs->trans($label); + $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]); + + $out .= ''; + $out .= 'attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow); + else $out .= $labeltoshow; + if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' *'; + } else { + if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired'; + $out .= '">'; + if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow); + else $out .= $labeltoshow; + } + $out .= ''; + + $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : ''; + + $out .= ''; switch ($mode) { case "view": - $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later + $out .= $extrafields->showOutputField($key, $value); break; - case "create": - case "edit": - // We get the value of property found with GETPOST so it takes into account: - // default values overwrite, restore back to list link, ... (but not 'default value in database' of field) - $check = 'alphanohtml'; - if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) { - $check = 'restricthtml'; + case "create": + case "edit": + $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element); + break; + } + + $out .= ''; + + /*for($ii = 0; $ii < ($colspan - 1); $ii++) + { + $out .=''; + }*/ + + if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= ''; + else $out .= ''; + $e++; + } + } + $out .= "\n"; + // Add code to manage list depending on others + if (!empty($conf->use_javascript_ajax)) { + $out .= ' + '."\n"; + setListDependencies(); + }); + '."\n"; + $out .= ' '."\n"; + } + } return $out; } + /** * Returns the rights used for this class @@ -7125,7 +7336,9 @@ if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false { $buyPrice = $unitPrice * (1 - $discountPercent / 100); - } else { + } + else + { // Get cost price for margin calculation if (!empty($fk_product)) { @@ -7142,11 +7355,13 @@ if ($product->cost_price > 0) { $buyPrice = $product->cost_price; - } elseif ($product->pmp > 0) + } + elseif ($product->pmp > 0) { $buyPrice = $product->pmp; } - } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') + } + elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $product = new Product($this->db); @@ -7169,7 +7384,8 @@ if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) { $buyPrice = $productFournisseur->fourn_unitprice; - } elseif ($result < 0) + } + elseif ($result < 0) { $this->errors[] = $productFournisseur->error; return -2; @@ -7180,7 +7396,7 @@ return $buyPrice; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show photos of an object (nbmax maximum), into several columns * @@ -7200,7 +7416,7 @@ */ public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user, $langs; include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -7212,20 +7428,20 @@ $dir = $sdir.'/'; $pdir = '/'; - $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart); - $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart); + $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/'; + $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/'; // For backward compatibility - if ($modulepart == 'product') { - if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; - $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; - } + if ($modulepart == 'product' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + { + $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; + $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; } // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; - if ($dir) { + if ($dir) + { $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir); $relativedir = preg_replace('/^[\\/]/', '', $relativedir); $relativedir = preg_replace('/[\\/]$/', '', $relativedir); @@ -7247,19 +7463,23 @@ completeFileArrayWithDatabaseInfo($filearray, $relativedir); - if (count($filearray)) { - if ($sortfield && $sortorder) { + if (count($filearray)) + { + if ($sortfield && $sortorder) + { $filearray = dol_sort_array($filearray, $sortfield, $sortorder); } - foreach ($filearray as $key => $val) { + foreach ($filearray as $key => $val) + { $photo = ''; $file = $val['name']; //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) - if (image_format_supported($file) >= 0) { + if (image_format_supported($file) >= 0) + { $nbphoto++; $photo = $file; $viewfilename = $file; @@ -7278,7 +7498,8 @@ if ($nbphoto % $nbbyrow == 1) $return .= ''; $return .= ''; - } elseif ($nbbyrow < 0) $return .= '
    '; + } + elseif ($nbbyrow < 0) $return .= '
    '; $return .= "\n"; @@ -7296,24 +7517,34 @@ $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height']; if ($notitle) $alt = ''; - if ($usesharelink) { - if ($val['share']) { - if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) { + if ($usesharelink) + { + if ($val['share']) + { + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) + { $return .= ''; $return .= ''; - } else { + } + else { $return .= ''; $return .= ''; } - } else { + } + else + { $return .= ''; $return .= ''; } - } else { - if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) { + } + else + { + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) + { $return .= ''; - $return .= ''; - } else { + $return .= ''; + } + else { $return .= ''; $return .= ''; } @@ -7338,7 +7569,7 @@ $return .= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; // Link to delete - $return .= ''; + $return .= ''; $return .= img_delete().''; } } @@ -7348,7 +7579,8 @@ { $return .= ''; if (($nbphoto % $nbbyrow) == 0) $return .= ''; - } elseif ($nbbyrow < 0) $return .= '
    '; + } + elseif ($nbbyrow < 0) $return .= '
    '; } if (empty($size)) { // Format origine @@ -7364,7 +7596,7 @@ $return .= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; // Link to delete - $return .= ''; + $return .= ''; $return .= img_delete().''; } } @@ -7405,7 +7637,8 @@ */ protected function isArray($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['type']) && $info['type'] == 'array') return true; else return false; } @@ -7432,10 +7665,12 @@ */ public function isDuration($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['type']) && ($info['type'] == 'duration')) return true; else return false; - } else return false; + } + else return false; } /** @@ -7446,10 +7681,12 @@ */ public function isInt($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true; else return false; - } else return false; + } + else return false; } /** @@ -7460,7 +7697,8 @@ */ public function isFloat($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) return true; else return false; } @@ -7475,7 +7713,8 @@ */ public function isText($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['type']) && $info['type'] == 'text') return true; else return false; } @@ -7490,7 +7729,8 @@ */ protected function canBeNull($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['notnull']) && $info['notnull'] != '1') return true; else return false; } @@ -7505,7 +7745,8 @@ */ protected function isForcedToNullIfZero($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['notnull']) && $info['notnull'] == '-1') return true; else return false; } @@ -7520,7 +7761,8 @@ */ protected function isIndex($info) { - if (is_array($info)) { + if (is_array($info)) + { if (isset($info['index']) && $info['index'] == true) return true; else return false; } @@ -7545,12 +7787,16 @@ // Depending on field type ('datetime', ...) if ($this->isDate($info)) { - if (empty($this->{$field})) { + if (empty($this->{$field})) + { $queryarray[$field] = null; - } else { + } + else + { $queryarray[$field] = $this->db->idate($this->{$field}); } - } elseif ($this->isArray($info)) + } + elseif ($this->isArray($info)) { if (!empty($this->{$field})) { if (!is_array($this->{$field})) { @@ -7560,33 +7806,28 @@ } else { $queryarray[$field] = null; } - } elseif ($this->isDuration($info)) + } + elseif ($this->isDuration($info)) { // $this->{$field} may be null, '', 0, '0', 123, '123' - if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) { - if (!isset($this->{$field})) { - $queryarray[$field] = 0; - } else { - $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 - } - } + if ($this->{$field} != '' || !empty($info['notnull'])) $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 else $queryarray[$field] = null; - } elseif ($this->isInt($info) || $this->isFloat($info)) + } + elseif ($this->isInt($info) || $this->isFloat($info)) { if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity; - else { + else + { // $this->{$field} may be null, '', 0, '0', 123, '123' - if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) { - if (!isset($this->{$field})) { - $queryarray[$field] = 0; - } elseif ($this->isInt($info)) { - $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 - } elseif ($this->isFloat($info)) { - $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 - } - } else $queryarray[$field] = null; - } - } else { + if ($this->{$field} != '' || !empty($info['notnull'])) { + if ($this->isInt($info)) $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + if ($this->isFloat($info)) $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + } + else $queryarray[$field] = null; + } + } + else + { $queryarray[$field] = $this->{$field}; } @@ -7601,18 +7842,18 @@ * Function to load data from a SQL pointer into properties of current object $this * * @param stdClass $obj Contain data of object from database - * @return void + * @return void */ public function setVarsFromFetchObj(&$obj) { - global $db; - foreach ($this->fields as $field => $info) { - if ($this->isDate($info)) { - if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = ''; - else $this->{$field} = $db->jdate($obj->{$field}); - } elseif ($this->isArray($info)) + if ($this->isDate($info)) + { + if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; + else $this->{$field} = strtotime($obj->{$field}); + } + elseif ($this->isArray($info)) { if (!empty($obj->{$field})) { $this->{$field} = @unserialize($obj->{$field}); @@ -7621,13 +7862,19 @@ } else { $this->{$field} = array(); } - } elseif ($this->isInt($info)) { + } + elseif ($this->isInt($info)) + { if ($field == 'rowid') $this->id = (int) $obj->{$field}; - else { - if ($this->isForcedToNullIfZero($info)) { + else + { + if ($this->isForcedToNullIfZero($info)) + { if (empty($obj->{$field})) $this->{$field} = null; else $this->{$field} = (double) $obj->{$field}; - } else { + } + else + { if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) { $this->{$field} = (int) $obj->{$field}; } else { @@ -7635,18 +7882,25 @@ } } } - } elseif ($this->isFloat($info)) { - if ($this->isForcedToNullIfZero($info)) { + } + elseif ($this->isFloat($info)) + { + if ($this->isForcedToNullIfZero($info)) + { if (empty($obj->{$field})) $this->{$field} = null; else $this->{$field} = (double) $obj->{$field}; - } else { + } + else + { if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) { $this->{$field} = (double) $obj->{$field}; } else { $this->{$field} = null; } } - } else { + } + else + { $this->{$field} = $obj->{$field}; } } @@ -7678,9 +7932,9 @@ if (is_null($value)) return 'NULL'; elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) return $this->db->escape("$value"); elseif ($fieldsentry['type'] == 'boolean') { - if ($value) return 'true'; - else return 'false'; - } + if ($value) return 'true'; + else return 'false'; + } else return "'".$this->db->escape($value)."'"; } @@ -7709,11 +7963,11 @@ if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data $keys = array(); - $values = array(); // Array to store string forged for SQL syntax + $values = array(); foreach ($fieldvalues as $k => $v) { $keys[$k] = $k; $value = $this->fields[$k]; - $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null + $values[$k] = $this->quote($v, $value); } // Clean and check mandatory @@ -7723,16 +7977,11 @@ if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; - if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) + //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); + if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && !isset($values[$key]) && is_null($this->fields[$key]['default'])) { $error++; $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); - } - - // If value is null and there is a default value for field - if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) - { - $values[$key] = $this->fields[$key]['default']; } // If field is an implicit foreign key field @@ -7768,19 +8017,19 @@ // If we have a field ref with a default value of (PROV) if (!$error) { - if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)') - { - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".$this->id; - $resqlupdate = $this->db->query($sql); - - if ($resqlupdate === false) - { - $error++; - $this->errors[] = $this->db->lasterror(); - } else { - $this->ref = '(PROV'.$this->id.')'; - } - } + if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)') + { + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".$this->id; + $resqlupdate = $this->db->query($sql); + + if ($resqlupdate === false) + { + $error++; + $this->errors[] = $this->db->lasterror(); + } else { + $this->ref = '(PROV'.$this->id.')'; + } + } } // Create extrafields @@ -7847,17 +8096,14 @@ { if (empty($id) && empty($ref) && empty($morewhere)) return -1; - $fieldlist = $this->getFieldList(); - if (empty($fieldlist)) return 0; - - $sql = 'SELECT '.$fieldlist; + $sql = 'SELECT '.$this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - if (!empty($id)) $sql .= ' WHERE rowid = '.$id; + if (!empty($id)) $sql .= ' WHERE rowid = '.$id; elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']); else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' AND entity IN ('.getEntity($this->table_element).')'; - if ($morewhere) $sql .= $morewhere; + if ($morewhere) $sql .= $morewhere; $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record $res = $this->db->query($sql); @@ -7868,15 +8114,19 @@ { $this->setVarsFromFetchObj($obj); - // Retrieve all extrafield + // Retreive all extrafield // fetch optionals attributes and labels $this->fetch_optionals(); return $this->id; - } else { + } + else + { return 0; } - } else { + } + else + { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; return -1; @@ -7904,9 +8154,6 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element; $sql .= ' WHERE fk_'.$this->element.' = '.$this->id; if ($morewhere) $sql .= $morewhere; - if (isset($objectline->fields['position'])) { - $sql .= $this->db->order('position', 'ASC'); - } $resql = $this->db->query($sql); if ($resql) @@ -7927,7 +8174,9 @@ } return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; return -1; @@ -7957,7 +8206,6 @@ unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data - // Add quotes and escape on fields with type string $keys = array(); $values = array(); $tmp = array(); @@ -7968,7 +8216,7 @@ $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]); } - // Clean and check mandatory fields + // Clean and check mandatory foreach ($keys as $key) { if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field @@ -7983,7 +8231,7 @@ }*/ } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(',', $tmp).' WHERE rowid='.$this->id; $this->db->begin(); if (!$error) @@ -8055,7 +8303,8 @@ return -1; } } - } elseif (!empty($this->fk_element) && !empty($this->childtables)) // If object has childs linked with a foreign key field, we check all child tables. + } + elseif (!empty($this->fk_element) && !empty($this->childtables)) // If object has childs linked with a foreign key field, we check all child tables. { $objectisused = $this->isObjectUsed($this->id); if (!empty($objectisused)) @@ -8070,46 +8319,46 @@ // Delete cascade first if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) { - foreach ($this->childtablesoncascade as $table) - { - $deleteFromObject = explode(':', $table); - if (count($deleteFromObject) >= 2) { - $className = str_replace('@', '', $deleteFromObject[0]); - $filePath = $deleteFromObject[1]; - $columnName = $deleteFromObject[2]; - if (dol_include_once($filePath)) { - $childObject = new $className($this->db); - if (method_exists($childObject, 'deleteByParentField')) { - $result = $childObject->deleteByParentField($this->id, $columnName); - if ($result < 0) { + foreach ($this->childtablesoncascade as $table) + { + $deleteFromObject = explode(':', $table); + if (count($deleteFromObject)>=2) { + $className = str_replace('@', '', $deleteFromObject[0]); + $filePath = $deleteFromObject[1]; + $columnName = $deleteFromObject[2]; + if (dol_include_once($filePath)) { + $childObject = new $className($this->db); + if (method_exists($childObject, 'deleteByParentField')) { + $result = $childObject->deleteByParentField($this->id, $columnName); + if ($result < 0) { $error++; - $this->errors[] = $childObject->error; - break; - } - } else { + $this->errors[] = $childObject->error; + break; + } + } else { $error++; $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it"; break; } - } else { + } else { + $error++; + $this->errors[] = 'Cannot include child class file ' .$filePath; + break; + } + } else { + // Delete record in child table + $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $table . ' WHERE ' . $this->fk_element . ' = ' . $this->id; + + $resql = $this->db->query($sql); + if (!$resql) { $error++; - $this->errors[] = 'Cannot include child class file '.$filePath; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; break; - } - } else { - // Delete record in child table - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id; - - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - break; - } - } - } - } + } + } + } + } if (!$error) { if (!$notrigger) { @@ -8117,14 +8366,6 @@ $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail // End call triggers - } - } - - // Delete llx_ecm_files - if (!$error) { - $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive - if (!$res) { - $error++; } } @@ -8173,8 +8414,8 @@ if (!empty($parentId) && !empty($parentField)) { $this->db->begin(); - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= ' WHERE '.$parentField.' = '.(int) $parentId; + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= ' WHERE '.$parentField.' = ' . (int) $parentId; $resql = $this->db->query($sql); if (!$resql) { @@ -8252,8 +8493,9 @@ if (empty($error)) { // Remove extrafields - $tmpobjectline = new $tmpforobjectlineclass($this->db); - if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) { + if (!$error) + { + $tmpobjectline = new $tmpforobjectlineclass($this->db); $tmpobjectline->id = $idline; $result = $tmpobjectline->deleteExtraFields(); if ($result < 0) @@ -8290,11 +8532,8 @@ $this->db->begin(); - $statusfield = 'status'; - if ($this->element == 'don' || $this->element == 'donation') $statusfield = 'fk_statut'; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ".$statusfield." = ".((int) $status); + $sql .= " SET status = ".$status; $sql .= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) @@ -8318,7 +8557,9 @@ $this->db->rollback(); return -1; } - } else { + } + else + { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -8330,31 +8571,22 @@ * Initialise object with example values * Id must be 0 if object instance is a specimen * - * @return int + * @return void */ public function initAsSpecimenCommon() { - global $user; + global $user; $this->id = 0; - $this->specimen = 1; - $fields = array( - 'label' => 'This is label', - 'ref' => 'ABCD1234', - 'description' => 'This is a description', - 'qty' => 123.12, - 'note_public' => 'Public note', - 'note_private' => 'Private note', - 'date_creation' => (dol_now() - 3600 * 48), - 'date_modification' => (dol_now() - 3600 * 24), - 'fk_user_creat' => $user->id, - 'fk_user_modif' => $user->id, - 'date' => dol_now(), - ); - foreach ($fields as $key => $value) { - if (array_key_exists($key, $this->fields)) $this->{$key} = $value; - } - return 1; + if (array_key_exists('label', $this->fields)) $this->label = 'This is label'; + if (array_key_exists('note_public', $this->fields)) $this->note_public = 'Public note'; + if (array_key_exists('note_private', $this->fields)) $this->note_private = 'Private note'; + if (array_key_exists('date_creation', $this->fields)) $this->date_creation = (dol_now() - 3600 * 24); + if (array_key_exists('date_modification', $this->fields)) $this->date_modification = (dol_now() - 3600 * 24); + if (array_key_exists('fk_user_creat', $this->fields)) $this->fk_user_creat = $user->id; + if (array_key_exists('fk_user_modif', $this->fields)) $this->fk_user_modif = $user->id; + if (array_key_exists('date', $this->fields)) $this->date = dol_now(); + // ... } @@ -8379,121 +8611,40 @@ return count($this->comments); } - /** - * Return nb comments already posted - * - * @return int - */ - public function getNbComments() - { - return count($this->comments); - } - - /** - * Trim object parameters - * - * @param string[] $parameters array of parameters to trim - * @return void - */ - public function trimParameters($parameters) - { - if (!is_array($parameters)) return; - foreach ($parameters as $parameter) { - if (isset($this->$parameter)) { - $this->$parameter = trim($this->$parameter); - } - } - } - - /* Part for categories/tags */ - - /** - * Sets object to given categories. - * - * Deletes object from existing categories not supplied. - * Adds it to non existing supplied categories. - * Existing categories are left untouch. - * - * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) - * @return int Array of category objects or < 0 if KO - */ - public function getCategoriesCommon($type_categ) - { - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - - // Get current categories - $c = new Categorie($this->db); - $existing = $c->containing($this->id, $type_categ, 'id'); - - return $existing; - } - - /** - * Sets object to given categories. - * - * Deletes object from existing categories not supplied. - * Adds it to non existing supplied categories. - * Existing categories are left untouch. - * - * @param int[]|int $categories Category ID or array of Categories IDs - * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) - * @return int <0 if KO, >0 if OK - */ - public function setCategoriesCommon($categories, $type_categ) - { - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - - // Handle single category - if (!is_array($categories)) { - $categories = array($categories); - } - - // Get current categories - $c = new Categorie($this->db); - $existing = $c->containing($this->id, $type_categ, 'id'); - - // Diff - if (is_array($existing)) { - $to_del = array_diff($existing, $categories); - $to_add = array_diff($categories, $existing); - } else { - $to_del = array(); // Nothing to delete - $to_add = $categories; - } - - $error = 0; - - // Process - foreach ($to_del as $del) { - if ($c->fetch($del) > 0) { - $c->del_type($this, $type_categ); - } - } - foreach ($to_add as $add) { - if ($c->fetch($add) > 0) - { - $result = $c->add_type($this, $type_categ); - if ($result < 0) - { - $error++; - $this->error = $c->error; - $this->errors = $c->errors; - break; - } - } - } - - return $error ? -1 : 1; - } - - /** - * Copy related categories to another object - * - * @param int $fromId Id object source - * @param int $toId Id object cible - * @param string $type Type of category ('product', ...) - * @return int < 0 if error, > 0 if ok - */ + /** + * Return nb comments already posted + * + * @return int + */ + public function getNbComments() + { + return count($this->comments); + } + + /** + * Trim object parameters + * @param string[] $parameters array of parameters to trim + * + * @return void + */ + public function trimParameters($parameters) + { + if (!is_array($parameters)) return; + foreach ($parameters as $parameter) { + if (isset($this->$parameter)) { + $this->$parameter = trim($this->$parameter); + } + } + } + + /** + * copy related categories to another object + * + * @param int $fromId Id object source + * @param int $toId Id object cible + * @param string $type Type of category ('product', ...) + * @return int < 0 si erreur, > 0 si ok + */ public function cloneCategories($fromId, $toId, $type = '') { $this->db->begin(); @@ -8505,7 +8656,7 @@ $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)"; $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]); - $sql .= " WHERE fk_product = ".((int) $fromId); + $sql .= " WHERE fk_product = '".$fromId."'"; if (!$this->db->query($sql)) { @@ -8517,87 +8668,4 @@ $this->db->commit(); return 1; } - - /** - * Delete related files of object in database - * - * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects) - * @return bool True if OK, False if KO - */ - public function deleteEcmFiles($mode = 0) - { - global $conf; - - $this->db->begin(); - - // Delete in database with mode 0 - if ($mode == 0) { - switch ($this->element) { - case 'propal': - $element = 'propale'; - break; - case 'product': - $element = 'produit'; - break; - case 'order_supplier': - $element = 'fournisseur/commande'; - break; - case 'invoice_supplier': - $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier'); - break; - case 'shipping': - $element = 'expedition/sending'; - break; - default: - $element = $this->element; - } - - // Delete ecm_files extrafields - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN ("; - $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'"; - $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here - $sql .= ")"; - - if (!$this->db->query($sql)) { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return false; - } - - // Delete ecm_files - $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files"; - $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'"; - $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here - - if (!$this->db->query($sql)) { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return false; - } - } - - // Delete in database with mode 1 - if ($mode == 1) { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields"; - $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")"; - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return false; - } - - $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files"; - $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id; - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return false; - } - } - - $this->db->commit(); - return true; - } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_commonobjectline.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commonobjectline.class.php @@ -19,7 +19,7 @@ /** * \file htdocs/core/class/commonobjectline.class.php * \ingroup core - * \brief File of the superclass of classes of lines of business objects (invoice, contract, proposal, orders, etc. ...) + * \brief File of the superclass of classes of lines of business objects (invoice, contract, PROPAL, commands, etc. ...) */ @@ -51,21 +51,11 @@ /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - /** - * Returns the label, shot_label or code found in units dictionary from ->fk_unit. + * Returns the translation key from units dictionary. * A langs->trans() must be called on result to get translated value. * - * @param string $type Label type ('long', 'short' or 'code'). This can be a translation key. - * @return string|int <0 if KO, label if OK (Example: 'long', 'short' or 'unitCODE') + * @param string $type Label type (long or short). This can be a translation key. + * @return string|int <0 if ko, label if ok */ public function getLabelOfUnit($type = 'long') { @@ -79,19 +69,22 @@ $label_type = 'label'; - $label_type = 'label'; - if ($type == 'short') $label_type = 'short_label'; - elseif ($type == 'code') $label_type = 'code'; + if ($type == 'short') + { + $label_type = 'short_label'; + } - $sql = 'select '.$label_type.', code from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit; + $sql = 'select '.$label_type.' from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit; $resql = $this->db->query($sql); - if ($resql && $this->db->num_rows($resql) > 0) { + if ($resql && $this->db->num_rows($resql) > 0) + { $res = $this->db->fetch_array($resql); - if ($label_type == 'code') $label = 'unit'.$res['code']; - else $label = $res[$label_type]; + $label = $res[$label_type]; $this->db->free($resql); return $label; - } else { + } + else + { $this->error = $this->db->error().' sql='.$sql; dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR); return -1; --- /tmp/dsg/dolibarr/htdocs/core/class/github_commonorder.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commonorder.class.php @@ -23,14 +23,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; /** * Superclass for orders classes */ abstract class CommonOrder extends CommonObject { - use CommonIncoterm; + } /** @@ -38,12 +37,6 @@ */ abstract class CommonOrderLine extends CommonObjectLine { - /** - * Custom label of line. Not used by default. - * @deprecated - */ - public $label; - /** * Product ref * @var string @@ -53,18 +46,18 @@ public $ref; /** + * Product ref + * @var string + */ + public $product_ref; + + /** * Product label * @var string * @deprecated Use product_label * @see $product_label */ public $libelle; - - /** - * Product ref - * @var string - */ - public $product_ref; /** * Product label @@ -79,18 +72,6 @@ public $product_desc; /** - * Product use lot - * @var string - */ - public $product_tobatch; - - /** - * Product barcode - * @var string - */ - public $product_barcode; - - /** * Quantity * @var float */ @@ -101,7 +82,7 @@ * @deprecated * @see $subprice */ - public $price; + public $price; /** * Unit price before taxes @@ -134,12 +115,6 @@ public $remise_percent; /** - * VAT code - * @var string - */ - public $vat_src_code; - - /** * VAT % * @var float */ @@ -169,11 +144,4 @@ public $info_bits = 0; public $special_code = 0; - - public $fk_multicurrency; - public $multicurrency_code; - public $multicurrency_subprice; - public $multicurrency_total_ht; - public $multicurrency_total_tva; - public $multicurrency_total_ttc; } --- /tmp/dsg/dolibarr/htdocs/core/class/github_commonstickergenerator.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commonstickergenerator.class.php @@ -61,46 +61,46 @@ */ abstract class CommonStickerGenerator { - public $code; // Code of format - - /** - * @var array format Array with informations - */ - public $format; - - // phpcs:disable PEAR.NamingConventions.ValidVariableName.PublicUnderscore - // protected - // Nom du format de l'etiquette - protected $_Avery_Name = ''; - // Marge de gauche de l'etiquette - protected $_Margin_Left = 0; - // marge en haut de la page avant la premiere etiquette - protected $_Margin_Top = 0; - // Espace horizontal entre 2 bandes d'etiquettes - protected $_X_Space = 0; - // Espace vertical entre 2 bandes d'etiquettes - protected $_Y_Space = 0; - // NX Nombre d'etiquettes sur la largeur de la page - protected $_X_Number = 0; - // NY Nombre d'etiquettes sur la hauteur de la page - protected $_Y_Number = 0; - // Largeur de chaque etiquette - protected $_Width = 0; - // Hauteur de chaque etiquette - protected $_Height = 0; - // Hauteur des caracteres - protected $_Char_Size = 10; - // Hauteur par defaut d'une ligne - protected $_Line_Height = 10; - // Type of metric.. Will help to calculate good values - protected $_Metric = 'mm'; - // Type of metric for the doc.. - protected $_Metric_Doc = 'mm'; - protected $_COUNTX = 1; - protected $_COUNTY = 1; - protected $_First = 1; - public $Tformat; - // phpcs:enable + public $code; // Code of format + + /** + * @var array format Array with informations + */ + public $format; + + // phpcs:disable PEAR.NamingConventions.ValidVariableName.PublicUnderscore + // protected + // Nom du format de l'etiquette + protected $_Avery_Name = ''; + // Marge de gauche de l'etiquette + protected $_Margin_Left = 0; + // marge en haut de la page avant la premiere etiquette + protected $_Margin_Top = 0; + // Espace horizontal entre 2 bandes d'etiquettes + protected $_X_Space = 0; + // Espace vertical entre 2 bandes d'etiquettes + protected $_Y_Space = 0; + // NX Nombre d'etiquettes sur la largeur de la page + protected $_X_Number = 0; + // NY Nombre d'etiquettes sur la hauteur de la page + protected $_Y_Number = 0; + // Largeur de chaque etiquette + protected $_Width = 0; + // Hauteur de chaque etiquette + protected $_Height = 0; + // Hauteur des caracteres + protected $_Char_Size = 10; + // Hauteur par defaut d'une ligne + protected $_Line_Height = 10; + // Type of metric.. Will help to calculate good values + protected $_Metric = 'mm'; + // Type of metric for the doc.. + protected $_Metric_Doc = 'mm'; + protected $_COUNTX = 1; + protected $_COUNTY = 1; + protected $_First = 1; + public $Tformat; + // phpcs:enable /** * Constructor * @@ -111,7 +111,7 @@ $this->db = $db; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Function to build PDF on disk, then output on HTTP strem. * @@ -122,30 +122,30 @@ * @return int 1=OK, 0=KO */ public abstract function write_file($arrayofrecords, $outputlangs, $srctemplatepath, $outputdir = ''); - // phpcs:enable + // phpcs:enable /** * Output a sticker on page at position _COUNTX, _COUNTY (_COUNTX and _COUNTY start from 0) * - * @param TCPDF $pdf PDF reference + * @param PDF $pdf PDF reference * @param Translate $outputlangs Output langs * @param array $param Associative array containing label content and optional parameters * @return void */ public abstract function addSticker(&$pdf, $outputlangs, $param); - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Methode qui permet de modifier la taille des caracteres * Cela modiera aussi l'espace entre chaque ligne * - * @param TCPDF $pdf PDF reference + * @param PDF $pdf PDF reference * @param int $pt point * @return void */ public function Set_Char_Size(&$pdf, $pt) { - // phpcs:enable + // phpcs:enable if ($pt > 3) { $this->_Char_Size = $pt; $this->_Line_Height = $this->_Get_Height_Chars($pt); @@ -153,12 +153,12 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * protected Print dot line * - * @param TCPDF $pdf PDF reference + * @param PDF $pdf PDF reference * @param int $x1 X1 * @param int $y1 Y1 * @param int $x2 X2 @@ -167,41 +167,42 @@ * @param int $nbPointilles Nb pointilles * @return void */ - protected function _Pointille(&$pdf, $x1 = 0, $y1 = 0, $x2 = 210, $y2 = 297, $epaisseur = 1, $nbPointilles = 15) - { - // phpcs:enable + protected function _Pointille(&$pdf, $x1 = 0, $y1 = 0, $x2 = 210, $y2 = 297, $epaisseur = 1, $nbPointilles = 15) + { + // phpcs:enable $pdf->SetLineWidth($epaisseur); $length = abs($x1 - $x2); $hauteur = abs($y1 - $y2); if ($length > $hauteur) { $Pointilles = ($length / $nbPointilles) / 2; // taille des pointilles - } else { + } + else { $Pointilles = ($hauteur / $nbPointilles) / 2; } for ($i = $x1; $i <= $x2; $i += $Pointilles + $Pointilles) { for ($j = $i; $j <= ($i + $Pointilles); $j++) { if ($j <= ($x2 - 1)) { - $pdf->Line($j, $y1, $j + 1, $y1); // on trace le pointill? du haut, point par point - $pdf->Line($j, $y2, $j + 1, $y2); // on trace le pointill? du bas, point par point + $pdf->Line($j, $y1, $j + 1, $y1); // on trace le pointill? du haut, point par point + $pdf->Line($j, $y2, $j + 1, $y2); // on trace le pointill? du bas, point par point } } } for ($i = $y1; $i <= $y2; $i += $Pointilles + $Pointilles) { for ($j = $i; $j <= ($i + $Pointilles); $j++) { if ($j <= ($y2 - 1)) { - $pdf->Line($x1, $j, $x1, $j + 1); // on trace le pointill? du haut, point par point - $pdf->Line($x2, $j, $x2, $j + 1); // on trace le pointill? du bas, point par point + $pdf->Line($x1, $j, $x1, $j + 1); // on trace le pointill? du haut, point par point + $pdf->Line($x2, $j, $x2, $j + 1); // on trace le pointill? du bas, point par point } } } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** * protected Function realisant une croix aux 4 coins des cartes * - * @param TCPDF $pdf PDF reference + * @param PDF $pdf PDF reference * @param int $x1 X1 * @param int $y1 Y1 * @param int $x2 X2 @@ -212,7 +213,7 @@ */ protected function _Croix(&$pdf, $x1 = 0, $y1 = 0, $x2 = 210, $y2 = 297, $epaisseur = 1, $taille = 4) { - // phpcs:enable + // phpcs:enable $pdf->SetDrawColor(192, 192, 192); $pdf->SetLineWidth($epaisseur); @@ -255,8 +256,8 @@ return $value; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** * protected Give the height for a char size given. * @@ -265,7 +266,7 @@ */ protected function _Get_Height_Chars($pt) { - // phpcs:enable + // phpcs:enable // Array for link between height of characters and space between lines $_Table_Hauteur_Chars = array(6=>2, 7=>2.5, 8=>3, 9=>3.5, 10=>4, 11=>6, 12=>7, 13=>8, 14=>9, 15=>10); if (in_array($pt, array_keys($_Table_Hauteur_Chars))) { @@ -275,18 +276,18 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** * protected Set format * - * @param TCPDF $pdf PDF reference + * @param PDF $pdf PDF reference * @param string $format Format * @return void */ protected function _Set_Format(&$pdf, $format) { - // phpcs:enable + // phpcs:enable $this->_Metric = $format['metric']; $this->_Avery_Name = $format['name']; $this->_Avery_Code = $format['code']; --- /tmp/dsg/dolibarr/htdocs/core/class/github_conf.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_conf.class.php @@ -32,63 +32,61 @@ */ class Conf { - /** \public */ - //! To store properties found in conf file - public $file; - - /** - * @var Object Associative array with some properties ->type, ->db, ... - */ - public $db; - - //! To store properties found into database - public $global; - //! To store browser info - public $browser; - - //! To store if javascript/ajax is enabked - public $use_javascript_ajax; - //! To store if javascript/ajax is enabked - public $disable_compute; + /** \public */ + //! To store properties found in conf file + public $file; + + /** + * @var Object Associative array with some properties ->type, ->db, ... + */ + public $db; + + //! To store properties found into database + public $global; + //! To store browser info + public $browser; + + //! To store if javascript/ajax is enabked + public $use_javascript_ajax; + //! To store if javascript/ajax is enabked + public $disable_compute; //! Used to store current currency (ISO code like 'USD', 'EUR', ...) public $currency; - //! Used to store current css (from theme) public $theme; // Contains current theme ("eldy", "auguria", ...) public $css; // Contains full path of css page ("/theme/eldy/style.css.php", ...) - - //! Used to store current menu handler + //! Used to store current menu handler public $standard_menu; - // List of activated modules - public $modules = array(); - public $modules_parts = array( - 'css' => array(), - 'js' => array(), - 'tabs' => array(), - 'triggers' => array(), - 'login' => array(), - 'substitutions' => array(), - 'menus' => array(), - 'theme' => array(), - 'sms' => array(), - 'tpl' => array(), - 'barcode' => array(), - 'models' => array(), - 'societe' => array(), - 'hooks' => array(), - 'dir' => array(), - 'syslog' => array(), - ); - - public $logbuffer = array(); - - /** - * @var LogHandlerInterface[] - */ - public $loghandlers = array(); - - //! To store properties of multi-company - public $multicompany; + // List of activated modules + public $modules = array(); + public $modules_parts = array( + 'css' => array(), + 'js' => array(), + 'tabs' => array(), + 'triggers' => array(), + 'login' => array(), + 'substitutions' => array(), + 'menus' => array(), + 'theme' => array(), + 'sms' => array(), + 'tpl' => array(), + 'barcode' => array(), + 'models' => array(), + 'societe' => array(), + 'hooks' => array(), + 'dir' => array(), + 'syslog' => array(), + ); + + public $logbuffer = array(); + + /** + * @var LogHandlerInterface[] + */ + public $loghandlers = array(); + + //! To store properties of multi-company + public $multicompany; //! Used to store running instance for multi-company (default 1) public $entity = 1; //! Used to store list of entities to use for each element @@ -99,10 +97,6 @@ public $dol_optimize_smallscreen; // Set if we force param dol_optimize_smallscreen into login url or if browser is smartphone public $dol_no_mouse_hover; // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone public $dol_use_jmobile; // Set if we force param dol_use_jmobile into login url - - public $liste_limit; - - public $tzuserinputkey = 'tzserver'; // Use 'tzuserrel' to always store date in GMT and show date in time zone of user. /** @@ -128,7 +122,7 @@ // First level object // TODO Remove this part. $this->expedition_bon = new stdClass(); - $this->delivery_note = new stdClass(); + $this->livraison_bon = new stdClass(); $this->fournisseur = new stdClass(); $this->product = new stdClass(); $this->service = new stdClass(); @@ -189,7 +183,7 @@ //if (! defined("$key")) define("$key", $value); // In some cases, the constant might be already forced (Example: SYSLOG_HANDLERS during install) $this->global->$key = $value; - if ($value && strpos($key, 'MAIN_MODULE_') === 0) + if ($value && preg_match('/^MAIN_MODULE_/', $key)) { $reg = array(); // If this is constant for a new tab page activated by a module. It initializes modules_parts['tabs']. @@ -197,7 +191,7 @@ { $partname = 'tabs'; $params = explode(':', $value, 2); - if (!is_array($this->modules_parts[$partname])) { $this->modules_parts[$partname] = array(); } + if (!isset($this->modules_parts[$partname]) || !is_array($this->modules_parts[$partname])) { $this->modules_parts[$partname] = array(); } $this->modules_parts[$partname][$params[0]][] = $value; // $value may be a string or an array } // If this is constant for all generic part activated by a module. It initializes @@ -218,7 +212,7 @@ elseif ($value == 1) $value = '/'.$modulename.'/core/modules/'.$partname.'/'; // ex: partname = societe $this->modules_parts[$partname] = array_merge($this->modules_parts[$partname], array($modulename => $value)); // $value may be a string or an array } - // If this is a module constant (must be at end) + // If this is a module constant (must be at end) elseif (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)$/i', $key, $reg)) { $modulename = strtolower($reg[1]); @@ -233,20 +227,20 @@ $i++; } - $db->free($resql); - } - - // Include other local consts.php files and fetch their values to the corresponding database constants. - if (!empty($this->global->LOCAL_CONSTS_FILES)) { - $filesList = explode(":", $this->global->LOCAL_CONSTS_FILES); - foreach ($filesList as $file) { - $file = dol_sanitizeFileName($file); - dol_include_once($file."/".$file."_consts.php"); // This file can run code like setting $this->global->XXX vars. - } - } - - //var_dump($this->modules); - //var_dump($this->modules_parts['theme']); + $db->free($resql); + } + + // Include other local consts.php files and fetch their values to the corresponding database constants. + if (!empty($this->global->LOCAL_CONSTS_FILES)) { + $filesList = explode(":", $this->global->LOCAL_CONSTS_FILES); + foreach ($filesList as $file) { + $file = dol_sanitizeFileName($file); + include_once DOL_DOCUMENT_ROOT."/".$file."/".$file."_consts.php"; // This file can run code like setting $this->global->XXX vars. + } + } + + //var_dump($this->modules); + //var_dump($this->modules_parts['theme']); // If you can't set timezone of your PHP, set this constant. Better is to set it to UTC. // In future, this constant will be forced to 'UTC' so PHP server timezone will not have effect anymore. @@ -255,7 +249,8 @@ { try { date_default_timezone_set($this->global->MAIN_SERVER_TZ); - } catch (Exception $e) + } + catch (Exception $e) { dol_syslog("Error: Bad value for parameter MAIN_SERVER_TZ=".$this->global->MAIN_SERVER_TZ, LOG_ERR); } @@ -276,7 +271,14 @@ if (empty($this->global->MAIN_MENUFRONT_STANDARD)) $this->global->MAIN_MENUFRONT_STANDARD = "eldy_menu.php"; if (empty($this->global->MAIN_MENU_SMARTPHONE)) $this->global->MAIN_MENU_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones if (empty($this->global->MAIN_MENUFRONT_SMARTPHONE)) $this->global->MAIN_MENUFRONT_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones + // Clean var use vat for company if (!isset($this->global->FACTURE_TVAOPTION)) $this->global->FACTURE_TVAOPTION = 1; + elseif (!empty($this->global->FACTURE_TVAOPTION) && !is_numeric($this->global->FACTURE_TVAOPTION)) + { + // Old value of option, we clean to use new value (0 or 1) + if ($this->global->FACTURE_TVAOPTION != "franchise") $this->global->FACTURE_TVAOPTION = 1; + else $this->global->FACTURE_TVAOPTION = 0; + } // Variable globales LDAP if (empty($this->global->LDAP_FIELD_FULLNAME)) $this->global->LDAP_FIELD_FULLNAME = ''; @@ -302,7 +304,7 @@ // Define default dir_output and dir_temp for directories of modules foreach ($this->modules as $module) { - //var_dump($module); + //var_dump($module); // For multicompany sharings $this->$module->multidir_output = array($this->entity => $rootfordata."/".$module); $this->$module->multidir_temp = array($this->entity => $rootfortemp."/".$module."/temp"); @@ -330,7 +332,9 @@ // For backward compatibility $this->$module->$dirname = $rootfordata."/".$name; - } else { + } + else + { // For multicompany sharings $this->$module->$multidirname = array($this->entity => $rootfortemp."/".$name."/temp"); @@ -376,8 +380,8 @@ // Sous module bons d'expedition $this->expedition_bon->enabled = (!empty($this->global->MAIN_SUBMODULE_EXPEDITION) ? $this->global->MAIN_SUBMODULE_EXPEDITION : 0); - // Sub module delivery note Sous module bons de livraison - $this->delivery_note->enabled = (!empty($this->global->MAIN_SUBMODULE_DELIVERY) ? $this->global->MAIN_SUBMODULE_DELIVERY : 0); + // Sous module bons de livraison + $this->livraison_bon->enabled = (!empty($this->global->MAIN_SUBMODULE_LIVRAISON) ? $this->global->MAIN_SUBMODULE_LIVRAISON : 0); // Module fournisseur if (!empty($this->fournisseur)) @@ -406,22 +410,28 @@ $this->fournisseur->payment->dir_output = $rootfordata."/fournisseur/payment"; // For backward compatibility $this->fournisseur->payment->dir_temp = $rootfortemp."/fournisseur/payment/temp"; // For backward compatibility - // To prepare split of module fournisseur into module 'fournisseur' + supplier_order + supplier_invoice - if (!empty($this->fournisseur->enabled) && empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // By default, if module supplier is on, and we don't use yet the new modules, we set artificialy the module properties + // To prepare split of module fournisseur into fournisseur + supplier_order + supplier_invoice + if (!empty($this->fournisseur->enabled) && empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // By default, if module supplier is on, we set new properties { - $this->supplier_order = new stdClass(); - $this->supplier_order->enabled = 1; - $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); - $this->supplier_order->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); - $this->supplier_order->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility - $this->supplier_order->dir_temp = $rootfortemp."/fournisseur/commande/temp"; // For backward compatibility - - $this->supplier_invoice = new stdClass(); - $this->supplier_invoice->enabled = 1; - $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture"); - $this->supplier_invoice->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/facture/temp"); - $this->supplier_invoice->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility - $this->supplier_invoice->dir_temp = $rootfortemp."/fournisseur/facture/temp"; // For backward compatibility + if (empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // This can be set to 1 once modules purchase order and supplier invoice exists + { + $this->supplier_order = new stdClass(); + $this->supplier_order->enabled = 1; + $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); + $this->supplier_order->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); + $this->supplier_order->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility + $this->supplier_order->dir_temp = $rootfortemp."/fournisseur/commande/temp"; // For backward compatibility + } + + if (empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // This can be set to 1 once modules purchase order and supplier invoice exists + { + $this->supplier_invoice = new stdClass(); + $this->supplier_invoice->enabled = 1; + $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture"); + $this->supplier_invoice->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/facture/temp"); + $this->supplier_invoice->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility + $this->supplier_invoice->dir_temp = $rootfortemp."/fournisseur/facture/temp"; // For backward compatibility + } } } @@ -437,8 +447,8 @@ $this->service->dir_temp = $rootfortemp."/produit/temp"; // Module productbatch - $this->productbatch->multidir_output = array($this->entity => $rootfordata."/productlot"); - $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/productlot/temp"); + $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot"); + $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/produitlot/temp"); // Module contrat $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract"); @@ -456,7 +466,7 @@ // Set some default values //$this->global->MAIN_LIST_FILTER_ON_DAY=1; // On filter that show date, we must show input field for day before or after month - $this->global->MAIN_MAIL_USE_MULTI_PART = 1; + $this->global->MAIN_MAIL_USE_MULTI_PART = 1; // societe if (empty($this->global->SOCIETE_CODECLIENT_ADDON)) $this->global->SOCIETE_CODECLIENT_ADDON = "mod_codeclient_leopard"; @@ -465,9 +475,9 @@ if (empty($this->global->CHEQUERECEIPTS_ADDON)) $this->global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint'; if (empty($this->global->TICKET_ADDON)) $this->global->TICKET_ADDON = 'mod_ticket_simple'; - // Security + // Security if (empty($this->global->USER_PASSWORD_GENERATED)) $this->global->USER_PASSWORD_GENERATED = 'standard'; // Default password generator - if (empty($this->global->MAIN_UMASK)) $this->global->MAIN_UMASK = '0664'; // Default mask + if (empty($this->global->MAIN_UMASK)) $this->global->MAIN_UMASK = '0664'; // Default mask // conf->use_javascript_ajax $this->use_javascript_ajax = 1; @@ -489,9 +499,7 @@ $this->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE = 0; $this->global->STOCK_CALCULATE_ON_SUPPLIER_BILL = 0; $this->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER = 0; - if (empty($this->reception->enabled)) { - $this->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER = 1; - } + if (empty($this->reception->enabled))$this->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER = 1; else { $this->global->STOCK_CALCULATE_ON_RECEPTION = 1; $this->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE = 0; @@ -505,16 +513,16 @@ if (empty($this->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY)) $this->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30; // Less than 1 minutes to be sure // conf->global->ACCOUNTING_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...) - if (empty($this->global->ACCOUNTING_MODE)) $this->global->ACCOUNTING_MODE = 'RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES' - - // By default, suppliers objects can be linked to all projects - if (!isset($this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)) $this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS = 1; - - // By default we enable feature to bill time spent - if (!isset($this->global->PROJECT_BILL_TIME_SPENT)) $this->global->PROJECT_BILL_TIME_SPENT = 1; - - // MAIN_HTML_TITLE - if (!isset($this->global->MAIN_HTML_TITLE)) $this->global->MAIN_HTML_TITLE = 'noapp,thirdpartynameonly,contactnameonly,projectnameonly'; + if (empty($this->global->ACCOUNTING_MODE)) $this->global->ACCOUNTING_MODE = 'RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES' + + // By default, suppliers objects can be linked to all projects + if (!isset($this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)) $this->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS = 1; + + // By default we enable feature to bill time spent + if (!isset($this->global->PROJECT_BILL_TIME_SPENT)) $this->global->PROJECT_BILL_TIME_SPENT = 1; + + // MAIN_HTML_TITLE + if (!isset($this->global->MAIN_HTML_TITLE)) $this->global->MAIN_HTML_TITLE = 'noapp,thirdpartynameonly,contactnameonly,projectnameonly'; // conf->liste_limit = constante de taille maximale des listes if (empty($this->global->MAIN_SIZE_LISTE_LIMIT)) $this->global->MAIN_SIZE_LISTE_LIMIT = 25; @@ -526,7 +534,7 @@ // conf->theme et $this->css if (empty($this->global->MAIN_THEME)) $this->global->MAIN_THEME = "eldy"; - if (!empty($this->global->MAIN_FORCETHEME)) $this->global->MAIN_THEME = $this->global->MAIN_FORCETHEME; + if (!empty($this->global->MAIN_FORCETHEME)) $this->global->MAIN_THEME = $this->global->MAIN_FORCETHEME; $this->theme = $this->global->MAIN_THEME; $this->css = "/theme/".$this->theme."/style.css.php"; @@ -543,22 +551,20 @@ if (!empty($this->global->MAILING_EMAIL_FROM)) $this->mailing->email_from = $this->global->MAILING_EMAIL_FROM; if (!isset($this->global->MAIN_EMAIL_ADD_TRACK_ID)) $this->global->MAIN_EMAIL_ADD_TRACK_ID = 1; - if (!isset($this->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) $this->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP = 1; - - // Format for date (used by default when not found or not searched in lang) - $this->format_date_short = "%d/%m/%Y"; // Format of day with PHP/C tags (strftime functions) - $this->format_date_short_java = "dd/MM/yyyy"; // Format of day with Java tags - $this->format_hour_short = "%H:%M"; - $this->format_hour_short_duration = "%H:%M"; - $this->format_date_text_short = "%d %b %Y"; - $this->format_date_text = "%d %B %Y"; - $this->format_date_hour_short = "%d/%m/%Y %H:%M"; - $this->format_date_hour_sec_short = "%d/%m/%Y %H:%M:%S"; - $this->format_date_hour_text_short = "%d %b %Y %H:%M"; - $this->format_date_hour_text = "%d %B %Y %H:%M"; - - // Duration of workday - if (!isset($this->global->MAIN_DURATION_OF_WORKDAY)) $this->global->MAIN_DURATION_OF_WORKDAY = 86400; + // Format for date (used by default when not found or not searched in lang) + $this->format_date_short = "%d/%m/%Y"; // Format of day with PHP/C tags (strftime functions) + $this->format_date_short_java = "dd/MM/yyyy"; // Format of day with Java tags + $this->format_hour_short = "%H:%M"; + $this->format_hour_short_duration = "%H:%M"; + $this->format_date_text_short = "%d %b %Y"; + $this->format_date_text = "%d %B %Y"; + $this->format_date_hour_short = "%d/%m/%Y %H:%M"; + $this->format_date_hour_sec_short = "%d/%m/%Y %H:%M:%S"; + $this->format_date_hour_text_short = "%d %b %Y %H:%M"; + $this->format_date_hour_text = "%d %B %Y %H:%M"; + + // Duration of workday + if (!isset($this->global->MAIN_DURATION_OF_WORKDAY)) $this->global->MAIN_DURATION_OF_WORKDAY = 86400; // Limites decimales si non definie (peuvent etre egale a 0) if (!isset($this->global->MAIN_MAX_DECIMALS_UNIT)) $this->global->MAIN_MAX_DECIMALS_UNIT = 5; @@ -598,76 +604,76 @@ if (empty($this->global->MAIN_USE_JQUERY_MULTISELECT) || $this->global->MAIN_USE_JQUERY_MULTISELECT == '1') $this->global->MAIN_USE_JQUERY_MULTISELECT = 'select2'; // Timeouts - if (empty($this->global->MAIN_USE_CONNECT_TIMEOUT)) $this->global->MAIN_USE_CONNECT_TIMEOUT = 10; - if (empty($this->global->MAIN_USE_RESPONSE_TIMEOUT)) $this->global->MAIN_USE_RESPONSE_TIMEOUT = 30; + if (empty($this->global->MAIN_USE_CONNECT_TIMEOUT)) $this->global->MAIN_USE_CONNECT_TIMEOUT = 10; + if (empty($this->global->MAIN_USE_RESPONSE_TIMEOUT)) $this->global->MAIN_USE_RESPONSE_TIMEOUT = 30; // Set default variable to calculate VAT as if option tax_mode was 0 (standard) - if (empty($this->global->TAX_MODE_SELL_PRODUCT)) $this->global->TAX_MODE_SELL_PRODUCT = 'invoice'; - if (empty($this->global->TAX_MODE_BUY_PRODUCT)) $this->global->TAX_MODE_BUY_PRODUCT = 'invoice'; - if (empty($this->global->TAX_MODE_SELL_SERVICE)) $this->global->TAX_MODE_SELL_SERVICE = 'payment'; - if (empty($this->global->TAX_MODE_BUY_SERVICE)) $this->global->TAX_MODE_BUY_SERVICE = 'payment'; + if (empty($this->global->TAX_MODE_SELL_PRODUCT)) $this->global->TAX_MODE_SELL_PRODUCT = 'invoice'; + if (empty($this->global->TAX_MODE_BUY_PRODUCT)) $this->global->TAX_MODE_BUY_PRODUCT = 'invoice'; + if (empty($this->global->TAX_MODE_SELL_SERVICE)) $this->global->TAX_MODE_SELL_SERVICE = 'payment'; + if (empty($this->global->TAX_MODE_BUY_SERVICE)) $this->global->TAX_MODE_BUY_SERVICE = 'payment'; // Delay before warnings // Avoid strict errors. TODO: Replace xxx->warning_delay with a property ->warning_delay_xxx if (isset($this->agenda)) { - $this->adherent->subscription = new stdClass(); - $this->adherent->subscription->warning_delay = (isset($this->global->MAIN_DELAY_MEMBERS) ? $this->global->MAIN_DELAY_MEMBERS : 0) * 86400; + $this->adherent->subscription = new stdClass(); + $this->adherent->subscription->warning_delay = (isset($this->global->MAIN_DELAY_MEMBERS) ? $this->global->MAIN_DELAY_MEMBERS : 0) * 24 * 60 * 60; } if (isset($this->agenda)) { - $this->agenda->warning_delay = (isset($this->global->MAIN_DELAY_ACTIONS_TODO) ? $this->global->MAIN_DELAY_ACTIONS_TODO : 7) * 86400; - } + $this->agenda->warning_delay = (isset($this->global->MAIN_DELAY_ACTIONS_TODO) ? $this->global->MAIN_DELAY_ACTIONS_TODO : 7) * 24 * 60 * 60; + } if (isset($this->projet)) { - $this->projet->warning_delay = (isset($this->global->MAIN_DELAY_PROJECT_TO_CLOSE) ? $this->global->MAIN_DELAY_PROJECT_TO_CLOSE : 7) * 86400; - $this->projet->task = new StdClass(); - $this->projet->task->warning_delay = (isset($this->global->MAIN_DELAY_TASKS_TODO) ? $this->global->MAIN_DELAY_TASKS_TODO : 7) * 86400; - } - + $this->projet->warning_delay = (isset($this->global->MAIN_DELAY_PROJECT_TO_CLOSE) ? $this->global->MAIN_DELAY_PROJECT_TO_CLOSE : 7) * 24 * 60 * 60; + $this->projet->task = new StdClass(); + $this->projet->task->warning_delay = (isset($this->global->MAIN_DELAY_TASKS_TODO) ? $this->global->MAIN_DELAY_TASKS_TODO : 7) * 24 * 60 * 60; + } + + if (isset($this->commande)) { + $this->commande->client = new stdClass(); + $this->commande->fournisseur = new stdClass(); + $this->commande->client->warning_delay = (isset($this->global->MAIN_DELAY_ORDERS_TO_PROCESS) ? $this->global->MAIN_DELAY_ORDERS_TO_PROCESS : 2) * 24 * 60 * 60; + $this->commande->fournisseur->warning_delay = (isset($this->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS) ? $this->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS : 7) * 24 * 60 * 60; + } + if (isset($this->propal)) { + $this->propal->cloture = new stdClass(); + $this->propal->facturation = new stdClass(); + $this->propal->cloture->warning_delay = (isset($this->global->MAIN_DELAY_PROPALS_TO_CLOSE) ? $this->global->MAIN_DELAY_PROPALS_TO_CLOSE : 0) * 24 * 60 * 60; + $this->propal->facturation->warning_delay = (isset($this->global->MAIN_DELAY_PROPALS_TO_BILL) ? $this->global->MAIN_DELAY_PROPALS_TO_BILL : 0) * 24 * 60 * 60; + } + if (isset($this->facture)) { + $this->facture->client = new stdClass(); + $this->facture->fournisseur = new stdClass(); + $this->facture->client->warning_delay = (isset($this->global->MAIN_DELAY_CUSTOMER_BILLS_UNPAYED) ? $this->global->MAIN_DELAY_CUSTOMER_BILLS_UNPAYED : 0) * 24 * 60 * 60; + $this->facture->fournisseur->warning_delay = (isset($this->global->MAIN_DELAY_SUPPLIER_BILLS_TO_PAY) ? $this->global->MAIN_DELAY_SUPPLIER_BILLS_TO_PAY : 0) * 24 * 60 * 60; + } + if (isset($this->contrat)) { + $this->contrat->services = new stdClass(); + $this->contrat->services->inactifs = new stdClass(); + $this->contrat->services->expires = new stdClass(); + $this->contrat->services->inactifs->warning_delay = (isset($this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES) ? $this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES : 0) * 24 * 60 * 60; + $this->contrat->services->expires->warning_delay = (isset($this->global->MAIN_DELAY_RUNNING_SERVICES) ? $this->global->MAIN_DELAY_RUNNING_SERVICES : 0) * 24 * 60 * 60; + } if (isset($this->commande)) { - $this->commande->client = new stdClass(); - $this->commande->fournisseur = new stdClass(); - $this->commande->client->warning_delay = (isset($this->global->MAIN_DELAY_ORDERS_TO_PROCESS) ? $this->global->MAIN_DELAY_ORDERS_TO_PROCESS : 2) * 86400; - $this->commande->fournisseur->warning_delay = (isset($this->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS) ? $this->global->MAIN_DELAY_SUPPLIER_ORDERS_TO_PROCESS : 7) * 86400; - } - if (isset($this->propal)) { - $this->propal->cloture = new stdClass(); - $this->propal->facturation = new stdClass(); - $this->propal->cloture->warning_delay = (isset($this->global->MAIN_DELAY_PROPALS_TO_CLOSE) ? $this->global->MAIN_DELAY_PROPALS_TO_CLOSE : 0) * 86400; - $this->propal->facturation->warning_delay = (isset($this->global->MAIN_DELAY_PROPALS_TO_BILL) ? $this->global->MAIN_DELAY_PROPALS_TO_BILL : 0) * 86400; - } - if (isset($this->facture)) { - $this->facture->client = new stdClass(); - $this->facture->fournisseur = new stdClass(); - $this->facture->client->warning_delay = (isset($this->global->MAIN_DELAY_CUSTOMER_BILLS_UNPAYED) ? $this->global->MAIN_DELAY_CUSTOMER_BILLS_UNPAYED : 0) * 86400; - $this->facture->fournisseur->warning_delay = (isset($this->global->MAIN_DELAY_SUPPLIER_BILLS_TO_PAY) ? $this->global->MAIN_DELAY_SUPPLIER_BILLS_TO_PAY : 0) * 86400; - } - if (isset($this->contrat)) { - $this->contrat->services = new stdClass(); - $this->contrat->services->inactifs = new stdClass(); - $this->contrat->services->expires = new stdClass(); - $this->contrat->services->inactifs->warning_delay = (isset($this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES) ? $this->global->MAIN_DELAY_NOT_ACTIVATED_SERVICES : 0) * 86400; - $this->contrat->services->expires->warning_delay = (isset($this->global->MAIN_DELAY_RUNNING_SERVICES) ? $this->global->MAIN_DELAY_RUNNING_SERVICES : 0) * 86400; - } - if (isset($this->commande)) { - $this->bank->rappro = new stdClass(); - $this->bank->cheque = new stdClass(); - $this->bank->rappro->warning_delay = (isset($this->global->MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE) ? $this->global->MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE : 0) * 86400; - $this->bank->cheque->warning_delay = (isset($this->global->MAIN_DELAY_CHEQUES_TO_DEPOSIT) ? $this->global->MAIN_DELAY_CHEQUES_TO_DEPOSIT : 0) * 86400; + $this->bank->rappro = new stdClass(); + $this->bank->cheque = new stdClass(); + $this->bank->rappro->warning_delay = (isset($this->global->MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE) ? $this->global->MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE : 0) * 24 * 60 * 60; + $this->bank->cheque->warning_delay = (isset($this->global->MAIN_DELAY_CHEQUES_TO_DEPOSIT) ? $this->global->MAIN_DELAY_CHEQUES_TO_DEPOSIT : 0) * 24 * 60 * 60; } if (isset($this->expensereport)) { - $this->expensereport->approve = new stdClass(); - $this->expensereport->approve->warning_delay = (isset($this->global->MAIN_DELAY_EXPENSEREPORTS) ? $this->global->MAIN_DELAY_EXPENSEREPORTS : 0) * 86400; - $this->expensereport->payment = new stdClass(); - $this->expensereport->payment->warning_delay = (isset($this->global->MAIN_DELAY_EXPENSEREPORTS_TO_PAY) ? $this->global->MAIN_DELAY_EXPENSEREPORTS_TO_PAY : 0) * 86400; - } - if (isset($this->holiday)) { - $this->holiday->approve = new stdClass(); - $this->holiday->approve->warning_delay = (isset($this->global->MAIN_DELAY_HOLIDAYS) ? $this->global->MAIN_DELAY_HOLIDAYS : 0) * 86400; - } + $this->expensereport->approve = new stdClass(); + $this->expensereport->approve->warning_delay = (isset($this->global->MAIN_DELAY_EXPENSEREPORTS) ? $this->global->MAIN_DELAY_EXPENSEREPORTS : 0) * 24 * 60 * 60; + $this->expensereport->payment = new stdClass(); + $this->expensereport->payment->warning_delay = (isset($this->global->MAIN_DELAY_EXPENSEREPORTS_TO_PAY) ? $this->global->MAIN_DELAY_EXPENSEREPORTS_TO_PAY : 0) * 24 * 60 * 60; + } + if (isset($this->holiday)) { + $this->holiday->approve = new stdClass(); + $this->holiday->approve->warning_delay = (isset($this->global->MAIN_DELAY_HOLIDAYS) ? $this->global->MAIN_DELAY_HOLIDAYS : 0) * 24 * 60 * 60; + } if (!empty($this->global->PRODUIT_MULTIPRICES) && empty($this->global->PRODUIT_MULTIPRICES_LIMIT)) { - $this->global->PRODUIT_MULTIPRICES_LIMIT = 5; + $this->global->PRODUIT_MULTIPRICES_LIMIT = 5; } // For modules that want to disable top or left menu @@ -691,11 +697,6 @@ // If we are in develop mode, we activate the option MAIN_SECURITY_CSRF_WITH_TOKEN to 1 if not already defined. if (!isset($this->global->MAIN_SECURITY_CSRF_WITH_TOKEN) && $this->global->MAIN_FEATURES_LEVEL >= 2) $this->global->MAIN_SECURITY_CSRF_WITH_TOKEN = 1; - - if (defined('MAIN_ANTIVIRUS_COMMAND')) $this->global->MAIN_ANTIVIRUS_COMMAND = constant('MAIN_ANTIVIRUS_COMMAND'); - if (defined('MAIN_ANTIVIRUS_PARAM')) $this->global->MAIN_ANTIVIRUS_PARAM = constant('MAIN_ANTIVIRUS_PARAM'); - - if (!empty($this->global->MAIN_TZUSERINPUTKEY)) $this->tzuserinputkey = $this->global->MAIN_TZUSERINPUTKEY; // 'tzserver' or 'tzuserrel' // For backward compatibility if (isset($this->product)) $this->produit = $this->product; @@ -705,50 +706,45 @@ if (isset($this->categorie)) $this->category = $this->categorie; if (isset($this->project)) $this->project = $this->projet; - // Object $mc - if (!defined('NOREQUIREMC') && !empty($this->multicompany->enabled)) - { - if (is_object($mc)) $mc->setValues($this); - } - - if (!empty($this->syslog->enabled)) { - // We init log handlers - if (!empty($this->global->SYSLOG_HANDLERS)) { - $handlers = json_decode($this->global->SYSLOG_HANDLERS); - } else { - $handlers = array(); - } - foreach ($handlers as $handler) { - $handler_file_found = ''; - $dirsyslogs = array_merge(array('/core/modules/syslog/'), $this->modules_parts['syslog']); - foreach ($dirsyslogs as $reldir) { - $dir = dol_buildpath($reldir, 0); - $newdir = dol_osencode($dir); - if (is_dir($newdir)) { - $file = $newdir.$handler.'.php'; - if (file_exists($file)) { - $handler_file_found = $file; - break; - } + // Object $mc + if (!defined('NOREQUIREMC') && !empty($this->multicompany->enabled)) + { + if (is_object($mc)) $mc->setValues($this); + } + + // We init log handlers + if (!empty($this->global->SYSLOG_HANDLERS)) { + $handlers = json_decode($this->global->SYSLOG_HANDLERS); + } else { + $handlers = array(); + } + foreach ($handlers as $handler) { + $handler_files = array(); + $dirsyslogs = array_merge(array('/core/modules/syslog/'), $this->modules_parts['syslog']); + foreach ($dirsyslogs as $reldir) { + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); + if (is_dir($newdir)) { + $file = $newdir.$handler.'.php'; + if (file_exists($file)) { + $handler_files[] = $file; } } - - if (empty($handler_file_found)) { - throw new Exception('Missing log handler file '.$handler.'.php'); - } - - require_once $handler_file_found; - $loghandlerinstance = new $handler(); - if (!$loghandlerinstance instanceof LogHandlerInterface) { - throw new Exception('Log handler does not extend LogHandlerInterface'); - } - - if (empty($this->loghandlers[$handler])) { - $this->loghandlers[$handler] = $loghandlerinstance; - } - } - } - - return 0; + } + + if (empty($handler_files)) { + throw new Exception('Missing log handler file '.$handler.'.php'); + } + + require_once $handler_files[0]; + $loghandlerinstance = new $handler(); + if (!$loghandlerinstance instanceof LogHandlerInterface) { + throw new Exception('Log handler does not extend LogHandlerInterface'); + } + + if (empty($this->loghandlers[$handler])) { + $this->loghandlers[$handler] = $loghandlerinstance; + } + } } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_coreobject.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_coreobject.class.php @@ -31,385 +31,408 @@ */ class CoreObject extends CommonObject { - public $withChild = true; - - /** - * @var Array $_fields Fields to synchronize with Database - */ - protected $fields = array(); - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct(DoliDB &$db) - { - $this->db = $db; - } - - /** - * Function to init fields - * - * @return bool - */ - protected function init() - { - $this->id = 0; - $this->datec = 0; - $this->tms = 0; - - if (!empty($this->fields)) - { - foreach ($this->fields as $field=>$info) - { - if ($this->isDate($info)) $this->{$field} = time(); - elseif ($this->isArray($info)) $this->{$field} = array(); - elseif ($this->isInt($info)) $this->{$field} = (int) 0; - elseif ($this->isFloat($info)) $this->{$field} = (double) 0; - else $this->{$field} = ''; - } - - $this->to_delete = false; - $this->is_clone = false; - - return true; - } else { - return false; - } - } - - /** - * Test type of field - * - * @param string $field name of field - * @param string $type type of field to test - * @return boolean value of field or false - */ - private function checkFieldType($field, $type) - { - if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type)) - { - return $this->{'is_'.$type}($this->fields[$field]); - } else { - return false; - } - } - - /** - * Get object and children from database - * - * @param int $id Id of object to load - * @param bool $loadChild used to load children from database - * @return int >0 if OK, <0 if KO, 0 if not found - */ - public function fetch($id, $loadChild = true) - { - $res = $this->fetchCommon($id); - if ($res > 0) { - if ($loadChild) $this->fetchChild(); - } - - return $res; - } - - - /** - * Function to instantiate a new child - * - * @param string $tabName Table name of child - * @param int $id If id is given, we try to return his key if exist or load if we try_to_load - * @param string $key Attribute name of the object id - * @param bool $try_to_load Force the fetch if an id is given - * @return int - */ - public function addChild($tabName, $id = 0, $key = 'id', $try_to_load = false) - { - if (!empty($id)) - { - foreach ($this->{$tabName} as $k=>&$object) - { - if ($object->{$key} === $id) return $k; - } - } - - $k = count($this->{$tabName}); - - $className = ucfirst($tabName); - $this->{$tabName}[$k] = new $className($this->db); - if ($id > 0 && $key === 'id' && $try_to_load) - { - $this->{$tabName}[$k]->fetch($id); - } - - return $k; - } - - - /** - * Function to set a child as to delete - * - * @param string $tabName Table name of child - * @param int $id Id of child to set as to delete - * @param string $key Attribute name of the object id - * @return bool - */ - public function removeChild($tabName, $id, $key = 'id') - { - foreach ($this->{$tabName} as &$object) - { - if ($object->{$key} == $id) - { - $object->to_delete = true; - return true; - } - } - return false; - } - - - /** - * Function to fetch children objects - * - * @return void - */ - public function fetchChild() - { - if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) - { - foreach ($this->childtables as &$childTable) - { - $className = ucfirst($childTable); - - $this->{$className} = array(); - - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id; - $res = $this->db->query($sql); - - if ($res) - { - while ($obj = $this->db->fetch_object($res)) - { - $o = new $className($this->db); - $o->fetch($obj->rowid); - - $this->{$className}[] = $o; - } - } else { - $this->errors[] = $this->db->lasterror(); - } - } - } - } - - /** - * Function to update children data - * - * @param User $user user object - * @return void - */ - public function saveChild(User &$user) - { - if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) - { - foreach ($this->childtables as &$childTable) - { - $className = ucfirst($childTable); - if (!empty($this->{$className})) - { - foreach ($this->{$className} as $i => &$object) - { - $object->{$this->fk_element} = $this->id; - - $object->update($user); - if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) unset($this->{$className}[$i]); - } - } - } - } - } - - - /** - * Function to update object or create or delete if needed - * - * @param User $user User object - * @return int < 0 if KO, > 0 if OK - */ - public function update(User &$user) - { - if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed - elseif (isset($this->to_delete) && $this->to_delete == true) return $this->delete($user); - - $error = 0; - $this->db->begin(); - - $res = $this->updateCommon($user); - if ($res) - { - $result = $this->call_trigger(strtoupper($this->element).'_UPDATE', $user); - if ($result < 0) $error++; - else $this->saveChild($user); - } else { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - } - - if (empty($error)) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } - - /** - * Function to create object in database - * - * @param User $user User object - * @return int < 0 if KO, > 0 if OK - */ - public function create(User $user) - { - if ($this->id > 0) return $this->update($user); - - $error = 0; - $this->db->begin(); - - $res = $this->createCommon($user); - if ($res) - { - $this->id = $this->db->last_insert_id($this->table_element); - - $result = $this->call_trigger(strtoupper($this->element).'_CREATE', $user); - if ($result < 0) $error++; - else $this->saveChild($user); - } else { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - } - - if (empty($error)) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } - - /** - * Function to delete object in database - * - * @param User $user user object - * @return int < 0 if KO, > 0 if OK - */ - public function delete(User &$user) - { - if ($this->id <= 0) return 0; - - $error = 0; - $this->db->begin(); - - $result = $this->call_trigger(strtoupper($this->element).'_DELETE', $user); - if ($result < 0) $error++; - - if (!$error) - { - $this->deleteCommon($user); - if ($this->withChild && !empty($this->childtables)) - { - foreach ($this->childtables as &$childTable) - { - $className = ucfirst($childTable); - if (!empty($this->{$className})) - { - foreach ($this->{$className} as &$object) - { - $object->delete($user); - } - } - } - } - } - - if (empty($error)) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - $this->db->rollback(); - return -1; - } - } - - - /** - * Function to get a formatted date - * - * @param string $field Attribute to return - * @param string $format Output date format - * @return string - */ - public function getDate($field, $format = '') - { - if (empty($this->{$field})) return ''; - else { - return dol_print_date($this->{$field}, $format); - } - } - - /** - * Function to set date in field - * - * @param string $field field to set - * @param string $date formatted date to convert - * @return mixed - */ - public function setDate($field, $date) - { - if (empty($date)) - { - $this->{$field} = 0; - } else { - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $this->{$field} = dol_stringtotime($date); - } - - return $this->{$field}; - } - - - /** - * Function to update current object - * - * @param array $Tab Array of values - * @return int - */ - public function setValues(&$Tab) - { - foreach ($Tab as $key => $value) - { - if ($this->checkFieldType($key, 'date')) - { - $this->setDate($key, $value); - } elseif ($this->checkFieldType($key, 'float')) - { - $this->{$key} = (double) price2num($value); - } elseif ($this->checkFieldType($key, 'int')) { - $this->{$key} = (int) price2num($value); - } else { - $this->{$key} = dol_string_nohtmltag($value); - } - } - - return 1; - } + public $withChild = true; + + /** + * @var Array $_fields Fields to synchronize with Database + */ + protected $fields = array(); + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB &$db) + { + $this->db = $db; + } + + /** + * Function to init fields + * + * @return bool + */ + protected function init() + { + $this->id = 0; + $this->datec = 0; + $this->tms = 0; + + if (!empty($this->fields)) + { + foreach ($this->fields as $field=>$info) + { + if ($this->isDate($info)) $this->{$field} = time(); + elseif ($this->isArray($info)) $this->{$field} = array(); + elseif ($this->isInt($info)) $this->{$field} = (int) 0; + elseif ($this->isFloat($info)) $this->{$field} = (double) 0; + else $this->{$field} = ''; + } + + $this->to_delete = false; + $this->is_clone = false; + + return true; + } + else + { + return false; + } + } + + /** + * Test type of field + * + * @param string $field name of field + * @param string $type type of field to test + * @return boolean value of field or false + */ + private function checkFieldType($field, $type) + { + if (isset($this->fields[$field]) && method_exists($this, 'is_'.$type)) + { + return $this->{'is_'.$type}($this->fields[$field]); + } + else + { + return false; + } + } + + /** + * Get object and children from database + * + * @param int $id Id of object to load + * @param bool $loadChild used to load children from database + * @return int >0 if OK, <0 if KO, 0 if not found + */ + public function fetch($id, $loadChild = true) + { + $res = $this->fetchCommon($id); + if ($res > 0) { + if ($loadChild) $this->fetchChild(); + } + + return $res; + } + + + /** + * Function to instantiate a new child + * + * @param string $tabName Table name of child + * @param int $id If id is given, we try to return his key if exist or load if we try_to_load + * @param string $key Attribute name of the object id + * @param bool $try_to_load Force the fetch if an id is given + * @return int + */ + public function addChild($tabName, $id = 0, $key = 'id', $try_to_load = false) + { + if (!empty($id)) + { + foreach ($this->{$tabName} as $k=>&$object) + { + if ($object->{$key} === $id) return $k; + } + } + + $k = count($this->{$tabName}); + + $className = ucfirst($tabName); + $this->{$tabName}[$k] = new $className($this->db); + if ($id > 0 && $key === 'id' && $try_to_load) + { + $this->{$tabName}[$k]->fetch($id); + } + + return $k; + } + + + /** + * Function to set a child as to delete + * + * @param string $tabName Table name of child + * @param int $id Id of child to set as to delete + * @param string $key Attribute name of the object id + * @return bool + */ + public function removeChild($tabName, $id, $key = 'id') + { + foreach ($this->{$tabName} as &$object) + { + if ($object->{$key} == $id) + { + $object->to_delete = true; + return true; + } + } + return false; + } + + + /** + * Function to fetch children objects + * + * @return void + */ + public function fetchChild() + { + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) + { + foreach ($this->childtables as &$childTable) + { + $className = ucfirst($childTable); + + $this->{$className} = array(); + + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id; + $res = $this->db->query($sql); + + if ($res) + { + while ($obj = $this->db->fetch_object($res)) + { + $o = new $className($this->db); + $o->fetch($obj->rowid); + + $this->{$className}[] = $o; + } + } + else + { + $this->errors[] = $this->db->lasterror(); + } + } + } + } + + /** + * Function to update children data + * + * @param User $user user object + * @return void + */ + public function saveChild(User &$user) + { + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) + { + foreach ($this->childtables as &$childTable) + { + $className = ucfirst($childTable); + if (!empty($this->{$className})) + { + foreach ($this->{$className} as $i => &$object) + { + $object->{$this->fk_element} = $this->id; + + $object->update($user); + if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) unset($this->{$className}[$i]); + } + } + } + } + } + + + /** + * Function to update object or create or delete if needed + * + * @param User $user User object + * @return int < 0 if KO, > 0 if OK + */ + public function update(User &$user) + { + if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed + elseif (isset($this->to_delete) && $this->to_delete == true) return $this->delete($user); + + $error = 0; + $this->db->begin(); + + $res = $this->updateCommon($user); + if ($res) + { + $result = $this->call_trigger(strtoupper($this->element).'_UPDATE', $user); + if ($result < 0) $error++; + else $this->saveChild($user); + } + else + { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } + + if (empty($error)) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1; + } + } + + /** + * Function to create object in database + * + * @param User $user user object + * @return int < 0 if KO, > 0 if OK + */ + public function create(User &$user) + { + if ($this->id > 0) return $this->update($user); + + $error = 0; + $this->db->begin(); + + $res = $this->createCommon($user); + if ($res) + { + $this->id = $this->db->last_insert_id($this->table_element); + + $result = $this->call_trigger(strtoupper($this->element).'_CREATE', $user); + if ($result < 0) $error++; + else $this->saveChild($user); + } + else + { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } + + if (empty($error)) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1; + } + } + + /** + * Function to delete object in database + * + * @param User $user user object + * @return int < 0 if KO, > 0 if OK + */ + public function delete(User &$user) + { + if ($this->id <= 0) return 0; + + $error = 0; + $this->db->begin(); + + $result = $this->call_trigger(strtoupper($this->element).'_DELETE', $user); + if ($result < 0) $error++; + + if (!$error) + { + $this->deleteCommon($user); + if ($this->withChild && !empty($this->childtables)) + { + foreach ($this->childtables as &$childTable) + { + $className = ucfirst($childTable); + if (!empty($this->{$className})) + { + foreach ($this->{$className} as &$object) + { + $object->delete($user); + } + } + } + } + } + + if (empty($error)) + { + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $this->db->rollback(); + return -1; + } + } + + + /** + * Function to get a formatted date + * + * @param string $field Attribute to return + * @param string $format Output date format + * @return string + */ + public function getDate($field, $format = '') + { + if (empty($this->{$field})) return ''; + else + { + return dol_print_date($this->{$field}, $format); + } + } + + /** + * Function to set date in field + * + * @param string $field field to set + * @param string $date formatted date to convert + * @return mixed + */ + public function setDate($field, $date) + { + if (empty($date)) + { + $this->{$field} = 0; + } + else + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + $this->{$field} = dol_stringtotime($date); + } + + return $this->{$field}; + } + + + /** + * Function to update current object + * + * @param array $Tab Array of values + * @return int + */ + public function setValues(&$Tab) + { + foreach ($Tab as $key => $value) + { + if ($this->checkFieldType($key, 'date')) + { + $this->setDate($key, $value); + } + elseif ($this->checkFieldType($key, 'float')) + { + $this->{$key} = (double) price2num($value); + } + elseif ($this->checkFieldType($key, 'int')) { + $this->{$key} = (int) price2num($value); + } + else + { + $this->{$key} = dol_string_nohtmltag($value); + } + } + + return 1; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_cstate.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_cstate.class.php @@ -27,9 +27,9 @@ class Cstate // extends CommonObject { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -44,13 +44,13 @@ //var $element='cstate'; //!< Id that identify managed objects //var $table_element='cstate'; //!< Name of table without prefix where object is stored - /** + /** * @var int ID */ public $id; public $code_departement; - public $code; + /** * @var string * @deprecated @@ -68,27 +68,27 @@ - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Create object into database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + + /** + * Create object into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -99,13 +99,13 @@ // Check parameters // Put here code to add control on parameters values - // Insert request + // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_departements("; $sql .= "rowid,"; $sql .= "code_departement,"; $sql .= "nom,"; $sql .= "active"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " ".(!isset($this->rowid) ? 'NULL' : "'".$this->db->escape($this->rowid)."'").","; $sql .= " ".(!isset($this->code_departement) ? 'NULL' : "'".$this->db->escape($this->code_departement)."'").","; $sql .= " ".(!isset($this->nom) ? 'NULL' : "'".$this->db->escape($this->nom)."'").","; @@ -115,84 +115,86 @@ $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - if (!$error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_departements"); - } - - // Commit or rollback - if ($error) + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_departements"); + } + + // Commit or rollback + if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from database - * - * @param int $id Id object - * @param string $code Code - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $code = '') - { - global $langs; - $sql = "SELECT"; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param string $code Code + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $code = '') + { + global $langs; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.code_departement,"; $sql .= " t.nom,"; $sql .= " t.active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_departements as t"; - if ($id) $sql .= " WHERE t.rowid = ".$id; - elseif ($code) $sql .= " WHERE t.code_departement = '".$this->db->escape($code)."'"; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->code_departement = $obj->code_departement; //deprecated - $this->code = $obj->code_departement; - $this->nom = $obj->nom; //deprecated - $this->name = $obj->nom; + $sql .= " FROM ".MAIN_DB_PREFIX."c_departements as t"; + if ($id) $sql .= " WHERE t.rowid = ".$id; + elseif ($code) $sql .= " WHERE t.code_departement = '".$this->db->escape($code)."'"; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->code_departement = $obj->code_departement; + $this->nom = $obj->nom; $this->active = $obj->active; - } - $this->db->free($resql); - - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Update object into database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) - { - global $conf, $langs; + } + $this->db->free($resql); + + return 1; + } + else + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update object into database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -204,40 +206,40 @@ // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_departements SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_departements SET"; $sql .= " code_departement=".(isset($this->code_departement) ? "'".$this->db->escape($this->code_departement)."'" : "null").","; $sql .= " nom=".(isset($this->nom) ? "'".$this->db->escape($this->nom)."'" : "null").","; $sql .= " active=".(isset($this->active) ? $this->active : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback - if ($error) { - foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else { - $this->db->commit(); - return 1; - } - } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback + if ($error) { + foreach ($this->errors as $errmsg) { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return 1; + } + } /** * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -250,19 +252,21 @@ dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } --- /tmp/dsg/dolibarr/htdocs/core/class/github_ctypent.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_ctypent.class.php @@ -28,9 +28,9 @@ class Ctypent // extends CommonObject { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -45,7 +45,7 @@ //var $element='ctypent'; //!< Id that identify managed objects //var $table_element='ctypent'; //!< Name of table without prefix where object is stored - /** + /** * @var int ID */ public $id; @@ -58,27 +58,27 @@ - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Create object into database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + + /** + * Create object into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -94,7 +94,7 @@ // Check parameters // Put here code to add control on parameters values - // Insert request + // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_typent("; $sql .= "id,"; @@ -104,7 +104,7 @@ $sql .= "module"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " ".(!isset($this->id) ? 'NULL' : "'".$this->db->escape($this->id)."'").","; $sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").","; @@ -118,88 +118,92 @@ $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_typent"); - } - - // Commit or rollback - if ($error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_typent"); + } + + // Commit or rollback + if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from database - * - * @param int $id Id object - * @param string $code Code - * @param string $label Label - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $code = '', $label = '') - { - global $langs; - $sql = "SELECT"; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param string $code Code + * @param string $label Label + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $code = '', $label = '') + { + global $langs; + $sql = "SELECT"; $sql .= " t.id,"; $sql .= " t.code,"; $sql .= " t.libelle as label,"; $sql .= " t.fk_country as country_id,"; $sql .= " t.active,"; $sql .= " t.module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_typent as t"; - if ($id) $sql .= " WHERE t.id = ".$id; - elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; - elseif ($label) $sql .= " WHERE t.libelle = '".$this->db->escape($label)."'"; - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->id; + $sql .= " FROM ".MAIN_DB_PREFIX."c_typent as t"; + if ($id) $sql .= " WHERE t.id = ".$id; + elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; + elseif ($label) $sql .= " WHERE t.libelle = '".$this->db->escape($label)."'"; + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->id; $this->code = $obj->code; $this->libelle = $obj->label; $this->country_id = $obj->country_id; $this->active = $obj->active; $this->module = $obj->module; - } - $this->db->free($resql); - - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Update object into database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) - { - global $conf, $langs; + } + $this->db->free($resql); + + return 1; + } + else + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update object into database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -212,44 +216,46 @@ // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_typent SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_typent SET"; $sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").","; $sql .= " libelle=".(isset($this->libelle) ? "'".$this->db->escape($this->libelle)."'" : "null").","; $sql .= " active=".(isset($this->active) ? $this->active : "null").","; $sql .= " module=".(isset($this->module) ? "'".$this->db->escape($this->module)."'" : "null").""; - $sql .= " WHERE id=".$this->id; + $sql .= " WHERE id=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } - } + } /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -262,21 +268,23 @@ dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback - if ($error) - { + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback + if ($error) + { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { - $this->db->commit(); - return 1; - } - } + } + else + { + $this->db->commit(); + return 1; + } + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_ctyperesource.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_ctyperesource.class.php @@ -50,9 +50,9 @@ public $code; /** - * @var string Type resource label - */ - public $label; + * @var string Type resource label + */ + public $label; public $active; @@ -252,7 +252,7 @@ $sql .= $this->db->order($sortfield, $sortorder); } if (!empty($limit)) { - $sql .= ' '.$this->db->plimit($limit, $offset); + $sql .= ' '.$this->db->plimit($limit, $offset); } $resql = $this->db->query($sql); @@ -482,9 +482,9 @@ public $code; /** - * @var string Type resource line label - */ - public $label; + * @var string Type resource line label + */ + public $label; public $active; --- /tmp/dsg/dolibarr/htdocs/core/class/github_cunits.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_cunits.class.php @@ -28,9 +28,9 @@ class CUnits // extends CommonObject { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -46,7 +46,7 @@ //var $element='ctypent'; //!< Id that identify managed objects //var $table_element='ctypent'; //!< Name of table without prefix where object is stored - /** + /** * @var int ID */ public $id; @@ -61,27 +61,27 @@ - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Create object into database - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + + /** + * Create object into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -97,7 +97,7 @@ // Check parameters // Put here code to add control on parameters values - // Insert request + // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units("; $sql .= "rowid,"; $sql .= "code,"; @@ -105,7 +105,7 @@ $sql .= "short_label,"; $sql .= "unit_type"; $sql .= "scale"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " ".(!isset($this->id) ? 'NULL' : "'".$this->db->escape($this->id)."'").","; $sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").","; $sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").","; @@ -117,45 +117,47 @@ $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_units"); - } - - // Commit or rollback - if ($error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_units"); + } + + // Commit or rollback + if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); - return $this->id; - } - } - - - /** - * Load object in memory from database - * - * @param int $id Id of CUnit object to fetch (rowid) - * @param string $code Code - * @param string $short_label Short Label ('g', 'kg', ...) - * @param string $unit_type Unit type ('size', 'surface', 'volume', 'weight', ...) - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $code = '', $short_label = '', $unit_type = '') - { - global $langs; - - $sql = "SELECT"; + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id of CUnit object to fetch (rowid) + * @param string $code Code + * @param string $short_label Short Label ('g', 'kg', ...) + * @param string $unit_type Unit type ('size', 'surface', 'volume', 'weight', ...) + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $code = '', $short_label = '', $unit_type = '') + { + global $langs; + + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.code,"; $sql .= " t.label,"; @@ -164,24 +166,24 @@ $sql .= " t.unit_type,"; $sql .= " t.scale,"; $sql .= " t.active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; - $sql_where = array(); - if ($id) $sql_where[] = " t.rowid = ".$id; - if ($unit_type) $sql_where[] = " t.unit_type = '".$this->db->escape($unit_type)."'"; - if ($code) $sql_where[] = " t.code = '".$this->db->escape($code)."'"; - if ($short_label) $sql_where[] = " t.short_label = '".$this->db->escape($short_label)."'"; - if (count($sql_where) > 0) { - $sql .= ' WHERE '.implode(' AND ', $sql_where); - } - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; + $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; + $sql_where = array(); + if ($id) $sql_where[] = " t.rowid = ".$id; + if ($unit_type) $sql_where[] = " t.unit_type = '".$this->db->escape($unit_type)."'"; + if ($code) $sql_where[] = " t.code = '".$this->db->escape($code)."'"; + if ($short_label) $sql_where[] = " t.short_label = '".$this->db->escape($short_label)."'"; + if (count($sql_where) > 0) { + $sql .= ' WHERE '.implode(' AND ', $sql_where); + } + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; $this->code = $obj->code; $this->label = $obj->label; $this->short_label = $obj->short_label; @@ -189,109 +191,115 @@ $this->unit_type = $obj->unit_type; $this->scale = $obj->scale; $this->active = $obj->active; - } - $this->db->free($resql); - - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } - - - /** - * Load list of objects in memory from the database. - * - * @param string $sortorder Sort Order - * @param string $sortfield Sort field - * @param int $limit limit - * @param int $offset Offset - * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) - * @param string $filtermode Filter mode (AND or OR) - * @return array|int int <0 if KO, array of pages if OK - */ - public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $sql = 'SELECT'; - $sql .= " t.rowid,"; - $sql .= " t.code,"; - $sql .= " t.label,"; - $sql .= " t.short_label,"; - $sql .= " t.unit_type,"; - $sql .= " t.scale,"; - $sql .= " t.active"; - $sql .= ' FROM '.MAIN_DB_PREFIX.'c_units as t'; - // Manage filter - $sqlwhere = array(); - if (count($filter) > 0) { - foreach ($filter as $key => $value) { - if ($key == 't.rowid' || $key == 't.active' || $key == 't.scale') { - $sqlwhere[] = $key.'='.(int) $value; - } elseif (strpos($key, 'date') !== false) { - $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; - } elseif ($key == 't.unit_type' || $key == 't.code' || $key == 't.short_label') { - $sqlwhere[] = $key.' = \''.$this->db->escape($value).'\''; - } else { - $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; - } - } - } - if (count($sqlwhere) > 0) { - $sql .= ' WHERE ('.implode(' '.$filtermode.' ', $sqlwhere).')'; - } - - if (!empty($sortfield)) { - $sql .= $this->db->order($sortfield, $sortorder); - } - if (!empty($limit)) { - $sql .= ' '.$this->db->plimit($limit, $offset); - } - - $resql = $this->db->query($sql); - if ($resql) { - $this->records = array(); - $num = $this->db->num_rows($resql); - if ($num > 0) { - while ($obj = $this->db->fetch_object($resql)) { - $record = new self($this->db); - - $record->id = $obj->rowid; - $record->code = $obj->code; - $record->label = $obj->label; - $record->short_label = $obj->short_label; - $record->unit_type = $obj->unit_type; - $record->scale = $obj->scale; - $record->active = $obj->active; - $this->records[$record->id] = $record; - } - } - $this->db->free($resql); - - return $this->records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - - /** - * Update object into database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) - { - global $conf, $langs; + } + $this->db->free($resql); + + return 1; + } + else + { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return array|int int <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $sql = 'SELECT'; + $sql .= " t.rowid,"; + $sql .= " t.code,"; + $sql .= " t.label,"; + $sql .= " t.short_label,"; + $sql .= " t.unit_type,"; + $sql .= " t.scale,"; + $sql .= " t.active"; + $sql .= ' FROM '.MAIN_DB_PREFIX.'c_units as t'; + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid' || $key == 't.active' || $key == 't.scale') { + $sqlwhere[] = $key.'='.(int) $value; + } + elseif (strpos($key, 'date') !== false) { + $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; + } + elseif ($key == 't.unit_type' || $key == 't.code' || $key == 't.short_label') { + $sqlwhere[] = $key.' = \''.$this->db->escape($value).'\''; + } + else { + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= ' WHERE ('.implode(' '.$filtermode.' ', $sqlwhere).')'; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $this->records = array(); + $num = $this->db->num_rows($resql); + if ($num > 0) { + while ($obj = $this->db->fetch_object($resql)) + { + $record = new self($this->db); + + $record->id = $obj->rowid; + $record->code = $obj->code; + $record->label = $obj->label; + $record->short_label = $obj->short_label; + $record->unit_type = $obj->unit_type; + $record->scale = $obj->scale; + $record->active = $obj->active; + $this->records[$record->id] = $record; + } + } + $this->db->free($resql); + + return $this->records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + + + /** + * Update object into database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -305,46 +313,48 @@ // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_units SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_units SET"; $sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").","; $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " short_label=".(isset($this->short_label) ? "'".$this->db->escape($this->short_label)."'" : "null").","; $sql .= " unit_type=".(isset($this->unit_type) ? "'".$this->db->escape($this->unit_type)."'" : "null").","; $sql .= " scale=".(isset($this->scale) ? "'".$this->db->escape($this->scale)."'" : "null").","; $sql .= " active=".(isset($this->active) ? $this->active : "null"); - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } - } + } /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -357,19 +367,21 @@ dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - - // Commit or rollback + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } else { + } + else + { $this->db->commit(); return 1; } @@ -385,9 +397,10 @@ public function getUnitFromCode($code, $mode = 'code') { - if ($mode == 'short_label') { + if($mode == 'short_label'){ return dol_getIdFromCode($this->db, $code, 'c_units', 'short_label', 'rowid'); - } elseif ($mode == 'code') { + } + elseif($mode == 'code'){ return dol_getIdFromCode($this->db, $code, 'c_units', 'code', 'rowid'); } @@ -403,29 +416,31 @@ */ public function unitConverter($value, $fk_unit, $fk_new_unit = 0) { - $value = doubleval(price2num($value)); + $value = doubleval(price2num($value)); $fk_unit = intval($fk_unit); // Calcul en unité de base $scaleUnitPow = $this->scaleOfUnitPow($fk_unit); // convert to standard unit - $value = $value * $scaleUnitPow; - if ($fk_new_unit != 0) { + $value = $value * $scaleUnitPow; + if($fk_new_unit !=0 ){ // Calcul en unité de base $scaleUnitPow = $this->scaleOfUnitPow($fk_new_unit); - if (!empty($scaleUnitPow)) + if(!empty($scaleUnitPow)) { // convert to new unit - $value = $value / $scaleUnitPow; + $value = $value / $scaleUnitPow; } } return round($value, 2); } + + /** * get scale of unit factor - * @param int $id id of unit in dictionary + * @param $id int id of unit in dictionary * @return float|int */ public function scaleOfUnitPow($id) @@ -433,9 +448,9 @@ $base = 10; // TODO : add base col into unit dictionary table $unit = $this->db->getRow('SELECT scale, unit_type from '.MAIN_DB_PREFIX.'c_units WHERE rowid = '.intval($id)); - if ($unit) { + if($unit){ // TODO : if base exist in unit dictionary table remove this convertion exception and update convertion infos in database exemple time hour currently scale 3600 will become scale 2 base 60 - if ($unit->unit_type == 'time') { + if($unit->unit_type == 'time'){ return doubleval($unit->scale); } --- /tmp/dsg/dolibarr/htdocs/core/class/github_discount.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_discount.class.php @@ -28,12 +28,12 @@ */ class DiscountAbsolute { - /** - * @var DoliDB Database handler. - */ - public $db; - - /** + /** + * @var DoliDB Database handler. + */ + public $db; + + /** * @var string Error code (or message) */ public $error; @@ -48,191 +48,194 @@ */ public $id; - /** + /** * @var int Thirdparty ID */ - public $fk_soc; - - public $discount_type; // 0 => customer discount, 1 => supplier discount - public $amount_ht; // - public $amount_tva; // - public $amount_ttc; // - public $multicurrency_amount_ht; - public $multicurrency_amount_tva; - public $multicurrency_amount_ttc; - // Vat rate - public $tva_tx; - public $vat_src_code; - - /** + public $fk_soc; + + public $discount_type; // 0 => customer discount, 1 => supplier discount + public $amount_ht; // + public $amount_tva; // + public $amount_ttc; // + public $multicurrency_amount_ht; + public $multicurrency_amount_tva; + public $multicurrency_amount_ttc; + // Vat rate + public $tva_tx; + public $vat_src_code; + + /** * @var int User ID Id utilisateur qui accorde la remise */ public $fk_user; - /** + /** * @var string description */ public $description; - /** - * Date creation record (datec) - * - * @var integer - */ - public $datec; - - /** - * @var int ID invoice line when a discount is used into an invoice line (for absolute discounts) - */ - public $fk_facture_line; - - /** - * @var int ID invoice when a discount line is used into an invoice (for credit note) - */ - public $fk_facture; - - /** - * @var int ID credit note or deposit used to create the discount - */ - public $fk_facture_source; - public $ref_facture_source; // Ref credit note or deposit used to create the discount + /** + * Date creation record (datec) + * + * @var integer + */ + public $datec; + + /** + * @var int ID invoice line when a discount is used into an invoice line (for absolute discounts) + */ + public $fk_facture_line; + + /** + * @var int ID invoice when a discount line is used into an invoice (for credit note) + */ + public $fk_facture; + + /** + * @var int ID credit note or deposit used to create the discount + */ + public $fk_facture_source; + public $ref_facture_source; // Ref credit note or deposit used to create the discount public $type_facture_source; - public $fk_invoice_supplier_source; - public $ref_invoice_supplier_source; // Ref credit note or deposit used to create the discount - public $type_invoice_supplier_source; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Load object from database into memory - * - * @param int $rowid id discount to load - * @param int $fk_facture_source fk_facture_source - * @param int $fk_invoice_supplier_source fk_invoice_supplier_source - * @return int <0 if KO, =0 if not found, >0 if OK - */ - public function fetch($rowid, $fk_facture_source = 0, $fk_invoice_supplier_source = 0) - { - global $conf; - - // Check parameters - if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source) - { - $this->error = 'ErrorBadParameters'; - return -1; - } - - $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,"; - $sql .= " sr.fk_user,"; - $sql .= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx, sr.vat_src_code,"; - $sql .= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; - $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,"; - $sql .= " sr.datec,"; - $sql .= " f.ref as ref_facture_source, f.type as type_facture_source,"; - $sql .= " fsup.ref as ref_invoice_supplier_source, fsup.type as type_invoice_supplier_source"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid"; - $sql .= " WHERE sr.entity IN (".getEntity('invoice').")"; - if ($rowid) $sql .= " AND sr.rowid=".$rowid; - if ($fk_facture_source) $sql .= " AND sr.fk_facture_source=".$fk_facture_source; - if ($fk_invoice_supplier_source) $sql .= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; - - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - - $this->id = $obj->rowid; - $this->fk_soc = $obj->fk_soc; - $this->discount_type = $obj->discount_type; - - $this->amount_ht = $obj->amount_ht; - $this->amount_tva = $obj->amount_tva; - $this->amount_ttc = $obj->amount_ttc; - - $this->multicurrency_amount_ht = $this->multicurrency_subprice = $obj->multicurrency_amount_ht; - $this->multicurrency_amount_tva = $obj->multicurrency_amount_tva; - $this->multicurrency_amount_ttc = $obj->multicurrency_amount_ttc; - - $this->tva_tx = $obj->tva_tx; - $this->vat_src_code = $obj->vat_src_code; - - $this->fk_user = $obj->fk_user; - $this->fk_facture_line = $obj->fk_facture_line; - $this->fk_facture = $obj->fk_facture; - $this->fk_facture_source = $obj->fk_facture_source; // Id credit note or deposit source - $this->ref_facture_source = $obj->ref_facture_source; // Ref credit note or deposit source - $this->type_facture_source = $obj->type_facture_source; // Type credit note or deposit source - $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line; - $this->fk_invoice_supplier = $obj->fk_invoice_supplier; - $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id credit note or deposit source - $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref credit note or deposit source - $this->type_invoice_supplier_source = $obj->type_invoice_supplier_source; // Type credit note or deposit source - $this->description = $obj->description; - $this->datec = $this->db->jdate($obj->datec); - - $this->db->free($resql); - return 1; - } else { - $this->db->free($resql); - return 0; - } - } else { - $this->error = $this->db->error(); - return -1; - } - } - - - /** - * Create a discount into database - * - * @param User $user User that create - * @return int <0 if KO, >0 if OK - */ - public function create($user) - { - global $conf, $langs; - - // Clean parameters - $this->amount_ht = price2num($this->amount_ht); - $this->amount_tva = price2num($this->amount_tva); - $this->amount_ttc = price2num($this->amount_ttc); - - $this->tva_tx = price2num($this->tva_tx); - - $this->multicurrency_amount_ht = price2num($this->multicurrency_amount_ht); - $this->multicurrency_amount_tva = price2num($this->multicurrency_amount_tva); - $this->multicurrency_amount_ttc = price2num($this->multicurrency_amount_ttc); - - if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht = 0; - if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva = 0; - if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc = 0; - if (empty($this->tva_tx)) $this->tva_tx = 0; - - // Check parameters - if (empty($this->description)) - { - $this->error = 'BadValueForPropertyDescription'; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - - $userid = $user->id; + public $fk_invoice_supplier_source; + public $ref_invoice_supplier_source; // Ref credit note or deposit used to create the discount + public $type_invoice_supplier_source; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + + /** + * Load object from database into memory + * + * @param int $rowid id discount to load + * @param int $fk_facture_source fk_facture_source + * @param int $fk_invoice_supplier_source fk_invoice_supplier_source + * @return int <0 if KO, =0 if not found, >0 if OK + */ + public function fetch($rowid, $fk_facture_source = 0, $fk_invoice_supplier_source = 0) + { + global $conf; + + // Check parameters + if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source) + { + $this->error = 'ErrorBadParameters'; + return -1; + } + + $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,"; + $sql .= " sr.fk_user,"; + $sql .= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx, sr.vat_src_code,"; + $sql .= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; + $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,"; + $sql .= " sr.datec,"; + $sql .= " f.ref as ref_facture_source, f.type as type_facture_source,"; + $sql .= " fsup.ref as ref_invoice_supplier_source, fsup.type as type_invoice_supplier_source"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid"; + $sql .= " WHERE sr.entity IN (".getEntity('invoice').")"; + if ($rowid) $sql .= " AND sr.rowid=".$rowid; + if ($fk_facture_source) $sql .= " AND sr.fk_facture_source=".$fk_facture_source; + if ($fk_invoice_supplier_source) $sql .= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->fk_soc = $obj->fk_soc; + $this->discount_type = $obj->discount_type; + + $this->amount_ht = $obj->amount_ht; + $this->amount_tva = $obj->amount_tva; + $this->amount_ttc = $obj->amount_ttc; + + $this->multicurrency_amount_ht = $this->multicurrency_subprice = $obj->multicurrency_amount_ht; + $this->multicurrency_amount_tva = $obj->multicurrency_amount_tva; + $this->multicurrency_amount_ttc = $obj->multicurrency_amount_ttc; + + $this->tva_tx = $obj->tva_tx; + $this->vat_src_code = $obj->vat_src_code; + + $this->fk_user = $obj->fk_user; + $this->fk_facture_line = $obj->fk_facture_line; + $this->fk_facture = $obj->fk_facture; + $this->fk_facture_source = $obj->fk_facture_source; // Id credit note or deposit source + $this->ref_facture_source = $obj->ref_facture_source; // Ref credit note or deposit source + $this->type_facture_source = $obj->type_facture_source; // Type credit note or deposit source + $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line; + $this->fk_invoice_supplier = $obj->fk_invoice_supplier; + $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id credit note or deposit source + $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref credit note or deposit source + $this->type_invoice_supplier_source = $obj->type_invoice_supplier_source; // Type credit note or deposit source + $this->description = $obj->description; + $this->datec = $this->db->jdate($obj->datec); + + $this->db->free($resql); + return 1; + } + else + { + $this->db->free($resql); + return 0; + } + } + else + { + $this->error = $this->db->error(); + return -1; + } + } + + + /** + * Create a discount into database + * + * @param User $user User that create + * @return int <0 if KO, >0 if OK + */ + public function create($user) + { + global $conf, $langs; + + // Clean parameters + $this->amount_ht = price2num($this->amount_ht); + $this->amount_tva = price2num($this->amount_tva); + $this->amount_ttc = price2num($this->amount_ttc); + + $this->tva_tx = price2num($this->tva_tx); + + $this->multicurrency_amount_ht = price2num($this->multicurrency_amount_ht); + $this->multicurrency_amount_tva = price2num($this->multicurrency_amount_tva); + $this->multicurrency_amount_ttc = price2num($this->multicurrency_amount_ttc); + + if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht = 0; + if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva = 0; + if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc = 0; + + // Check parameters + if (empty($this->description)) + { + $this->error = 'BadValueForPropertyDescription'; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + + $userid = $user->id; if (!($userid > 0)) // For example when record is saved into an anonymous context with a not loaded object $user. { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -241,463 +244,497 @@ $userid = $tmpinvoice->fk_user_author; // We use the author of invoice } - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; - $sql .= " (entity, datec, fk_soc, discount_type, fk_user, description,"; - $sql .= " amount_ht, amount_tva, amount_ttc, tva_tx, vat_src_code,"; - $sql .= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,"; - $sql .= " fk_facture_source, fk_invoice_supplier_source"; - $sql .= ")"; - $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)).", ".$userid.", '".$this->db->escape($this->description)."',"; - $sql .= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.", '".$this->db->escape($this->vat_src_code)."',"; - $sql .= " ".$this->multicurrency_amount_ht.", ".$this->multicurrency_amount_tva.", ".$this->multicurrency_amount_ttc.", "; - $sql .= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null").","; - $sql .= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'" : "null"); - $sql .= ")"; - - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except"); - return $this->id; - } else { - $this->error = $this->db->lasterror().' - sql='.$sql; - return -1; - } - } - - - /** - * Delete object in database. If fk_facture_source is defined, we delete all familiy with same fk_facture_source. If not, only with id is removed - * - * @param User $user Object of user asking to delete - * @return int <0 if KO, >0 if OK - */ - public function delete($user) - { - global $conf, $langs; - - // Check if we can remove the discount - if ($this->fk_facture_source) - { - $sql = "SELECT COUNT(rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except"; - $sql .= " WHERE (fk_facture_line IS NOT NULL"; // Not used as absolute simple discount - $sql .= " OR fk_facture IS NOT NULL)"; // Not used as credit note and not used as deposit - $sql .= " AND fk_facture_source = ".$this->fk_facture_source; - //$sql.=" AND rowid != ".$this->id; - - dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj->nb > 0) - { - $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; - return -2; - } - } else { - dol_print_error($this->db); - return -1; - } - } - - // Check if we can remove the discount - if ($this->fk_invoice_supplier_source) - { - $sql = "SELECT COUNT(rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except"; - $sql .= " WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount - $sql .= " OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit - $sql .= " AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; - //$sql.=" AND rowid != ".$this->id; - - dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj->nb > 0) - { - $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; - return -2; - } - } else { - dol_print_error($this->db); - return -1; - } - } - - $this->db->begin(); - - // Delete but only if not used - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except "; - if ($this->fk_facture_source) $sql .= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie - elseif ($this->fk_invoice_supplier_source) $sql .= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie - else $sql .= " WHERE rowid = ".$this->id; // Delete only line - $sql .= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount - $sql .= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit - $sql .= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount - $sql .= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit - - dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // If source of discount was a credit note or deposit, we change source statut. - if ($this->fk_facture_source) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."facture"; - $sql .= " set paye=0, fk_statut=1"; - $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source; - - dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } elseif ($this->fk_invoice_supplier_source) { - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; - $sql .= " set paye=0, fk_statut=1"; - $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source; - - dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } else { - $this->db->commit(); - return 1; - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Link the discount to a particular invoice line or a particular invoice. - * When discount is a global discount used as an invoice line, we link using rowidline. - * When discount is from a credit note used to reduce payment of an invoice, we link using rowidinvoice - * - * @param int $rowidline Invoice line id (To use discount into invoice lines) - * @param int $rowidinvoice Invoice id (To use discount as a credit note to reduc payment of invoice) - * @return int <0 if KO, >0 if OK - */ - public function link_to_invoice($rowidline, $rowidinvoice) - { - // phpcs:enable - // Check parameters - if (!$rowidline && !$rowidinvoice) - { - $this->error = 'ErrorBadParameters'; - return -1; - } - if ($rowidline && $rowidinvoice) - { - $this->error = 'ErrorBadParameters'; - return -2; - } - - $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if (!empty($this->discount_type)) { - if ($rowidline) $sql .= " SET fk_invoice_supplier_line = ".$rowidline; - if ($rowidinvoice) $sql .= " SET fk_invoice_supplier = ".$rowidinvoice; - } else { - if ($rowidline) $sql .= " SET fk_facture_line = ".$rowidline; - if ($rowidinvoice) $sql .= " SET fk_facture = ".$rowidinvoice; - } - $sql .= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!empty($this->discount_type)) { - $this->fk_invoice_supplier_line = $rowidline; - $this->fk_invoice_supplier = $rowidinvoice; - } else { - $this->fk_facture_line = $rowidline; - $this->fk_facture = $rowidinvoice; - } - return 1; - } else { - $this->error = $this->db->error(); - return -3; - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Link the discount to a particular invoice line or a particular invoice. - * Do not call this if discount is linked to a reconcialiated invoice - * - * @return int <0 if KO, >0 if OK - */ - public function unlink_invoice() - { - // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if (!empty($this->discount_type)) { - $sql .= " SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; - } else { + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; + $sql .= " (entity, datec, fk_soc, discount_type, fk_user, description,"; + $sql .= " amount_ht, amount_tva, amount_ttc, tva_tx, vat_src_code,"; + $sql .= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,"; + $sql .= " fk_facture_source, fk_invoice_supplier_source"; + $sql .= ")"; + $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)).", ".$userid.", '".$this->db->escape($this->description)."',"; + $sql .= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.", '".$this->db->escape($this->vat_src_code)."',"; + $sql .= " ".$this->multicurrency_amount_ht.", ".$this->multicurrency_amount_tva.", ".$this->multicurrency_amount_ttc.", "; + $sql .= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null").","; + $sql .= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'" : "null"); + $sql .= ")"; + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except"); + return $this->id; + } + else + { + $this->error = $this->db->lasterror().' - sql='.$sql; + return -1; + } + } + + + /** + * Delete object in database. If fk_facture_source is defined, we delete all familiy with same fk_facture_source. If not, only with id is removed + * + * @param User $user Object of user asking to delete + * @return int <0 if KO, >0 if OK + */ + public function delete($user) + { + global $conf, $langs; + + // Check if we can remove the discount + if ($this->fk_facture_source) + { + $sql = "SELECT COUNT(rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except"; + $sql .= " WHERE (fk_facture_line IS NOT NULL"; // Not used as absolute simple discount + $sql .= " OR fk_facture IS NOT NULL)"; // Not used as credit note and not used as deposit + $sql .= " AND fk_facture_source = ".$this->fk_facture_source; + //$sql.=" AND rowid != ".$this->id; + + dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; + return -2; + } + } + else + { + dol_print_error($this->db); + return -1; + } + } + + // Check if we can remove the discount + if ($this->fk_invoice_supplier_source) + { + $sql = "SELECT COUNT(rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except"; + $sql .= " WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount + $sql .= " OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit + $sql .= " AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; + //$sql.=" AND rowid != ".$this->id; + + dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; + return -2; + } + } + else + { + dol_print_error($this->db); + return -1; + } + } + + $this->db->begin(); + + // Delete but only if not used + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except "; + if ($this->fk_facture_source) $sql .= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie + elseif ($this->fk_invoice_supplier_source) $sql .= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie + else $sql .= " WHERE rowid = ".$this->id; // Delete only line + $sql .= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount + $sql .= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit + $sql .= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount + $sql .= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit + + dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // If source of discount was a credit note or deposit, we change source statut. + if ($this->fk_facture_source) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."facture"; + $sql .= " set paye=0, fk_statut=1"; + $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source; + + dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + elseif ($this->fk_invoice_supplier_source) { + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; + $sql .= " set paye=0, fk_statut=1"; + $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source; + + dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + else + { + $this->db->commit(); + return 1; + } + } + else + { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Link the discount to a particular invoice line or a particular invoice. + * When discount is a global discount used as an invoice line, we link using rowidline. + * When discount is from a credit note used to reduce payment of an invoice, we link using rowidinvoice + * + * @param int $rowidline Invoice line id (To use discount into invoice lines) + * @param int $rowidinvoice Invoice id (To use discount as a credit note to reduc payment of invoice) + * @return int <0 if KO, >0 if OK + */ + public function link_to_invoice($rowidline, $rowidinvoice) + { + // phpcs:enable + // Check parameters + if (!$rowidline && !$rowidinvoice) + { + $this->error = 'ErrorBadParameters'; + return -1; + } + if ($rowidline && $rowidinvoice) + { + $this->error = 'ErrorBadParameters'; + return -2; + } + + $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; + if (!empty($this->discount_type)) { + if ($rowidline) $sql .= " SET fk_invoice_supplier_line = ".$rowidline; + if ($rowidinvoice) $sql .= " SET fk_invoice_supplier = ".$rowidinvoice; + } else { + if ($rowidline) $sql .= " SET fk_facture_line = ".$rowidline; + if ($rowidinvoice) $sql .= " SET fk_facture = ".$rowidinvoice; + } + $sql .= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!empty($this->discount_type)) { + $this->fk_invoice_supplier_line = $rowidline; + $this->fk_invoice_supplier = $rowidinvoice; + } else { + $this->fk_facture_line = $rowidline; + $this->fk_facture = $rowidinvoice; + } + return 1; + } + else + { + $this->error = $this->db->error(); + return -3; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Link the discount to a particular invoice line or a particular invoice. + * Do not call this if discount is linked to a reconcialiated invoice + * + * @return int <0 if KO, >0 if OK + */ + public function unlink_invoice() + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; + if (!empty($this->discount_type)) { + $sql .= " SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; + } else { $sql .= " SET fk_facture_line = NULL, fk_facture = NULL"; } - $sql .= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - return 1; - } else { - $this->error = $this->db->error(); - return -3; - } - } - - - /** - * Return amount (with tax) of discounts currently available for a company, user or other criteria - * - * @param Societe $company Object third party for filter - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param int $maxvalue Filter on max value for discount - * @param int $discount_type 0 => customer discount, 1 => supplier discount + $sql .= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + return 1; + } + else + { + $this->error = $this->db->error(); + return -3; + } + } + + + /** + * Return amount (with tax) of discounts currently available for a company, user or other criteria + * + * @param Societe $company Object third party for filter + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param int $maxvalue Filter on max value for discount + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @param int $multicurrency Return multicurrency_amount instead of amount - * @return int <0 if KO, amount otherwise - */ - public function getAvailableDiscounts($company = '', $user = '', $filter = '', $maxvalue = 0, $discount_type = 0, $multicurrency = 0) - { - global $conf; - - dol_syslog(get_class($this)."::getAvailableDiscounts discount_type=".$discount_type, LOG_DEBUG); - - $sql = "SELECT SUM(rc.amount_ttc) as amount, SUM(rc.multicurrency_amount_ttc) as multicurrency_amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql .= " WHERE rc.entity = ".$conf->entity; - $sql .= " AND rc.discount_type=".intval($discount_type); - if (!empty($discount_type)) { - $sql .= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier - } else { - $sql .= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer - } - if (is_object($company)) $sql .= " AND rc.fk_soc = ".$company->id; - if (is_object($user)) $sql .= " AND rc.fk_user = ".$user->id; - if ($filter) $sql .= ' AND ('.$filter.')'; - if ($maxvalue) $sql .= ' AND rc.amount_ttc <= '.price2num($maxvalue); - - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - //while ($obj) - //{ - //print 'zz'.$obj->amount; - //$obj = $this->db->fetch_object($resql); - //} + * @return int <0 if KO, amount otherwise + */ + public function getAvailableDiscounts($company = '', $user = '', $filter = '', $maxvalue = 0, $discount_type = 0, $multicurrency = 0) + { + global $conf; + + dol_syslog(get_class($this)."::getAvailableDiscounts discount_type=".$discount_type, LOG_DEBUG); + + $sql = "SELECT SUM(rc.amount_ttc) as amount, SUM(rc.multicurrency_amount_ttc) as multicurrency_amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " WHERE rc.entity = ".$conf->entity; + $sql .= " AND rc.discount_type=".intval($discount_type); + if (!empty($discount_type)) { + $sql .= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier + } else { + $sql .= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer + } + if (is_object($company)) $sql .= " AND rc.fk_soc = ".$company->id; + if (is_object($user)) $sql .= " AND rc.fk_user = ".$user->id; + if ($filter) $sql .= ' AND ('.$filter.')'; + if ($maxvalue) $sql .= ' AND rc.amount_ttc <= '.price2num($maxvalue); + + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + //while ($obj) + //{ + //print 'zz'.$obj->amount; + //$obj = $this->db->fetch_object($resql); + //} if ($multicurrency) { return $obj->amount_multicurrency; } - return $obj->amount; - } - return -1; - } + return $obj->amount; + } + return -1; + } + + + /** + * Return amount (with tax) of all deposits invoices used by invoice as a payment. + * Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended). + * + * @param CommonInvoice $invoice Object invoice (customer of supplier) + * @param int $multicurrency 1=Return multicurrency_amount instead of amount + * @return int <0 if KO, Sum of credit notes and deposits amount otherwise + */ + public function getSumDepositsUsed($invoice, $multicurrency = 0) + { + dol_syslog(get_class($this)."::getSumDepositsUsed", LOG_DEBUG); + + if ($invoice->element == 'facture' || $invoice->element == 'invoice') + { + $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; + $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; + $sql .= ' AND f.type = 3'; + } + elseif ($invoice->element == 'invoice_supplier') + { + $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; + $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; + $sql .= ' AND f.type = 3'; + } + else + { + $this->error = get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter"; + dol_print_error($this->error); + return -1; + } + + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($multicurrency == 1) return $obj->multicurrency_amount; + else return $obj->amount; + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + } + + /** + * Return amount (with tax) of all credit notes invoices + excess received used by invoice as a payment + * + * @param CommonInvoice $invoice Object invoice + * @param int $multicurrency 1=Return multicurrency_amount instead of amount + * @return int <0 if KO, Sum of credit notes and excess received amount otherwise + */ + public function getSumCreditNotesUsed($invoice, $multicurrency = 0) + { + dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); + + if ($invoice->element == 'facture' || $invoice->element == 'invoice') + { + $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; + $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; + $sql .= ' AND f.type IN ('.$invoice::TYPE_STANDARD.', '.$invoice::TYPE_CREDIT_NOTE.', '.$invoice::TYPE_SITUATION.')'; // Find discount coming from credit note or excess received + } + elseif ($invoice->element == 'invoice_supplier') + { + $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; + $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; + $sql .= ' AND f.type IN ('.$invoice::TYPE_STANDARD.', '.$invoice::TYPE_CREDIT_NOTE.')'; // Find discount coming from credit note or excess paid + } + else + { + $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter"; + dol_print_error($this->error); + return -1; + } + + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($multicurrency == 1) return $obj->multicurrency_amount; + else return $obj->amount; + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + } + /** + * Return amount (with tax) of all converted amount for this credit note + * + * @param CommonInvoice $invoice Object invoice + * @param int $multicurrency Return multicurrency_amount instead of amount + * @return int <0 if KO, Sum of credit notes and deposits amount otherwise + */ + public function getSumFromThisCreditNotesNotUsed($invoice, $multicurrency = 0) + { + dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); + + if ($invoice->element == 'facture' || $invoice->element == 'invoice') + { + $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc'; + $sql .= ' WHERE rc.fk_facture IS NULL AND rc.fk_facture_source = '.$invoice->id; + } + elseif ($invoice->element == 'invoice_supplier') + { + $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc'; + $sql .= ' WHERE rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_source = '.$invoice->id; + } + else + { + $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter"; + dol_print_error($this->error); + return -1; + } + + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($multicurrency) return $obj->multicurrency_amount; + else return $obj->amount; + } + else + { + $this->error = $this->db->lasterror(); + return -1; + } + } + + /** + * Return clickable ref of object (with picto or not) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Picto only + * @param string $option Where to link to ('invoice' or 'discount') + * @return string String with URL + */ + public function getNomUrl($withpicto, $option = 'invoice') + { + global $langs; + + $result = ''; + $link = ''; + $linkend = ''; + $label = ''; + $picto = ''; + $ref = ''; + + if ($option == 'invoice') { + $facid = !empty($this->discount_type) ? $this->fk_invoice_supplier_source : $this->fk_facture_source; + $link = !empty($this->discount_type) ? '/fourn/facture/card.php' : '/compta/facture/card.php'; + $label = $langs->trans("ShowSourceInvoice").': '.$this->ref_facture_source; + $link = ''; + $linkend = ''; + $ref = !empty($this->discount_type) ? $this->ref_invoice_supplier_source : $this->ref_facture_source; + $picto = 'bill'; + } + if ($option == 'discount') { + $label = $langs->trans("Discount"); + $link = ''; + $linkend = ''; + $ref = $langs->trans("Discount"); + $picto = 'generic'; + } + + + if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + if ($withpicto && $withpicto != 2) $result .= ' '; + $result .= $link.$ref.$linkend; + return $result; + } /** - * Return amount (with tax) of all deposits invoices used by invoice as a payment. - * Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended). - * - * @param CommonInvoice $invoice Object invoice (customer of supplier) - * @param int $multicurrency 1=Return multicurrency_amount instead of amount - * @return int <0 if KO, Sum of credit notes and deposits amount otherwise - */ - public function getSumDepositsUsed($invoice, $multicurrency = 0) - { - dol_syslog(get_class($this)."::getSumDepositsUsed", LOG_DEBUG); - - if ($invoice->element == 'facture' || $invoice->element == 'invoice') - { - $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; - $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; - $sql .= ' AND f.type = 3'; - } elseif ($invoice->element == 'invoice_supplier') - { - $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; - $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; - $sql .= ' AND f.type = 3'; - } else { - $this->error = get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter"; - dol_print_error($this->error); - return -1; - } - - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($multicurrency == 1) return $obj->multicurrency_amount; - else return $obj->amount; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - - /** - * Return amount (with tax) of all credit notes invoices + excess received used by invoice as a payment - * - * @param CommonInvoice $invoice Object invoice - * @param int $multicurrency 1=Return multicurrency_amount instead of amount - * @return int <0 if KO, Sum of credit notes and excess received amount otherwise - */ - public function getSumCreditNotesUsed($invoice, $multicurrency = 0) - { - dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); - - if ($invoice->element == 'facture' || $invoice->element == 'invoice') - { - $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; - $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; - $sql .= ' AND f.type IN ('.$invoice::TYPE_STANDARD.', '.$invoice::TYPE_CREDIT_NOTE.', '.$invoice::TYPE_SITUATION.')'; // Find discount coming from credit note or excess received - } elseif ($invoice->element == 'invoice_supplier') - { - $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; - $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; - $sql .= ' AND f.type IN ('.$invoice::TYPE_STANDARD.', '.$invoice::TYPE_CREDIT_NOTE.')'; // Find discount coming from credit note or excess paid - } else { - $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter"; - dol_print_error($this->error); - return -1; - } - - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($multicurrency == 1) return $obj->multicurrency_amount; - else return $obj->amount; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - /** - * Return amount (with tax) of all converted amount for this credit note - * - * @param CommonInvoice $invoice Object invoice - * @param int $multicurrency Return multicurrency_amount instead of amount - * @return int <0 if KO, Sum of credit notes and deposits amount otherwise - */ - public function getSumFromThisCreditNotesNotUsed($invoice, $multicurrency = 0) - { - dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); - - if ($invoice->element == 'facture' || $invoice->element == 'invoice') - { - $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc'; - $sql .= ' WHERE rc.fk_facture IS NULL AND rc.fk_facture_source = '.$invoice->id; - } elseif ($invoice->element == 'invoice_supplier') - { - $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc'; - $sql .= ' WHERE rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_source = '.$invoice->id; - } else { - $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter"; - dol_print_error($this->error); - return -1; - } - - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($multicurrency) return $obj->multicurrency_amount; - else return $obj->amount; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - - /** - * Return clickable ref of object (with picto or not) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Picto only - * @param string $option Where to link to ('invoice' or 'discount') - * @return string String with URL - */ - public function getNomUrl($withpicto, $option = 'invoice') - { - global $langs; - - $result = ''; - $link = ''; - $linkend = ''; - $label = ''; - $picto = ''; - $ref = ''; - - if ($option == 'invoice') { - $facid = !empty($this->discount_type) ? $this->fk_invoice_supplier_source : $this->fk_facture_source; - $link = !empty($this->discount_type) ? '/fourn/facture/card.php' : '/compta/facture/card.php'; - $label = $langs->trans("ShowSourceInvoice").': '.$this->ref_facture_source; - $link = ''; - $linkend = ''; - $ref = !empty($this->discount_type) ? $this->ref_invoice_supplier_source : $this->ref_facture_source; - $picto = 'bill'; - } - if ($option == 'discount') { - $label = $langs->trans("Discount"); - $link = ''; - $linkend = ''; - $ref = $langs->trans("Discount"); - $picto = 'generic'; - } - - - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - $result .= $link.$ref.$linkend; - return $result; - } - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ public function initAsSpecimen() { --- /tmp/dsg/dolibarr/htdocs/core/class/github_doleditor.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_doleditor.class.php @@ -28,132 +28,132 @@ */ class DolEditor { - public $tool; // Store the selected tool - - // If using fckeditor - public $editor; - - // If not using fckeditor - public $content; - public $htmlname; - public $toolbarname; - public $toolbarstartexpanded; - public $rows; - public $cols; - public $height; - public $width; - public $readonly; - - - /** - * Create an object to build an HTML area to edit a large string content - * - * @param string $htmlname HTML name of WYSIWIG field - * @param string $content Content of WYSIWIG field - * @param int $width Width in pixel of edit area (auto by default) - * @param int $height Height in pixel of edit area (200px by default) - * @param string $toolbarname Name of bar set to use ('Full', 'dolibarr_notes[_encoded]', 'dolibarr_details[_encoded]'=the less featured, 'dolibarr_mailings[_encoded]', 'dolibarr_readonly'). - * @param string $toolbarlocation Where bar is stored : - * 'In' each window has its own toolbar - * 'Out:name' share toolbar into the div called 'name' - * @param boolean $toolbarstartexpanded Bar is visible or not at start + public $tool; // Store the selected tool + + // If using fckeditor + public $editor; + + // If not using fckeditor + public $content; + public $htmlname; + public $toolbarname; + public $toolbarstartexpanded; + public $rows; + public $cols; + public $height; + public $width; + public $readonly; + + + /** + * Create an object to build an HTML area to edit a large string content + * + * @param string $htmlname HTML name of WYSIWIG field + * @param string $content Content of WYSIWIG field + * @param int $width Width in pixel of edit area (auto by default) + * @param int $height Height in pixel of edit area (200px by default) + * @param string $toolbarname Name of bar set to use ('Full', 'dolibarr_notes[_encoded]', 'dolibarr_details[_encoded]'=the less featured, 'dolibarr_mailings[_encoded]', 'dolibarr_readonly'). + * @param string $toolbarlocation Where bar is stored : + * 'In' each window has its own toolbar + * 'Out:name' share toolbar into the div called 'name' + * @param boolean $toolbarstartexpanded Bar is visible or not at start * @param int $uselocalbrowser Enabled to add links to local object with local browser. If false, only external images can be added in content. * @param boolean|string $okforextendededitor True=Allow usage of extended editor tool if qualified (like ckeditor). If 'textarea', force use of simple textarea. If 'ace', force use of Ace. * Warning: If you use 'ace', don't forget to also include ace.js in page header. Also, the button "save" must have class="buttonforacesave". - * @param int $rows Size of rows for textarea tool + * @param int $rows Size of rows for textarea tool * @param string $cols Size of cols for textarea tool (textarea number of cols '70' or percent 'x%') * @param int $readonly 0=Read/Edit, 1=Read only */ - public function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = true, $okforextendededitor = true, $rows = 0, $cols = 0, $readonly = 0) - { - global $conf, $langs; - - dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname); - - if (!$rows) $rows = round($height / 20); - if (!$cols) $cols = ($width ?round($width / 6) : 80); + public function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = true, $okforextendededitor = true, $rows = 0, $cols = 0, $readonly = 0) + { + global $conf, $langs; + + dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname); + + if (!$rows) $rows = round($height / 20); + if (!$cols) $cols = ($width ?round($width / 6) : 80); $shorttoolbarname = preg_replace('/_encoded$/', '', $toolbarname); - // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor') - $defaulteditor = 'ckeditor'; - $this->tool = empty($conf->global->FCKEDITOR_EDITORNAME) ? $defaulteditor : $conf->global->FCKEDITOR_EDITORNAME; - $this->uselocalbrowser = $uselocalbrowser; - $this->readonly = $readonly; - - // Check if extended editor is ok. If not we force textarea - if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea'; + // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor') + $defaulteditor = 'ckeditor'; + $this->tool = empty($conf->global->FCKEDITOR_EDITORNAME) ? $defaulteditor : $conf->global->FCKEDITOR_EDITORNAME; + $this->uselocalbrowser = $uselocalbrowser; + $this->readonly = $readonly; + + // Check if extended editor is ok. If not we force textarea + if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea'; if ($okforextendededitor === 'ace') $this->tool = 'ace'; - //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile - - // Define some properties - if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) - { - if ($this->tool == 'ckeditor' && !dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML. - $this->content = dol_nl2br($content); - } - else { - $this->content = $content; - } - $this->htmlname = $htmlname; - $this->toolbarname = $shorttoolbarname; - $this->toolbarstartexpanded = $toolbarstartexpanded; - $this->rows = max(ROWS_3, $rows); - $this->cols = (preg_match('/%/', $cols) ? $cols : max(40, $cols)); // If $cols is a percent, we keep it, otherwise, we take max - $this->height = $height; - $this->width = $width; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output edit area inside the HTML stream. - * Output depends on this->tool (fckeditor, ckeditor, textarea, ...) - * - * @param int $noprint 1=Return HTML string instead of printing it to output - * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });". Used by CKEditor only. - * @param boolean $disallowAnyContent Disallow to use any content. true=restrict to a predefined list of allowed elements. Used by CKEditor only. - * @param string $titlecontent Show title content before editor area. Used by ACE editor only. - * @param string $option For ACE editor, set the source language ('html', 'php', 'javascript', ...) - * @return void|string - */ - public function Create($noprint = 0, $morejs = '', $disallowAnyContent = true, $titlecontent = '', $option = '') - { - // phpcs:enable - global $conf, $langs; - - $fullpage = false; - if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) - { - $disallowAnyContent = empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed or all - } - - $found = 0; + //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile + + // Define some properties + if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) + { + if ($this->tool == 'ckeditor' && ! dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML. + $this->content = dol_nl2br($content); + } + else { + $this->content = $content; + } + $this->htmlname = $htmlname; + $this->toolbarname = $shorttoolbarname; + $this->toolbarstartexpanded = $toolbarstartexpanded; + $this->rows = max(ROWS_3, $rows); + $this->cols = (preg_match('/%/', $cols) ? $cols : max(40, $cols)); // If $cols is a percent, we keep it, otherwise, we take max + $this->height = $height; + $this->width = $width; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Output edit area inside the HTML stream. + * Output depends on this->tool (fckeditor, ckeditor, textarea, ...) + * + * @param int $noprint 1=Return HTML string instead of printing it to output + * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });". Used by CKEditor only. + * @param boolean $disallowAnyContent Disallow to use any content. true=restrict to a predefined list of allowed elements. Used by CKEditor only. + * @param string $titlecontent Show title content before editor area. Used by ACE editor only. + * @param string $option For ACE editor, set the source language ('html', 'php', 'javascript', ...) + * @return void|string + */ + public function Create($noprint = 0, $morejs = '', $disallowAnyContent = true, $titlecontent = '', $option = '') + { + // phpcs:enable + global $conf, $langs; + + $fullpage = false; + if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) + { + $disallowAnyContent = empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed or all + } + + $found = 0; $out = ''; - if (in_array($this->tool, array('textarea', 'ckeditor'))) - { - $found = 1; - //$out.= ''; - - if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax) && !empty($conf->fckeditor->enabled)) - { - if (!defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR', '1'); - - if (!empty($conf->global->FCKEDITOR_SKIN)) { + if (in_array($this->tool, array('textarea', 'ckeditor'))) + { + $found = 1; + //$out.= ''; + + if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax) && !empty($conf->fckeditor->enabled)) + { + if (!defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR', '1'); + + if (!empty($conf->global->FCKEDITOR_SKIN)) { $skin = $conf->global->FCKEDITOR_SKIN; } else { $skin = 'moono-lisa'; // default with ckeditor 4.6 : moono-lisa } - $htmlencode_force = preg_match('/_encoded$/', $this->toolbarname) ? 'true' : 'false'; - - $out .= ''."\n"; - $out .= ''."\n"; - } - } - - // Output editor ACE - // Warning: ace.js and ext-statusbar.js must be loaded by the parent page. - if (preg_match('/^ace/', $this->tool)) - { - $found = 1; + } + $out .= ' })'.$morejs; + $out .= '});'."\n"; + $out .= ''."\n"; + } + } + + // Output editor ACE + // Warning: ace.js and ext-statusbar.js must be loaded by the parent page. + if (preg_match('/^ace/', $this->tool)) + { + $found = 1; $format = $option; - $out .= "\n".''."\n"; + $out .= "\n".''."\n"; if ($titlecontent) { - $out .= '
    '.$titlecontent; - $out .= '   -   '.dol_escape_htmltag($langs->trans("ShowMoreLines")).'     '; - $out .= '
    '; - $out .= ''."\n"; + $out .= ''."\n"; } - $out .= '
    content);
    
    -			$out .= '
    '; - $out .= ''; - - $out .= ''."\n"; - } - - if (empty($found)) - { - $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.'; - } - - if ($noprint) return $out; - else print $out; - } + $out .= ''."\n"; + } + + if (empty($found)) + { + $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.'; + } + + if ($noprint) return $out; + else print $out; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_dolexception.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_dolexception.class.php @@ -27,10 +27,10 @@ */ class DolException extends Exception { - /** - * Constructor - */ - public function __construct() - { - } + /** + * Constructor + */ + public function __construct() + { + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_dolgeoip.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_dolgeoip.class.php @@ -33,7 +33,7 @@ */ class DolGeoIP { - public $gi; + public $gi; /** * Constructor @@ -50,19 +50,21 @@ if ($type == 'country') { - // geoip may have been already included with PEAR + // geoip may have been already included with PEAR if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) - { - require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; - } - } elseif ($type == 'city') - { - // geoip may have been already included with PEAR + { + require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; + } + } + elseif ($type == 'city') + { + // geoip may have been already included with PEAR if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) - { - require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; - } - } else { print 'ErrorBadParameterInConstructor'; return 0; } + { + require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; + } + } + else { print 'ErrorBadParameterInConstructor'; return 0; } // Here, function exists (embedded into PHP or exists because we made include) if (empty($type) || empty($datfile)) @@ -83,22 +85,23 @@ { try { $this->gi = new GeoIp2\Database\Reader($datfile); // '/usr/local/share/GeoIP/GeoIP2-City.mmdb' - } catch (Exception $e) + } + catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - } elseif (function_exists('geoip_open')) + } + elseif (function_exists('geoip_open')) { $this->gi = geoip_open($datfile, GEOIP_STANDARD); } - elseif (function_exists('geoip_country_code_by_name')) { - $this->gi = 'NOGI'; // We are using embedded php geoip functions - //print 'function_exists(geoip_country_code_by_name))='.function_exists('geoip_country_code_by_name'); - //print geoip_database_info(); - } else { - $this->gi = ''; // For avoid error + else + { + $this->gi = 'NOGI'; // We are using embedded php geoip functions + //print 'function_exists(geoip_country_code_by_name))='.function_exists('geoip_country_code_by_name'); + //print geoip_database_info(); } } @@ -121,9 +124,11 @@ } if ($this->gi == 'NOGI') { - // geoip_country_code_by_addr does not exists - return strtolower(geoip_country_code_by_name($ip)); - } else { + // geoip_country_code_by_addr does not exists + return strtolower(geoip_country_code_by_name($ip)); + } + else + { if (preg_match('/^[0-9]+.[0-9]+\.[0-9]+\.[0-9]+/', $ip)) { if ($geoipversion == '2') @@ -131,25 +136,33 @@ try { $record = $this->gi->country($ip); return strtolower($record->country->isoCode); - } catch (Exception $e) { + } + catch (Exception $e) { //return $e->getMessage(); return ''; } - } else { - if (!function_exists('geoip_country_code_by_addr')) return strtolower(geoip_country_code_by_name($this->gi, $ip)); - return strtolower(geoip_country_code_by_addr($this->gi, $ip)); - } - } else { + } + else + { + if (!function_exists('geoip_country_code_by_addr')) return strtolower(geoip_country_code_by_name($this->gi, $ip)); + return strtolower(geoip_country_code_by_addr($this->gi, $ip)); + } + } + else + { if ($geoipversion == '2') { try { $record = $this->gi->country($ip); return strtolower($record->country->isoCode); - } catch (Exception $e) { + } + catch (Exception $e) { //return $e->getMessage(); return ''; } - } else { + } + else + { if (!function_exists('geoip_country_code_by_addr_v6')) return strtolower(geoip_country_code_by_name_v6($this->gi, $ip)); return strtolower(geoip_country_code_by_addr_v6($this->gi, $ip)); } @@ -180,46 +193,49 @@ try { $record = $this->gi->country($name); return $record->country->isoCode; - } catch (Exception $e) { + } + catch (Exception $e) { //return $e->getMessage(); return ''; } - } else { + } + else + { return geoip_country_code_by_name($this->gi, $name); } } - /** - * Return verion of data file - * - * @return string Version of datafile - */ - public function getVersion() - { - global $conf; - - $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; - - if ($geoipversion == 'php') - { - if ($this->gi == 'NOGI') return geoip_database_info(); - else return 'geoip_database_info() function not available'; - } - - return 'Not available (not using PHP internal geo functions - We are using embedded Geoip v'.$geoipversion.')'; - } - - /** - * Close geoip object - * - * @return void - */ - public function close() - { - if (function_exists('geoip_close')) { - // With some geoip with PEAR, geoip_close function may not exists - geoip_close($this->gi); - } - } + /** + * Return verion of data file + * + * @return string Version of datafile + */ + public function getVersion() + { + global $conf; + + $geoipversion = '2'; // 'php', or '2' + if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + + if ($geoipversion == 'php') + { + if ($this->gi == 'NOGI') return geoip_database_info(); + else return 'geoip_database_info() function not available'; + } + + return 'Not available (not using PHP internal geo functions - We are using embedded Geoip v'.$geoipversion.')'; + } + + /** + * Close geoip object + * + * @return void + */ + public function close() + { + if (function_exists('geoip_close')) { + // With some geoip with PEAR, geoip_close function may not exists + geoip_close($this->gi); + } + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_dolgraph.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_dolgraph.class.php @@ -39,9 +39,9 @@ */ class DolGraph { - public $type = array(); // Array with type of each series. Example: array('bars', 'horizontalbars', 'lines', 'pies', 'piesemicircle', 'polar'...) + public $type = array(); // Array with type of each series. Example: array('bars', 'lines', ...) public $mode = 'side'; // Mode bars graph: side, depth - private $_library = 'chart'; // Graphic library to use (jflot, chart, artichow) + private $_library = 'jflot'; // Graphic library to use (jflot, artichow) //! Array of data public $data; // Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...) @@ -103,8 +103,9 @@ $this->datacolor = array(array(120, 130, 150), array(160, 160, 180), array(190, 190, 220)); $this->bgcolor = array(235, 235, 224); - $color_file = DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/theme_vars.inc.php'; - if (is_readable($color_file)) { + $color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; + if (is_readable($color_file)) + { include_once $color_file; if (isset($theme_bordercolor)) $this->bordercolor = $theme_bordercolor; if (isset($theme_datacolor)) $this->datacolor = $theme_datacolor; @@ -114,12 +115,12 @@ $this->_library = $library; if ($this->_library == 'auto') { - $this->_library = (empty($conf->global->MAIN_JS_GRAPH) ? 'chart' : $conf->global->MAIN_JS_GRAPH); - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + $this->_library = (empty($conf->global->MAIN_JS_GRAPH) ? 'jflot' : $conf->global->MAIN_JS_GRAPH); + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2 * @@ -128,12 +129,12 @@ */ public function SetHorizTickIncrement($xi) { - // phpcs:enable + // phpcs:enable $this->horizTickIncrement = $xi; return true; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2 * @@ -142,12 +143,12 @@ */ public function SetNumXTicks($xt) { - // phpcs:enable + // phpcs:enable $this->SetNumXTicks = $xt; return true; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set label interval to reduce number of labels * @@ -156,12 +157,12 @@ */ public function SetLabelInterval($x) { - // phpcs:enable + // phpcs:enable $this->labelInterval = $x; return true; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Hide X grid * @@ -170,12 +171,12 @@ */ public function SetHideXGrid($bool) { - // phpcs:enable + // phpcs:enable $this->hideXGrid = $bool; return true; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Hide Y grid * @@ -184,12 +185,12 @@ */ public function SetHideYGrid($bool) { - // phpcs:enable + // phpcs:enable $this->hideYGrid = $bool; return true; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set y label * @@ -198,11 +199,11 @@ */ public function SetYLabel($label) { - // phpcs:enable + // phpcs:enable $this->YLabel = $label; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set width * @@ -211,11 +212,11 @@ */ public function SetWidth($w) { - // phpcs:enable + // phpcs:enable $this->width = $w; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set title * @@ -224,11 +225,11 @@ */ public function SetTitle($title) { - // phpcs:enable + // phpcs:enable $this->title = $title; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set data * @@ -238,11 +239,11 @@ */ public function SetData($data) { - // phpcs:enable + // phpcs:enable $this->data = $data; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set data * @@ -251,25 +252,25 @@ */ public function SetDataColor($datacolor) { - // phpcs:enable + // phpcs:enable $this->datacolor = $datacolor; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set type * * @param array $type Array with type for each serie. Example: array('type1', 'type2', ...) where type can be: - * 'pie', 'piesemicircle', 'polar', 'lines', 'linesnopoint', 'bars', 'horizontalbars'... + * 'pie', 'piesemicircle', 'polar', 'lines', 'linesnopoint', 'bars', ... * @return void */ public function SetType($type) { - // phpcs:enable + // phpcs:enable $this->type = $type; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set legend * @@ -278,11 +279,11 @@ */ public function SetLegend($legend) { - // phpcs:enable + // phpcs:enable $this->Legend = $legend; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set min width * @@ -291,120 +292,120 @@ */ public function SetLegendWidthMin($legendwidthmin) { - // phpcs:enable + // phpcs:enable $this->LegendWidthMin = $legendwidthmin; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set max value * * @param int $max Max value * @return void */ - public function SetMaxValue($max) - { - // phpcs:enable + public function SetMaxValue($max) + { + // phpcs:enable $this->MaxValue = $max; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get max value * * @return int Max value */ - public function GetMaxValue() - { - // phpcs:enable + public function GetMaxValue() + { + // phpcs:enable return $this->MaxValue; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set min value * * @param int $min Min value * @return void */ - public function SetMinValue($min) - { - // phpcs:enable + public function SetMinValue($min) + { + // phpcs:enable $this->MinValue = $min; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get min value * * @return int Max value */ - public function GetMinValue() - { - // phpcs:enable + public function GetMinValue() + { + // phpcs:enable return $this->MinValue; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set height * * @param int $h Height * @return void */ - public function SetHeight($h) - { - // phpcs:enable + public function SetHeight($h) + { + // phpcs:enable $this->height = $h; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set shading * * @param string $s Shading * @return void */ - public function SetShading($s) - { - // phpcs:enable + public function SetShading($s) + { + // phpcs:enable $this->SetShading = $s; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set shading * * @param string $s Shading * @return void */ - public function SetCssPrefix($s) - { - // phpcs:enable + public function SetCssPrefix($s) + { + // phpcs:enable $this->cssprefix = $s; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Reset bg color * * @return void */ - public function ResetBgColor() - { - // phpcs:enable + public function ResetBgColor() + { + // phpcs:enable unset($this->bgcolor); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Reset bgcolorgrid * * @return void */ - public function ResetBgColorGrid() - { - // phpcs:enable + public function ResetBgColorGrid() + { + // phpcs:enable unset($this->bgcolorgrid); } @@ -413,7 +414,7 @@ * * @return string Error */ - public function isGraphKo() + public function isGraphKo() { return $this->error; } @@ -424,7 +425,7 @@ * @param int $showlegend 1=Show legend (default), 0=Hide legend, 2=Show legend on right * @return void */ - public function setShowLegend($showlegend) + public function setShowLegend($showlegend) { $this->showlegend = $showlegend; } @@ -435,7 +436,7 @@ * @param int $showpointvalue 1=Show value for each point, as tooltip or inline (default), 0=Hide value * @return void */ - public function setShowPointValue($showpointvalue) + public function setShowPointValue($showpointvalue) { $this->showpointvalue = $showpointvalue; } @@ -446,92 +447,106 @@ * @param int $showpercent 1=Show percent for each point, as tooltip or inline, 0=Hide percent (default) * @return void */ - public function setShowPercent($showpercent) + public function setShowPercent($showpercent) { $this->showpercent = $showpercent; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define background color of complete image * * @param array $bg_color array(R,G,B) ou 'onglet' ou 'default' * @return void */ - public function SetBgColor($bg_color = array(255, 255, 255)) - { - // phpcs:enable + public function SetBgColor($bg_color = array(255, 255, 255)) + { + // phpcs:enable global $theme_bgcolor, $theme_bgcoloronglet; - if (!is_array($bg_color)) { - if ($bg_color == 'onglet') { + if (!is_array($bg_color)) + { + if ($bg_color == 'onglet') + { //print 'ee'.join(',',$theme_bgcoloronglet); $this->bgcolor = $theme_bgcoloronglet; - } else { + } + else + { $this->bgcolor = $theme_bgcolor; } - } else { + } + else + { $this->bgcolor = $bg_color; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define background color of grid * * @param array $bg_colorgrid array(R,G,B) ou 'onglet' ou 'default' * @return void */ - public function SetBgColorGrid($bg_colorgrid = array(255, 255, 255)) - { - // phpcs:enable + public function SetBgColorGrid($bg_colorgrid = array(255, 255, 255)) + { + // phpcs:enable global $theme_bgcolor, $theme_bgcoloronglet; - if (!is_array($bg_colorgrid)) { - if ($bg_colorgrid == 'onglet') { + if (!is_array($bg_colorgrid)) + { + if ($bg_colorgrid == 'onglet') + { //print 'ee'.join(',',$theme_bgcoloronglet); $this->bgcolorgrid = $theme_bgcoloronglet; - } else { + } + else + { $this->bgcolorgrid = $theme_bgcolor; } - } else { + } + else + { $this->bgcolorgrid = $bg_colorgrid; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Reset data color * * @return void */ - public function ResetDataColor() - { - // phpcs:enable - unset($this->datacolor); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** + public function ResetDataColor() + { + // phpcs:enable + unset($this->datacolor); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** * Get max value * * @return int Max value */ - public function GetMaxValueInData() - { - // phpcs:enable + public function GetMaxValueInData() + { + // phpcs:enable if (!is_array($this->data)) return 0; $k = 0; $vals = array(); $nblines = count($this->data); - $nbvalues = (empty($this->data[0]) ? 0 : count($this->data[0]) - 1); - - for ($j = 0; $j < $nblines; $j++) { - for ($i = 0; $i < $nbvalues; $i++) { + $nbvalues = count($this->data[0]) - 1; + + for ($j = 0; $j < $nblines; $j++) + { + for ($i = 0; $i < $nbvalues; $i++) + { $vals[$k] = $this->data[$j][$i + 1]; $k++; } @@ -540,25 +555,27 @@ return $vals[0]; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return min value of all data * * @return int Min value of all data */ - public function GetMinValueInData() - { - // phpcs:enable + public function GetMinValueInData() + { + // phpcs:enable if (!is_array($this->data)) return 0; $k = 0; $vals = array(); $nblines = count($this->data); - $nbvalues = (empty($this->data[0]) ? 0 : count($this->data[0]) - 1); - - for ($j = 0; $j < $nblines; $j++) { - for ($i = 0; $i < $nbvalues; $i++) { + $nbvalues = count($this->data[0]) - 1; + + for ($j = 0; $j < $nblines; $j++) + { + for ($i = 0; $i < $nbvalues; $i++) + { $vals[$k] = $this->data[$j][$i + 1]; $k++; } @@ -567,20 +584,21 @@ return $vals[0]; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return max value of all data * * @return int Max value of all data */ - public function GetCeilMaxValue() - { - // phpcs:enable + public function GetCeilMaxValue() + { + // phpcs:enable $max = $this->GetMaxValueInData(); if ($max != 0) $max++; $size = dol_strlen(abs(ceil($max))); $factor = 1; - for ($i = 0; $i < ($size - 1); $i++) { + for ($i = 0; $i < ($size - 1); $i++) + { $factor *= 10; } @@ -591,21 +609,22 @@ return $res; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return min value of all data * * @return double Max value of all data */ - public function GetFloorMinValue() - { - // phpcs:enable + public function GetFloorMinValue() + { + // phpcs:enable $min = $this->GetMinValueInData(); if ($min == '') $min = 0; if ($min != 0) $min--; $size = dol_strlen(abs(floor($min))); $factor = 1; - for ($i = 0; $i < ($size - 1); $i++) { + for ($i = 0; $i < ($size - 1); $i++) + { $factor *= 10; } @@ -622,27 +641,30 @@ * @param string $fileurl Url path to show image if saved onto disk * @return integer|null */ - public function draw($file, $fileurl = '') - { - if (empty($file)) { + public function draw($file, $fileurl = '') + { + if (empty($file)) + { $this->error = "Call to draw method was made with empty value for parameter file."; - dol_syslog(get_class($this) . "::draw " . $this->error, LOG_ERR); + dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR); return -2; } - if (!is_array($this->data)) { + if (!is_array($this->data)) + { $this->error = "Call to draw method was made but SetData was not called or called with an empty dataset for parameters"; - dol_syslog(get_class($this) . "::draw " . $this->error, LOG_ERR); + dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR); return -1; } - if (count($this->data) < 1) { + if (count($this->data) < 1) + { $this->error = "Call to draw method was made but SetData was is an empty dataset"; - dol_syslog(get_class($this) . "::draw " . $this->error, LOG_WARNING); - } - $call = "draw_" . $this->_library; + dol_syslog(get_class($this)."::draw ".$this->error, LOG_WARNING); + } + $call = "draw_".$this->_library; call_user_func_array(array($this, $call), array($file, $fileurl)); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Build a graph using JFlot library. Input when calling this method should be: * $this->data = array(array(0=>'labelxA',1=>yA), array('labelxB',yB)); @@ -661,12 +683,13 @@ */ private function draw_jflot($file, $fileurl) { - // phpcs:enable + // phpcs:enable global $conf, $langs; - dol_syslog(get_class($this) . "::draw_jflot this->type=" . join(',', $this->type) . " this->MaxValue=" . $this->MaxValue); - - if (empty($this->width) && empty($this->height)) { + dol_syslog(get_class($this)."::draw_jflot this->type=".join(',', $this->type)." this->MaxValue=".$this->MaxValue); + + if (empty($this->width) && empty($this->height)) + { print 'Error width or height not set'; return; } @@ -686,7 +709,7 @@ while ($i < $nblot) // Loop on each serie { $values = array(); // Array with horizontal y values (specific values of a serie) for each abscisse x - $serie[$i] = "var d" . $i . " = [];\n"; + $serie[$i] = "var d".$i." = [];\n"; // Fill array $values $x = 0; @@ -697,13 +720,16 @@ $x++; } - if (isset($this->type[$firstlot]) && in_array($this->type[$firstlot], array('pie', 'piesemicircle', 'polar'))) { + if (isset($this->type[$firstlot]) && in_array($this->type[$firstlot], array('pie', 'piesemicircle', 'polar'))) + { foreach ($values as $x => $y) { - if (isset($y)) $serie[$i] .= 'd' . $i . '.push({"label":"' . dol_escape_js($legends[$x]) . '", "data":' . $y . '});' . "\n"; + if (isset($y)) $serie[$i] .= 'd'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n"; } - } else { + } + else + { foreach ($values as $x => $y) { - if (isset($y)) $serie[$i] .= 'd' . $i . '.push([' . $x . ', ' . $y . ']);' . "\n"; + if (isset($y)) $serie[$i] .= 'd'.$i.'.push(['.$x.', '.$y.']);'."\n"; } } @@ -712,39 +738,45 @@ } $tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.')))); - $this->stringtoshow = '' . "\n"; - if (!empty($this->title)) $this->stringtoshow .= '
    ' . $this->title . '
    '; - if (!empty($this->shownographyet)) { - $this->stringtoshow .= '
    '; - $this->stringtoshow .= '
    ' . $langs->trans("NotEnoughDataYet") . '...
    '; - return; + $this->stringtoshow = ''."\n"; + if (!empty($this->title)) $this->stringtoshow .= '
    '.$this->title.'
    '; + if (!empty($this->shownographyet)) + { + $this->stringtoshow .= '
    '; + $this->stringtoshow .= '
    '.$langs->trans("NotEnoughDataYet").'...
    '; + return; } // Start the div that will contains all the graph $dolxaxisvertical = ''; if (count($this->data) > 20) $dolxaxisvertical = 'dol-xaxis-vertical'; - $this->stringtoshow .= '
    ' . "\n"; - - $this->stringtoshow .= '' . "\n"; + $this->stringtoshow .= ', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor : \'#e6e6e6\' }'."\n"; + //$this->stringtoshow.=', shadowSize: 20'."\n"; TODO Uncommet this + $this->stringtoshow .= '});'."\n"; + $this->stringtoshow .= '}'."\n"; + } + + $this->stringtoshow .= 'plotWithOptions_'.$tag.'();'."\n"; + $this->stringtoshow .= '});'."\n"; + $this->stringtoshow .= ''."\n"; } @@ -923,9 +961,10 @@ // phpcs:enable global $conf, $langs; - dol_syslog(get_class($this) . "::draw_chart this->type=" . join(',', $this->type) . " this->MaxValue=" . $this->MaxValue); - - if (empty($this->width) && empty($this->height)) { + dol_syslog(get_class($this)."::draw_chart this->type=".join(',', $this->type)." this->MaxValue=".$this->MaxValue); + + if (empty($this->width) && empty($this->height)) + { print 'Error width or height not set'; return; } @@ -946,8 +985,7 @@ // Works with line but not with bars //if ($nblot > 2) $firstlot = ($nblot - 2); // We limit nblot to 2 because jflot can't manage more than 2 bars on same x - $serie = array(); - $arrayofgroupslegend = array(); + $serie = array(); $arrayofgroupslegend = array(); //var_dump($this->data); $i = $firstlot; @@ -965,15 +1003,15 @@ $alabelexists = 1; $tmpykey = explode('_', ($array_of_ykeys[$i + ($alabelexists ? 1 : 0)]), 3); if (!empty($tmpykey[2]) || $tmpykey[2] == '0') { // This is a 'Group by' array - $tmpvalue = (array_key_exists('y_' . $tmpykey[1] . '_' . $tmpykey[2], $valarray) ? $valarray['y_' . $tmpykey[1] . '_' . $tmpykey[2]] : $valarray[$i + 1]); + $tmpvalue = (array_key_exists('y_'.$tmpykey[1].'_'.$tmpykey[2], $valarray) ? $valarray['y_'.$tmpykey[1].'_'.$tmpykey[2]] : $valarray[$i + 1]); $values[$x] = (is_numeric($tmpvalue) ? $tmpvalue : null); $arrayofgroupslegend[$i] = array( - 'stacknum' => $tmpykey[1], + 'stacknum'=> $tmpykey[1], 'legend' => $this->Legend[$tmpykey[1]], - 'legendwithgroup' => $this->Legend[$tmpykey[1]] . ' - ' . $tmpykey[2] + 'legendwithgroup' => $this->Legend[$tmpykey[1]].' - '.$tmpykey[2] ); } else { - $tmpvalue = (array_key_exists('y_' . $i, $valarray) ? $valarray['y_' . $i] : $valarray[$i + 1]); + $tmpvalue = (array_key_exists('y_'.$i, $valarray) ? $valarray['y_'.$i] : $valarray[$i + 1]); //var_dump($i.'_'.$x.'_'.$tmpvalue); $values[$x] = (is_numeric($tmpvalue) ? $tmpvalue : null); } @@ -983,9 +1021,9 @@ $j = 0; foreach ($values as $x => $y) { if (isset($y)) { - $serie[$i] .= ($j > 0 ? ", " : "") . $y; + $serie[$i] .= ($j > 0 ? ", " : "").$y; } else { - $serie[$i] .= ($j > 0 ? ", " : "") . 'null'; + $serie[$i] .= ($j > 0 ? ", " : "").'null'; } $j++; } @@ -998,11 +1036,12 @@ $tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.')))); - $this->stringtoshow = '' . "\n"; - if (!empty($this->title)) $this->stringtoshow .= '
    ' . $this->title . '
    '; - if (!empty($this->shownographyet)) { - $this->stringtoshow .= '
    '; - $this->stringtoshow .= '
    ' . $langs->trans("NotEnoughDataYet") . '...
    '; + $this->stringtoshow = ''."\n"; + if (!empty($this->title)) $this->stringtoshow .= '
    '.$this->title.'
    '; + if (!empty($this->shownographyet)) + { + $this->stringtoshow .= '
    '; + $this->stringtoshow .= '
    '.$langs->trans("NotEnoughDataYet").'...
    '; return; } @@ -1011,15 +1050,19 @@ if (count($this->data) > 20) $dolxaxisvertical = 'dol-xaxis-vertical'; // No height for the pie grah $cssfordiv = 'dolgraphchart'; - if (isset($this->type[$firstlot])) $cssfordiv .= ' dolgraphchar' . $this->type[$firstlot]; - $this->stringtoshow .= '
    ' . "\n"; - - $this->stringtoshow .= '' . "\n"; + $this->stringtoshow .= ']'."\n"; + $this->stringtoshow .= '}'."\n"; + $this->stringtoshow .= '});'."\n"; + } + + $this->stringtoshow .= ''."\n"; } @@ -1314,7 +1298,7 @@ * * @return string HTML string to total value */ - public function total() + public function total() { $value = 0; foreach ($this->data as $valarray) // Loop on each x @@ -1330,17 +1314,18 @@ * @param int|string $shownographyet Show graph to say there is not enough data or the message in $shownographyet if it is a string. * @return string HTML string to show graph */ - public function show($shownographyet = 0) + public function show($shownographyet = 0) { global $langs; - if ($shownographyet) { - $s = '
    '; + if ($shownographyet) + { + $s = '
    '; $s .= '
    '; if (is_numeric($shownographyet)) { - $s .= $langs->trans("NotEnoughDataYet") . '...'; + $s .= $langs->trans("NotEnoughDataYet").'...'; } else { - $s .= $shownographyet . '...'; + $s .= $shownographyet.'...'; } $s .= '
    '; return $s; --- /tmp/dsg/dolibarr/htdocs/core/class/github_dolreceiptprinter.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_dolreceiptprinter.class.php @@ -25,32 +25,32 @@ /* * Tags for ticket template * - * {dol_align_left} Left align text - * {dol_align_center} Center text - * {dol_align_right} Right align text - * {dol_use_font_a} Use font A of printer - * {dol_use_font_b} Use font B of printer - * {dol_use_font_c} Use font C of printer - * {dol_bold} Text Bold - * {dol_bold_disabled} Disable Text Bold - * {dol_double_height} Text double height - * {dol_double_width} Text double width - * {dol_default_height_width} Text default height and width - * {dol_underline} Underline text - * {dol_underline_disabled} Disable underline text - * {dol_cut_paper_full} Cut ticket completely - * {dol_cut_paper_partial} Cut ticket partially - * {dol_open_drawer} Open cash drawer - * {dol_beep} Activate buzzer - * {dol_print_barcode} Print barcode - * {dol_print_logo} Print logo stored on printer. Example : 32|32 - * {dol_print_logo_old} Print logo stored on printer. Must be followed by logo code. For old printers. - * {dol_print_object_lines} Print object lines - * {dol_print_object_tax} Print object total tax - * {dol_print_object_local_tax} Print object local tax - * {dol_print_object_total} Print object total - * {dol_print_order_lines} Print order lines for Printer - * {dol_print_payment} Print payment method + * Left align text + * Center text + * Right align text + * Use font A of printer + * Use font B of printer + * Use font C of printer + * Text Bold + * Disable Text Bold + * Text double height + * Text double width + * Text default height and width + * Underline text + * Disable underline text + * Cut ticket completely + * Cut ticket partially + * Open cash drawer + * Activate buzzer + * Print barcode + * Print logo stored on printer. Example : 32|32 + * Print logo stored on printer. Must be followed by logo code. For old printers. + * Print object lines + * Print object total tax + * Print object local tax + * Print object total + * Print order lines for Printer + * Print payment method * * Code which can be placed everywhere * Replaced by date AAAA-MM-DD @@ -115,429 +115,410 @@ */ class dolReceiptPrinter extends Printer { - const CONNECTOR_DUMMY = 1; - const CONNECTOR_FILE_PRINT = 2; - const CONNECTOR_NETWORK_PRINT = 3; - const CONNECTOR_WINDOWS_PRINT = 4; - const CONNECTOR_CUPS_PRINT = 5; - - /** - * @var DoliDB Database handler. - */ - public $db; - - /* + const CONNECTOR_DUMMY = 1; + const CONNECTOR_FILE_PRINT = 2; + const CONNECTOR_NETWORK_PRINT = 3; + const CONNECTOR_WINDOWS_PRINT = 4; + const CONNECTOR_CUPS_PRINT = 5; + + /** + * @var DoliDB Database handler. + */ + public $db; + + /* * @var string[] array of tags */ - public $tags; - public $printer; - public $template; - - /** - * Number of order printer - * @var int - */ - public $orderprinter; - - /** - * @var string Error code (or message) - */ - public $error = ''; - - /** - * @var string[] Error codes (or messages) - */ - public $errors = array(); - - /** - * Constructor - * - * @param DoliDB $db database - */ - public function __construct($db) - { - $this->db = $db; - $this->tags = array( - 'dol_line_feed' => 'DOL_LINE_FEED', - 'dol_line_feed_reverse' => 'DOL_LINE_FEED_REVERSE', - 'dol_align_left' => 'DOL_ALIGN_LEFT', - 'dol_align_center' => 'DOL_ALIGN_CENTER', - 'dol_align_right' => 'DOL_ALIGN_RIGHT', - 'dol_use_font_a' => 'DOL_USE_FONT_A', - 'dol_use_font_b' => 'DOL_USE_FONT_B', - 'dol_use_font_c' => 'DOL_USE_FONT_C', - 'dol_bold' => 'DOL_BOLD', - 'dol_bold_disabled' => 'DOL_BOLD_DISABLED', - 'dol_double_height' => 'DOL_DOUBLE_HEIGHT', - 'dol_double_width' => 'DOL_DOUBLE_WIDTH', - 'dol_default_height_width' => 'DOL_DEFAULT_HEIGHT_WIDTH', - 'dol_underline' => 'DOL_UNDERLINE', - 'dol_underline_disabled' => 'DOL_UNDERLINE_DISABLED', - 'dol_cut_paper_full' => 'DOL_CUT_PAPER_FULL', - 'dol_cut_paper_partial' => 'DOL_CUT_PAPER_PARTIAL', - 'dol_open_drawer' => 'DOL_OPEN_DRAWER', - 'dol_beep' => 'DOL_BEEP', - 'dol_print_text' => 'DOL_PRINT_TEXT', - 'dol_print_barcode' => 'DOL_PRINT_BARCODE', - 'dol_value_date' => 'DateInvoice', - 'dol_value_date_time' => 'DateInvoiceWithTime', - 'dol_value_year' => 'YearInvoice', - 'dol_value_month_letters' => 'DOL_VALUE_MONTH_LETTERS', - 'dol_value_month' => 'DOL_VALUE_MONTH', - 'dol_value_day' => 'DOL_VALUE_DAY', - 'dol_value_day_letters' => 'DOL_VALUE_DAY', - 'dol_print_payment' => 'DOL_PRINT_PAYMENT', - 'dol_print_logo' => 'DOL_PRINT_LOGO', - 'dol_print_logo_old' => 'DOL_PRINT_LOGO_OLD', - 'dol_value_object_id' => 'InvoiceID', - 'dol_value_object_ref' => 'InvoiceRef', - 'dol_print_object_lines' => 'DOL_PRINT_OBJECT_LINES', - 'dol_print_object_tax' => 'TotalVAT', - 'dol_print_object_local_tax1' => 'TotalLT1', - 'dol_print_object_local_tax2' => 'TotalLT2', - 'dol_print_object_total' => 'Total', - 'dol_print_object_number' => 'DOL_PRINT_OBJECT_NUMBER', - //'dol_value_object_points' => 'DOL_VALUE_OBJECT_POINTS', - 'dol_print_order_lines' => 'DOL_PRINT_ORDER_LINES', - 'dol_value_customer_firstname' => 'DOL_VALUE_CUSTOMER_FIRSTNAME', - 'dol_value_customer_lastname' => 'DOL_VALUE_CUSTOMER_LASTNAME', - 'dol_value_customer_mail' => 'DOL_VALUE_CUSTOMER_MAIL', - 'dol_value_customer_phone' => 'DOL_VALUE_CUSTOMER_PHONE', - 'dol_value_customer_skype' => 'DOL_VALUE_CUSTOMER_SKYPE', - 'dol_value_customer_tax_number' => 'DOL_VALUE_CUSTOMER_TAX_NUMBER', - //'dol_value_customer_account_balance' => 'DOL_VALUE_CUSTOMER_ACCOUNT_BALANCE', - //'dol_value_customer_points' => 'DOL_VALUE_CUSTOMER_POINTS', - 'dol_value_mysoc_name' => 'DOL_VALUE_MYSOC_NAME', - 'dol_value_mysoc_address' => 'Address', - 'dol_value_mysoc_zip' => 'Zip', - 'dol_value_mysoc_town' => 'Town', - 'dol_value_mysoc_country' => 'Country', - 'dol_value_mysoc_idprof1' => 'ProfId1', - 'dol_value_mysoc_idprof2' => 'ProfId2', - 'dol_value_mysoc_idprof3' => 'ProfId3', - 'dol_value_mysoc_idprof4' => 'ProfId4', - 'dol_value_mysoc_idprof5' => 'ProfId5', - 'dol_value_mysoc_idprof6' => 'ProfId6', - 'dol_value_mysoc_tva_intra' => 'VATIntra', - 'dol_value_mysoc_capital' => 'Capital', - 'dol_value_vendor_lastname' => 'VendorLastname', - 'dol_value_vendor_firstname' => 'VendorFirstname', - 'dol_value_vendor_mail' => 'VendorEmail', - ); - } - - /** - * list printers - * - * @return int 0 if OK; >0 if KO - */ - public function listPrinters() - { - global $conf; - $error = 0; - $line = 0; - $obj = array(); - $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; - $sql .= ' WHERE entity = '.$conf->entity; - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - while ($line < $num) { - $row = $this->db->fetch_array($resql); - switch ($row['fk_type']) { - case 1: - $row['fk_type_name'] = 'CONNECTOR_DUMMY'; - break; - case 2: - $row['fk_type_name'] = 'CONNECTOR_FILE_PRINT'; - break; - case 3: - $row['fk_type_name'] = 'CONNECTOR_NETWORK_PRINT'; - break; - case 4: - $row['fk_type_name'] = 'CONNECTOR_WINDOWS_PRINT'; - break; - case 5: - $row['fk_type_name'] = 'CONNECTOR_CUPS_PRINT'; - break; - default: - $row['fk_type_name'] = 'CONNECTOR_UNKNOWN'; - break; - } - switch ($row['fk_profile']) { - case 0: - $row['fk_profile_name'] = 'PROFILE_DEFAULT'; - break; - case 1: - $row['fk_profile_name'] = 'PROFILE_SIMPLE'; - break; - case 2: - $row['fk_profile_name'] = 'PROFILE_EPOSTEP'; - break; - case 3: - $row['fk_profile_name'] = 'PROFILE_P822D'; - break; - default: - $row['fk_profile_name'] = 'PROFILE_STAR'; - break; - } - $obj[] = $row; - $line++; - } - } else { - $error++; - $this->errors[] = $this->db->lasterror; - } - $this->listprinters = $obj; - return $error; - } - - - /** - * List printers templates - * - * @return int 0 if OK; >0 if KO - */ - public function listPrintersTemplates() - { - global $conf; - $error = 0; - $line = 0; - $obj = array(); - $sql = 'SELECT rowid, name, template'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql .= ' WHERE entity = '.$conf->entity; - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - while ($line < $num) { - $obj[] = $this->db->fetch_array($resql); - $line++; - } - } else { - $error++; - $this->errors[] = $this->db->lasterror; - } - $this->listprinterstemplates = $obj; - return $error; - } - - - /** - * Form to Select type printer - * - * @param string $selected Id printer type pre-selected - * @param string $htmlname select html name - * @return int 0 if OK; >0 if KO - */ - public function selectTypePrinter($selected = '', $htmlname = 'printertypeid') - { - global $langs; - - $options = array( - 1 => $langs->trans('CONNECTOR_DUMMY'), - 2 => $langs->trans('CONNECTOR_FILE_PRINT'), - 3 => $langs->trans('CONNECTOR_NETWORK_PRINT'), - 4 => $langs->trans('CONNECTOR_WINDOWS_PRINT'), + public $tags; + public $printer; + public $template; + + /** + * Number of order printer + * @var int + */ + public $orderprinter; + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string[] Error codes (or messages) + */ + public $errors = array(); + + /** + * Constructor + * + * @param DoliDB $db database + */ + public function __construct($db) + { + $this->db = $db; + $this->tags = array( + 'dol_line_feed' => 'DOL_LINE_FEED', + 'dol_line_feed_reverse' => 'DOL_LINE_FEED_REVERSE', + 'dol_align_left' => 'DOL_ALIGN_LEFT', + 'dol_align_center' => 'DOL_ALIGN_CENTER', + 'dol_align_right' => 'DOL_ALIGN_RIGHT', + 'dol_use_font_a' => 'DOL_USE_FONT_A', + 'dol_use_font_b' => 'DOL_USE_FONT_B', + 'dol_use_font_c' => 'DOL_USE_FONT_C', + 'dol_bold' => 'DOL_BOLD', + 'dol_bold_disabled' => 'DOL_BOLD_DISABLED', + 'dol_double_height' => 'DOL_DOUBLE_HEIGHT', + 'dol_double_width' => 'DOL_DOUBLE_WIDTH', + 'dol_default_height_width' => 'DOL_DEFAULT_HEIGHT_WIDTH', + 'dol_underline' => 'DOL_UNDERLINE', + 'dol_underline_disabled' => 'DOL_UNDERLINE_DISABLED', + 'dol_cut_paper_full' => 'DOL_CUT_PAPER_FULL', + 'dol_cut_paper_partial' => 'DOL_CUT_PAPER_PARTIAL', + 'dol_open_drawer' => 'DOL_OPEN_DRAWER', + 'dol_beep' => 'DOL_BEEP', + 'dol_print_text' => 'DOL_PRINT_TEXT', + 'dol_print_barcode' => 'DOL_PRINT_BARCODE', + 'dol_value_date' => 'DateInvoice', + 'dol_value_date_time' => 'DateInvoiceWithTime', + 'dol_value_year' => 'YearInvoice', + 'dol_value_month_letters' => 'DOL_VALUE_MONTH_LETTERS', + 'dol_value_month' => 'DOL_VALUE_MONTH', + 'dol_value_day' => 'DOL_VALUE_DAY', + 'dol_value_day_letters' => 'DOL_VALUE_DAY', + //'dol_print_payment', + 'dol_print_logo' => 'DOL_PRINT_LOGO', + 'dol_print_logo_old' => 'DOL_PRINT_LOGO_OLD', + 'dol_value_object_id' => 'InvoiceID', + 'dol_value_object_ref' => 'InvoiceRef', + 'dol_print_object_lines' => 'DOL_PRINT_OBJECT_LINES', + 'dol_print_object_tax' => 'TotalVAT', + 'dol_print_object_local_tax1' => 'TotalLT1', + 'dol_print_object_local_tax2' => 'TotalLT2', + 'dol_print_object_total' => 'Total', + 'dol_print_object_number' => 'DOL_PRINT_OBJECT_NUMBER', + 'dol_value_object_points' => 'DOL_VALUE_OBJECT_POINTS', + 'dol_print_order_lines' => 'DOL_PRINT_ORDER_LINES', + 'dol_value_customer_firstname' => 'DOL_VALUE_CUSTOMER_FIRSTNAME', + 'dol_value_customer_lastname' => 'DOL_VALUE_CUSTOMER_LASTNAME', + 'dol_value_customer_mail' => 'DOL_VALUE_CUSTOMER_MAIL', + 'dol_value_customer_phone' => 'DOL_VALUE_CUSTOMER_PHONE', + 'dol_value_customer_mobile' => 'DOL_VALUE_CUSTOMER_MOBILE', + 'dol_value_customer_skype' => 'DOL_VALUE_CUSTOMER_SKYPE', + 'dol_value_customer_tax_number' => 'DOL_VALUE_CUSTOMER_TAX_NUMBER', + 'dol_value_customer_account_balance' => 'DOL_VALUE_CUSTOMER_ACCOUNT_BALANCE', + 'dol_value_customer_points' => 'DOL_VALUE_CUSTOMER_POINTS', + 'dol_value_mysoc_name' => 'DOL_VALUE_MYSOC_NAME', + 'dol_value_mysoc_address' => 'Address', + 'dol_value_mysoc_zip' => 'Zip', + 'dol_value_mysoc_town' => 'Town', + 'dol_value_mysoc_country' => 'Country', + 'dol_value_mysoc_idprof1' => 'ProfId1', + 'dol_value_mysoc_idprof2' => 'ProfId2', + 'dol_value_mysoc_idprof3' => 'ProfId3', + 'dol_value_mysoc_idprof4' => 'ProfId4', + 'dol_value_mysoc_idprof5' => 'ProfId5', + 'dol_value_mysoc_idprof6' => 'ProfId6', + 'dol_value_mysoc_tva_intra' => 'VATIntra', + 'dol_value_mysoc_capital' => 'Capital', + 'dol_value_vendor_lastname' => 'VendorLastname', + 'dol_value_vendor_firstname' => 'VendorFirstname', + 'dol_value_vendor_mail' => 'VendorEmail', + ); + } + + /** + * list printers + * + * @return int 0 if OK; >0 if KO + */ + public function listPrinters() + { + global $conf; + $error = 0; + $line = 0; + $obj = array(); + $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' WHERE entity = '.$conf->entity; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + while ($line < $num) { + $row = $this->db->fetch_array($resql); + switch ($row['fk_type']) { + case 1: + $row['fk_type_name'] = 'CONNECTOR_DUMMY'; + break; + case 2: + $row['fk_type_name'] = 'CONNECTOR_FILE_PRINT'; + break; + case 3: + $row['fk_type_name'] = 'CONNECTOR_NETWORK_PRINT'; + break; + case 4: + $row['fk_type_name'] = 'CONNECTOR_WINDOWS_PRINT'; + break; + case 5: + $row['fk_type_name'] = 'CONNECTOR_CUPS_PRINT'; + break; + default: + $row['fk_type_name'] = 'CONNECTOR_UNKNOWN'; + break; + } + switch ($row['fk_profile']) { + case 0: + $row['fk_profile_name'] = 'PROFILE_DEFAULT'; + break; + case 1: + $row['fk_profile_name'] = 'PROFILE_SIMPLE'; + break; + case 2: + $row['fk_profile_name'] = 'PROFILE_EPOSTEP'; + break; + case 3: + $row['fk_profile_name'] = 'PROFILE_P822D'; + break; + default: + $row['fk_profile_name'] = 'PROFILE_STAR'; + break; + } + $obj[] = $row; + $line++; + } + } else { + $error++; + $this->errors[] = $this->db->lasterror; + } + $this->listprinters = $obj; + return $error; + } + + + /** + * List printers templates + * + * @return int 0 if OK; >0 if KO + */ + public function listPrintersTemplates() + { + global $conf; + $error = 0; + $line = 0; + $obj = array(); + $sql = 'SELECT rowid, name, template'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; + $sql .= ' WHERE entity = '.$conf->entity; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + while ($line < $num) { + $obj[] = $this->db->fetch_array($resql); + $line++; + } + } else { + $error++; + $this->errors[] = $this->db->lasterror; + } + $this->listprinterstemplates = $obj; + return $error; + } + + + /** + * Form to Select type printer + * + * @param string $selected Id printer type pre-selected + * @param string $htmlname select html name + * @return int 0 if OK; >0 if KO + */ + public function selectTypePrinter($selected = '', $htmlname = 'printertypeid') + { + global $langs; + + $options = array( + 1 => $langs->trans('CONNECTOR_DUMMY'), + 2 => $langs->trans('CONNECTOR_FILE_PRINT'), + 3 => $langs->trans('CONNECTOR_NETWORK_PRINT'), + 4 => $langs->trans('CONNECTOR_WINDOWS_PRINT'), 5 => $langs->trans('CONNECTOR_CUPS_PRINT'), - ); - - $this->resprint = Form::selectarray($htmlname, $options, $selected); - - return 0; - } - - - /** - * Form to Select Profile printer - * - * @param string $selected Id printer profile pre-selected - * @param string $htmlname select html name - * @return int 0 if OK; >0 if KO - */ - public function selectProfilePrinter($selected = '', $htmlname = 'printerprofileid') - { - global $langs; - - $options = array( - 0 => $langs->trans('PROFILE_DEFAULT'), - 1 => $langs->trans('PROFILE_SIMPLE'), - 2 => $langs->trans('PROFILE_EPOSTEP'), - 3 => $langs->trans('PROFILE_P822D'), - 4 => $langs->trans('PROFILE_STAR'), - ); - - $this->profileresprint = Form::selectarray($htmlname, $options, $selected); - return 0; - } - - - /** - * Function to Add a printer in db - * - * @param string $name Printer name - * @param int $type Printer type - * @param int $profile Printer profile - * @param string $parameter Printer parameter - * @return int 0 if OK; >0 if KO - */ - public function addPrinter($name, $type, $profile, $parameter) - { - global $conf; - $error = 0; - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt'; - $sql .= ' (name, fk_type, fk_profile, parameter, entity)'; - $sql .= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')'; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = $this->db->lasterror; - } - return $error; - } - - /** - * Function to Update a printer in db - * - * @param string $name Printer name - * @param int $type Printer type - * @param int $profile Printer profile - * @param string $parameter Printer parameter - * @param int $printerid Printer id - * @return int 0 if OK; >0 if KO - */ - public function updatePrinter($name, $type, $profile, $parameter, $printerid) - { - global $conf; - $error = 0; - $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt'; - $sql .= ' SET name="'.$this->db->escape($name).'"'; - $sql .= ', fk_type='.$type; - $sql .= ', fk_profile='.$profile; - $sql .= ', parameter="'.$this->db->escape($parameter).'"'; - $sql .= ' WHERE rowid='.$printerid; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = $this->db->lasterror; - } - return $error; - } - - /** - * Function to Delete a printer from db - * - * @param int $printerid Printer id - * @return int 0 if OK; >0 if KO - */ - public function deletePrinter($printerid) - { - global $conf; - $error = 0; - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt'; - $sql .= ' WHERE rowid='.$printerid; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = $this->db->lasterror; - } - return $error; - } - - /** - * Function to add a printer template in db - * - * @param string $name Template name - * @param int $template Template - * @return int 0 if OK; >0 if KO - */ - public function addTemplate($name, $template) - { - global $conf; - $error = 0; - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql .= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"'; - $sql .= ', "'.$this->db->escape($template).'", '.$conf->entity.')'; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = $this->db->lasterror; - } - return $error; - } - - /** - * Function to delete a printer template in db - * - * @param int $templateid Template ID - * @return int 0 if OK; >0 if KO - */ - public function deleteTemplate($templateid) - { - global $conf; - $error = 0; - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql .= " WHERE rowid = ".((int) $this->db->escape($templateid)); - $sql .= " AND entity = ".$conf->entity; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = $this->db->lasterror; - } - return $error; - } - - /** - * Function to Update a printer template in db - * - * @param string $name Template name - * @param int $template Template - * @param int $templateid Template id - * @return int 0 if OK; >0 if KO - */ - public function updateTemplate($name, $template, $templateid) - { - global $conf; - $error = 0; - $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql .= ' SET name="'.$this->db->escape($name).'"'; - $sql .= ', template="'.$this->db->escape($template).'"'; - $sql .= ' WHERE rowid='.$templateid; - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->errors[] = $this->db->lasterror; - } - return $error; - } - - - /** - * Function to Send Test page to Printer - * - * @param int $printerid Printer id - * @return int 0 if OK; >0 if KO - */ - public function sendTestToPrinter($printerid) - { - global $conf; - $error = 0; - $img = EscposImage::load(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo_bw.png'); - //$this->profile = CapabilityProfile::load("TM-T88IV"); - $ret = $this->initPrinter($printerid); - if ($ret > 0) { - setEventMessages($this->error, $this->errors, 'errors'); - } else { - try { - $this->printer->bitImage($img); - $this->printer->text("Hello World!\n"); - $testStr = "1234567890"; - $this->printer->barcode($testStr); - //$this->printer->qrcode($testStr, Printer::QR_ECLEVEL_M, 5, Printer::QR_MODEL_1); - $this->printer->text("Most simple example\n"); - $this->printer->feed(); - $this->printer->cut(); + ); + + $this->resprint = Form::selectarray($htmlname, $options, $selected); + + return 0; + } + + + /** + * Form to Select Profile printer + * + * @param string $selected Id printer profile pre-selected + * @param string $htmlname select html name + * @return int 0 if OK; >0 if KO + */ + public function selectProfilePrinter($selected = '', $htmlname = 'printerprofileid') + { + global $langs; + + $options = array( + 0 => $langs->trans('PROFILE_DEFAULT'), + 1 => $langs->trans('PROFILE_SIMPLE'), + 2 => $langs->trans('PROFILE_EPOSTEP'), + 3 => $langs->trans('PROFILE_P822D'), + 4 => $langs->trans('PROFILE_STAR'), + ); + + $this->profileresprint = Form::selectarray($htmlname, $options, $selected); + return 0; + } + + + /** + * Function to Add a printer in db + * + * @param string $name Printer name + * @param int $type Printer type + * @param int $profile Printer profile + * @param string $parameter Printer parameter + * @return int 0 if OK; >0 if KO + */ + public function addPrinter($name, $type, $profile, $parameter) + { + global $conf; + $error = 0; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' (name, fk_type, fk_profile, parameter, entity)'; + $sql .= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')'; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = $this->db->lasterror; + } + return $error; + } + + /** + * Function to Update a printer in db + * + * @param string $name Printer name + * @param int $type Printer type + * @param int $profile Printer profile + * @param string $parameter Printer parameter + * @param int $printerid Printer id + * @return int 0 if OK; >0 if KO + */ + public function updatePrinter($name, $type, $profile, $parameter, $printerid) + { + global $conf; + $error = 0; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' SET name="'.$this->db->escape($name).'"'; + $sql .= ', fk_type='.$type; + $sql .= ', fk_profile='.$profile; + $sql .= ', parameter="'.$this->db->escape($parameter).'"'; + $sql .= ' WHERE rowid='.$printerid; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = $this->db->lasterror; + } + return $error; + } + + /** + * Function to Delete a printer from db + * + * @param int $printerid Printer id + * @return int 0 if OK; >0 if KO + */ + public function deletePrinter($printerid) + { + global $conf; + $error = 0; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' WHERE rowid='.$printerid; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = $this->db->lasterror; + } + return $error; + } + + /** + * Function to add a printer template in db + * + * @param string $name Template name + * @param int $template Template + * @return int 0 if OK; >0 if KO + */ + public function addTemplate($name, $template) + { + global $conf; + $error = 0; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt_template'; + $sql .= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"'; + $sql .= ', "'.$this->db->escape($template).'", '.$conf->entity.')'; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = $this->db->lasterror; + } + return $error; + } + + + /** + * Function to Update a printer template in db + * + * @param string $name Template name + * @param int $template Template + * @param int $templateid Template id + * @return int 0 if OK; >0 if KO + */ + public function updateTemplate($name, $template, $templateid) + { + global $conf; + $error = 0; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt_template'; + $sql .= ' SET name="'.$this->db->escape($name).'"'; + $sql .= ', template="'.$this->db->escape($template).'"'; + $sql .= ' WHERE rowid='.$templateid; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + $this->errors[] = $this->db->lasterror; + } + return $error; + } + + + /** + * Function to Send Test page to Printer + * + * @param int $printerid Printer id + * @return int 0 if OK; >0 if KO + */ + public function sendTestToPrinter($printerid) + { + global $conf; + $error = 0; + $img = EscposImage::load(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo_bw.png'); + //$this->profile = CapabilityProfile::load("TM-T88IV"); + $ret = $this->initPrinter($printerid); + if ($ret > 0) { + setEventMessages($this->error, $this->errors, 'errors'); + } else { + try { + $this->printer->bitImage($img); + $this->printer->text("Hello World!\n"); + $testStr = "1234567890"; + $this->printer->barcode($testStr); + //$this->printer->qrcode($testStr, Printer::QR_ECLEVEL_M, 5, Printer::QR_MODEL_1); + $this->printer->text("Most simple example\n"); + $this->printer->feed(); + $this->printer->cut(); // If is DummyPrintConnector send to log to debugging if ($this->printer->connector instanceof DummyPrintConnector) @@ -545,387 +526,343 @@ $data = $this->printer->connector-> getData(); dol_syslog($data); } - $this->printer->close(); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - } - return $error; - } - - /** - * Function to Print Receipt Ticket - * - * @param Facture|Commande $object Order or invoice object - * @param int $templateid Template id - * @param int $printerid Printer id - * @return int 0 if OK; >0 if KO - */ - public function sendToPrinter($object, $templateid, $printerid) - { - global $conf, $mysoc, $langs, $user; - $error = 0; - $ret = $this->loadTemplate($templateid); - - // tags a remplacer par leur valeur avant de parser (dol_value_xxx) - $this->template = str_replace('{dol_value_object_id}', $object->id, $this->template); - $this->template = str_replace('{dol_value_object_ref}', $object->ref, $this->template); - //$this->template = str_replace('', $object->points, $this->template); - $this->template = str_replace('{dol_value_date}', dol_print_date($object->date, 'day'), $this->template); - $this->template = str_replace('{dol_value_date_time}', dol_print_date($object->date, 'dayhour'), $this->template); - $this->template = str_replace('{dol_value_year}', dol_print_date($object->date, '%Y'), $this->template); - $this->template = str_replace('{dol_value_month_letters}', $langs->trans("Month".dol_print_date($object->date, '%m')), $this->template); - $this->template = str_replace('{dol_value_month}', dol_print_date($object->date, '%m'), $this->template); - $this->template = str_replace('{dol_value_day}', dol_print_date($object->date, '%d'), $this->template); - $this->template = str_replace('{dol_value_day_letters}', $langs->trans("Day".dol_print_date($object->date, '%m')[1]), $this->template); - - $this->template = str_replace('{dol_value_customer_firstname}', $object->thirdparty->firstname, $this->template); - $this->template = str_replace('{dol_value_customer_lastname}', $object->thirdparty->lastname, $this->template); - $this->template = str_replace('{dol_value_customer_mail}', $object->thirdparty->email, $this->template); - $this->template = str_replace('{dol_value_customer_phone}', $object->thirdparty->phone, $this->template); - //$this->template = str_replace('', $object->thirdparty->mobile, $this->template); - $this->template = str_replace('{dol_value_customer_tax_number}', $object->thirdparty->tva_intra, $this->template); - //$this->template = str_replace('', $object->customer_account_balance, $this->template); - //$this->template = str_replace('', $object->customer_points, $this->template); - - $this->template = str_replace('{dol_value_mysoc_name}', $mysoc->name, $this->template); - $this->template = str_replace('{dol_value_mysoc_address}', $mysoc->address, $this->template); - $this->template = str_replace('{dol_value_mysoc_zip}', $mysoc->zip, $this->template); - $this->template = str_replace('{dol_value_mysoc_town}', $mysoc->town, $this->template); - $this->template = str_replace('{dol_value_mysoc_country}', $mysoc->country, $this->template); - $this->template = str_replace('{dol_value_mysoc_idprof1}', $mysoc->idprof1, $this->template); - $this->template = str_replace('{dol_value_mysoc_idprof2}', $mysoc->idprof2, $this->template); - $this->template = str_replace('{dol_value_mysoc_idprof3}', $mysoc->idprof3, $this->template); - $this->template = str_replace('{dol_value_mysoc_idprof4}', $mysoc->idprof4, $this->template); - $this->template = str_replace('{dol_value_mysoc_idprof5}', $mysoc->idprof5, $this->template); - $this->template = str_replace('{dol_value_mysoc_idprof6}', $mysoc->idprof6, $this->template); - $this->template = str_replace('{dol_value_mysoc_tva_intra}', $mysoc->tva_intra, $this->template); - $this->template = str_replace('{dol_value_mysoc_capital}', $mysoc->capital, $this->template); - - $this->template = str_replace('{dol_value_vendor_firstname}', $user->firstname, $this->template); - $this->template = str_replace('{dol_value_vendor_lastname}', $user->lastname, $this->template); - $this->template = str_replace('{dol_value_vendor_mail}', $user->email, $this->template); - - // parse template - $this->template = str_replace("{", "<", $this->template); - $this->template = str_replace("}", ">", $this->template); - $p = xml_parser_create(); - xml_parse_into_struct($p, $this->template, $vals, $index); - xml_parser_free($p); - //print '
    '.print_r($index, true).'
    '; - //print '
    '.print_r($vals, true).'
    '; - // print ticket - $level = 0; - $nbcharactbyline = (!empty($conf->global->RECEIPT_PRINTER_NB_CHARACT_BY_LINE) ? $conf->global->RECEIPT_PRINTER_NB_CHARACT_BY_LINE : 48); - $ret = $this->initPrinter($printerid); - if ($ret > 0) { - setEventMessages($this->error, $this->errors, 'errors'); - } else { - $nboflines = count($vals); - for ($tplline = 0; $tplline < $nboflines; $tplline++) { - //var_dump($vals[$tplline]['value']); - switch ($vals[$tplline]['tag']) { - case 'DOL_PRINT_TEXT': - $this->printer->text($vals[$tplline]['value']); - break; - case 'DOL_PRINT_OBJECT_LINES': - foreach ($object->lines as $line) { - if ($line->fk_product) - { - $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); - $this->printer->text(strip_tags(htmlspecialchars_decode($line->product_label))."\n"); - } - else { - $spacestoadd = $nbcharactbyline - strlen($line->description) - strlen($line->qty) - 10 - 1; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($line->description.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); - } - } - break; - case 'DOL_PRINT_OBJECT_TAX': - //var_dump($object); - $vatarray = array(); - foreach ($object->lines as $line) { - $vatarray[$line->tva_tx] += $line->total_tva; - } - foreach ($vatarray as $vatkey => $vatvalue) { - $spacestoadd = $nbcharactbyline - strlen($vatkey) - 12; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($spaces.$vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n"); - } - break; - case 'DOL_PRINT_OBJECT_TAX1': - //var_dump($object); - $total_localtax1 = 0; - foreach ($object->lines as $line) { - $total_localtax1 += $line->total_localtax1; - } - foreach ($vatarray as $vatkey => $vatvalue) { - $this->printer->text(str_pad(price($total_localtax1), 10, ' ', STR_PAD_LEFT)."\n"); - } - break; - case 'DOL_PRINT_OBJECT_TAX2': - //var_dump($object); - $total_localtax2 = 0; - foreach ($object->lines as $line) { - $total_localtax2 += $line->total_localtax2; - } - foreach ($vatarray as $vatkey => $vatvalue) { - $this->printer->text(str_pad(price($total_localtax2), 10, ' ', STR_PAD_LEFT)."\n"); - } - break; - case 'DOL_PRINT_OBJECT_TOTAL': - $title = $langs->trans('TotalHT'); - $spacestoadd = $nbcharactbyline - strlen($title) - 10; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($title.$spaces.str_pad(price($object->total_ht), 10, ' ', STR_PAD_LEFT)."\n"); - $title = $langs->trans('TotalVAT'); - $spacestoadd = $nbcharactbyline - strlen($title) - 10; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($title.$spaces.str_pad(price($object->total_tva), 10, ' ', STR_PAD_LEFT)."\n"); - $title = $langs->trans('TotalTTC'); - $spacestoadd = $nbcharactbyline - strlen($title) - 10; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($title.$spaces.str_pad(price($object->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); - break; - case 'DOL_LINE_FEED': - $this->printer->feed(); - break; - case 'DOL_LINE_FEED_REVERSE': - $this->printer->feedReverse(); - break; - case 'DOL_ALIGN_CENTER': - $this->printer->setJustification(Printer::JUSTIFY_CENTER); - break; - case 'DOL_ALIGN_RIGHT': - $this->printer->setJustification(Printer::JUSTIFY_RIGHT); - break; - case 'DOL_ALIGN_LEFT': - $this->printer->setJustification(Printer::JUSTIFY_LEFT); - break; - case 'DOL_OPEN_DRAWER': - $this->printer->pulse(); - break; - case 'DOL_ACTIVATE_BUZZER': - //$this->printer->buzzer(); - break; - case 'DOL_PRINT_BARCODE': - // $vals[$tplline]['value'] -> barcode($content, $type) - // var_dump($vals[$tplline]['value']); - try { - $this->printer->barcode($vals[$tplline]['value']); - } catch (Exception $e) { - $this->errors[] = 'Invalid Barcode value: '.$vals[$tplline]['value']; - $error++; - } - break; - case 'DOL_PRINT_LOGO': - $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo); - $this->printer->graphics($img); - break; - case 'DOL_PRINT_LOGO_OLD': - $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo); - $this->printer->bitImage($img); - break; - case 'DOL_PRINT_QRCODE': - // $vals[$tplline]['value'] -> qrCode($content, $ec, $size, $model) - $this->printer->qrcode($vals[$tplline]['value']); - break; - case 'DOL_CUT_PAPER_FULL': - $this->printer->cut(Printer::CUT_FULL); - break; - case 'DOL_CUT_PAPER_PARTIAL': - $this->printer->cut(Printer::CUT_PARTIAL); - break; - case 'DOL_USE_FONT_A': - $this->printer->setFont(Printer::FONT_A); - break; - case 'DOL_USE_FONT_B': - $this->printer->setFont(Printer::FONT_B); - break; - case 'DOL_USE_FONT_C': - $this->printer->setFont(Printer::FONT_C); - break; + $this->printer->close(); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + } + return $error; + } + + /** + * Function to Print Receipt Ticket + * + * @param Facture|Commande $object Order or invoice object + * @param int $templateid Template id + * @param int $printerid Printer id + * @return int 0 if OK; >0 if KO + */ + public function sendToPrinter($object, $templateid, $printerid) + { + global $conf, $mysoc, $langs, $user; + $error = 0; + $ret = $this->loadTemplate($templateid); + + // tags a remplacer par leur valeur avant de parser (dol_value_xxx) + $this->template = str_replace('', $object->id, $this->template); + $this->template = str_replace('', $object->ref, $this->template); + $this->template = str_replace('', $object->points, $this->template); + $this->template = str_replace('', dol_print_date($object->date, 'day'), $this->template); + $this->template = str_replace('', dol_print_date($object->date, 'dayhour'), $this->template); + $this->template = str_replace('', dol_print_date($object->date, '%Y'), $this->template); + $this->template = str_replace('', $langs->trans("Month".dol_print_date($object->date, '%m')), $this->template); + $this->template = str_replace('', dol_print_date($object->date, '%m'), $this->template); + $this->template = str_replace('', dol_print_date($object->date, '%d'), $this->template); + $this->template = str_replace('', $langs->trans("Day".dol_print_date($object->date, '%m')[1]), $this->template); + + $this->template = str_replace('', $object->thirdparty->firstname, $this->template); + $this->template = str_replace('', $object->thirdparty->lastname, $this->template); + $this->template = str_replace('', $object->thirdparty->mail, $this->template); + $this->template = str_replace('', $object->thirdparty->phone, $this->template); + $this->template = str_replace('', $object->thirdparty->mobile, $this->template); + $this->template = str_replace('', $object->thirdparty->vatintra, $this->template); + $this->template = str_replace('', $object->customer_account_balance, $this->template); + $this->template = str_replace('', $object->customer_points, $this->template); + + $this->template = str_replace('', $mysoc->name, $this->template); + $this->template = str_replace('', $mysoc->address, $this->template); + $this->template = str_replace('', $mysoc->zip, $this->template); + $this->template = str_replace('', $mysoc->town, $this->template); + $this->template = str_replace('', $mysoc->country, $this->template); + $this->template = str_replace('', $mysoc->idprof1, $this->template); + $this->template = str_replace('', $mysoc->idprof2, $this->template); + $this->template = str_replace('', $mysoc->idprof3, $this->template); + $this->template = str_replace('', $mysoc->idprof4, $this->template); + $this->template = str_replace('', $mysoc->idprof5, $this->template); + $this->template = str_replace('', $mysoc->idprof6, $this->template); + $this->template = str_replace('', $mysoc->tva_intra, $this->template); + $this->template = str_replace('', $mysoc->capital, $this->template); + + $this->template = str_replace('', $user->firstname, $this->template); + $this->template = str_replace('', $user->lastname, $this->template); + $this->template = str_replace('', $user->email, $this->template); + + // parse template + $p = xml_parser_create(); + xml_parse_into_struct($p, $this->template, $vals, $index); + xml_parser_free($p); + //print '
    '.print_r($index, true).'
    '; + //print '
    '.print_r($vals, true).'
    '; + // print ticket + $level = 0; + $nbcharactbyline = (!empty($conf->global->RECEIPT_PRINTER_NB_CHARACT_BY_LINE) ? $conf->global->RECEIPT_PRINTER_NB_CHARACT_BY_LINE : 48); + $ret = $this->initPrinter($printerid); + if ($ret > 0) { + setEventMessages($this->error, $this->errors, 'errors'); + } else { + $nboflines = count($vals); + for ($tplline = 0; $tplline < $nboflines; $tplline++) { + //var_dump($vals[$tplline]['value']); + switch ($vals[$tplline]['tag']) { + case 'DOL_PRINT_TEXT': + $this->printer->text($vals[$tplline]['value']); + break; + case 'DOL_PRINT_OBJECT_LINES': + foreach ($object->lines as $line) { + //var_dump($line); + $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); + $this->printer->text(strip_tags(htmlspecialchars_decode($line->product_label))."\n"); + } + break; + case 'DOL_PRINT_OBJECT_TAX': + //var_dump($object); + $vatarray = array(); + foreach ($object->lines as $line) { + $vatarray[$line->tva_tx] += $line->total_tva; + } + foreach ($vatarray as $vatkey => $vatvalue) { + $spacestoadd = $nbcharactbyline - strlen($vatkey) - 12; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($spaces.$vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n"); + } + break; + case 'DOL_PRINT_OBJECT_TAX1': + //var_dump($object); + $total_localtax1 = 0; + foreach ($object->lines as $line) { + $total_localtax1 += $line->total_localtax1; + } + foreach ($vatarray as $vatkey => $vatvalue) { + $this->printer->text(str_pad(price($total_localtax1), 10, ' ', STR_PAD_LEFT)."\n"); + } + break; + case 'DOL_PRINT_OBJECT_TAX2': + //var_dump($object); + $total_localtax2 = 0; + foreach ($object->lines as $line) { + $total_localtax2 += $line->total_localtax2; + } + foreach ($vatarray as $vatkey => $vatvalue) { + $this->printer->text(str_pad(price($total_localtax2), 10, ' ', STR_PAD_LEFT)."\n"); + } + break; + case 'DOL_PRINT_OBJECT_TOTAL': + $title = $langs->trans('TotalHT'); + $spacestoadd = $nbcharactbyline - strlen($title) - 10; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($title.$spaces.str_pad(price($object->total_ht), 10, ' ', STR_PAD_LEFT)."\n"); + $title = $langs->trans('TotalVAT'); + $spacestoadd = $nbcharactbyline - strlen($title) - 10; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($title.$spaces.str_pad(price($object->total_tva), 10, ' ', STR_PAD_LEFT)."\n"); + $title = $langs->trans('TotalTTC'); + $spacestoadd = $nbcharactbyline - strlen($title) - 10; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($title.$spaces.str_pad(price($object->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); + break; + case 'DOL_LINE_FEED': + $this->printer->feed(); + break; + case 'DOL_LINE_FEED_REVERSE': + $this->printer->feedReverse(); + break; + case 'DOL_ALIGN_CENTER': + $this->printer->setJustification(Printer::JUSTIFY_CENTER); + break; + case 'DOL_ALIGN_RIGHT': + $this->printer->setJustification(Printer::JUSTIFY_RIGHT); + break; + case 'DOL_ALIGN_LEFT': + $this->printer->setJustification(Printer::JUSTIFY_LEFT); + break; + case 'DOL_OPEN_DRAWER': + $this->printer->pulse(); + break; + case 'DOL_ACTIVATE_BUZZER': + //$this->printer->buzzer(); + break; + case 'DOL_PRINT_BARCODE': + // $vals[$tplline]['value'] -> barcode($content, $type) + // var_dump($vals[$tplline]['value']); + try { + $this->printer->barcode($vals[$tplline]['value']); + } catch (Exception $e) { + $this->errors[] = 'Invalid Barcode value: '.$vals[$tplline]['value']; + $error++; + } + break; + case 'DOL_PRINT_LOGO': + $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo); + $this->printer->graphics($img); + break; + case 'DOL_PRINT_LOGO_OLD': + $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo); + $this->printer->bitImage($img); + break; + case 'DOL_PRINT_QRCODE': + // $vals[$tplline]['value'] -> qrCode($content, $ec, $size, $model) + $this->printer->qrcode($vals[$tplline]['value']); + break; + case 'DOL_CUT_PAPER_FULL': + $this->printer->cut(Printer::CUT_FULL); + break; + case 'DOL_CUT_PAPER_PARTIAL': + $this->printer->cut(Printer::CUT_PARTIAL); + break; + case 'DOL_USE_FONT_A': + $this->printer->setFont(Printer::FONT_A); + break; + case 'DOL_USE_FONT_B': + $this->printer->setFont(Printer::FONT_B); + break; + case 'DOL_USE_FONT_C': + $this->printer->setFont(Printer::FONT_C); + break; case 'DOL_BOLD': - $this->printer->setEmphasis(true); - break; + $this->printer->setEmphasis(true); + break; case 'DOL_BOLD_DISABLED': - $this->printer->setEmphasis(false); - break; + $this->printer->setEmphasis(false); + break; case 'DOL_DOUBLE_HEIGHT': - $this->printer->setTextSize(1, 2); - break; + $this->printer->setTextSize(1, 2); + break; case 'DOL_DOUBLE_WIDTH': - $this->printer->setTextSize(2, 1); - break; + $this->printer->setTextSize(2, 1); + break; case 'DOL_DEFAULT_HEIGHT_WIDTH': - $this->printer->setTextSize(1, 1); - break; + $this->printer->setTextSize(1, 1); + break; case 'DOL_UNDERLINE': - $this->printer->setUnderline(true); - break; + $this->printer->setUnderline(true); + break; case 'DOL_UNDERLINE_DISABLED': - $this->printer->setUnderline(false); - break; + $this->printer->setUnderline(false); + break; case 'DOL_BEEP': - $this->printer->getPrintConnector() -> write("\x1e"); - break; + $this->printer->getPrintConnector() -> write("\x1e"); + break; case 'DOL_PRINT_ORDER_LINES': foreach ($object->lines as $line) { if ($line->special_code == $this->orderprinter) { $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); + $spaces = str_repeat(' ', $spacestoadd); $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); $this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n"); } - } + } break; - case 'DOL_PRINT_PAYMENT': - $sql = "SELECT p.pos_change as pos_change, p.datep as date, p.fk_paiement, p.num_paiement as num, pf.amount as amount, pf.multicurrency_amount,"; - $sql .= " cp.code"; - $sql .= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id"; - $sql .= " WHERE pf.fk_paiement = p.rowid AND pf.fk_facture = ".$object->id; - $sql .= " ORDER BY p.datep"; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) { - $row = $this->db->fetch_object($resql); - $spacestoadd = $nbcharactbyline - strlen($langs->transnoentitiesnoconv("PaymentTypeShort".$row->code)) - 12; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $amount_payment = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) ? $row->multicurrency_amount : $row->amount; - if ($row->code == "LIQ") $amount_payment = $amount_payment + $row->pos_change; // Show amount with excess received if is cash payment - $this->printer->text($spaces.$langs->transnoentitiesnoconv("PaymentTypeShort".$row->code).' '.str_pad(price($amount_payment), 10, ' ', STR_PAD_LEFT)."\n"); - if ($row->code == "LIQ" && $row->pos_change > 0) // Print change only in cash payments - { - $spacestoadd = $nbcharactbyline - strlen($langs->trans("Change")) - 12; - $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); - $this->printer->text($spaces.$langs->trans("Change").' '.str_pad(price($row->pos_change), 10, ' ', STR_PAD_LEFT)."\n"); - } - $i++; - } - } - break; - default: - $this->printer->text($vals[$tplline]['tag']); - $this->printer->text($vals[$tplline]['value']); - $this->errors[] = 'UnknowTag: <'.strtolower($vals[$tplline]['tag']).'>'; - $error++; - break; - } - } - // If is DummyPrintConnector send to log to debugging - if ($this->printer->connector instanceof DummyPrintConnector || $conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") + default: + $this->printer->text($vals[$tplline]['tag']); + $this->printer->text($vals[$tplline]['value']); + $this->errors[] = 'UnknowTag: <'.strtolower($vals[$tplline]['tag']).'>'; + $error++; + break; + } + } + // If is DummyPrintConnector send to log to debugging + if ($this->printer->connector instanceof DummyPrintConnector) { $data = $this->printer->connector->getData(); - if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") echo base64_encode($data); dol_syslog($data); } // Close and print - $this->printer->close(); - } - return $error; - } - - /** - * Function to load Template - * - * @param int $templateid Template id - * @return int 0 if OK; >0 if KO - */ - public function loadTemplate($templateid) - { - global $conf; - $error = 0; - $sql = 'SELECT template'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql .= ' WHERE rowid='.$templateid; - $sql .= ' AND entity = '.$conf->entity; - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_array($resql); - } else { - $error++; - $this->errors[] = $this->db->lasterror; - } - if (empty($obj)) { - $error++; - $this->errors[] = 'TemplateDontExist'; - } else { - $this->template = $obj['0']; - } - - return $error; - } - - - /** - * Function Init Printer - * - * @param int $printerid Printer id - * @return int 0 if OK; >0 if KO - */ - public function initPrinter($printerid) - { - global $conf; - if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { - $this->connector = new DummyPrintConnector(); - $this->printer = new Printer($this->connector, $this->profile); - return; - } - $error = 0; - $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; - $sql .= ' WHERE rowid = '.$printerid; - $sql .= ' AND entity = '.$conf->entity; - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_array($resql); - } else { - $error++; - $this->errors[] = $this->db->lasterror; - } - if (empty($obj)) { - $error++; - $this->errors[] = 'PrinterDontExist'; - } - if (!$error) { - $parameter = $obj['parameter']; - try { - switch ($obj['fk_type']) { - case 1: - $this->connector = new DummyPrintConnector(); - break; - case 2: - $this->connector = new FilePrintConnector($parameter); - break; - case 3: - $parameters = explode(':', $parameter); - $this->connector = new NetworkPrintConnector($parameters[0], $parameters[1]); - break; - case 4: - $this->connector = new WindowsPrintConnector($parameter); - break; + $this->printer->close(); + } + return $error; + } + + /** + * Function to load Template + * + * @param int $templateid Template id + * @return int 0 if OK; >0 if KO + */ + public function loadTemplate($templateid) + { + global $conf; + $error = 0; + $sql = 'SELECT template'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; + $sql .= ' WHERE rowid='.$templateid; + $sql .= ' AND entity = '.$conf->entity; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_array($resql); + } else { + $error++; + $this->errors[] = $this->db->lasterror; + } + if (empty($obj)) { + $error++; + $this->errors[] = 'TemplateDontExist'; + } else { + $this->template = $obj['0']; + } + + return $error; + } + + + /** + * Function Init Printer + * + * @param int $printerid Printer id + * @return int 0 if OK; >0 if KO + */ + public function initPrinter($printerid) + { + global $conf; + $error = 0; + $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' WHERE rowid = '.$printerid; + $sql .= ' AND entity = '.$conf->entity; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_array($resql); + } else { + $error++; + $this->errors[] = $this->db->lasterror; + } + if (empty($obj)) { + $error++; + $this->errors[] = 'PrinterDontExist'; + } + if (!$error) { + $parameter = $obj['parameter']; + try { + switch ($obj['fk_type']) { + case 1: + $this->connector = new DummyPrintConnector(); + break; + case 2: + $this->connector = new FilePrintConnector($parameter); + break; + case 3: + $parameters = explode(':', $parameter); + $this->connector = new NetworkPrintConnector($parameters[0], $parameters[1]); + break; + case 4: + $this->connector = new WindowsPrintConnector($parameter); + break; case 5: - $this->connector = new CupsPrintConnector($parameter); - break; - default: - $this->connector = 'CONNECTOR_UNKNOWN'; - break; - } - $this->printer = new Printer($this->connector, $this->profile); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - } - return $error; - } + $this->connector = new CupsPrintConnector($parameter); + break; + default: + $this->connector = 'CONNECTOR_UNKNOWN'; + break; + } + $this->printer = new Printer($this->connector, $this->profile); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + } + return $error; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_emailsenderprofile.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_emailsenderprofile.class.php @@ -95,12 +95,13 @@ 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>1), 'email' => array('type'=>'varchar(255)', 'label'=>'Email', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1), + //'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), 'private' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'User', 'visible'=>-1, 'enabled'=>1, 'position'=>50, 'default'=>'0', 'notnull'=>1), 'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>3, 'enabled'=>1, 'position'=>400, 'notnull'=>-1, 'index'=>1,), 'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>1, 'enabled'=>1, 'position'=>405, 'notnull'=>-1, 'index'=>1,), 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), - 'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'default'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array(0=>'Disabled', 1=>'Enabled')), + 'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'default'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1, 'arrayofkeyval'=>array(0=>'Disabled', 1=>'Enabled')), ); /** @@ -114,23 +115,51 @@ public $entity; /** - * @var string Email Sender Profile label - */ - public $label; + * @var string Email Sender Profile label + */ + public $label; public $email; /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; + public $tms; - public $private; + //public $fk_user_creat; + //public $fk_user_modif; public $signature; public $position; public $active; // END MODULEBUILDER PROPERTIES + + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'emailsenderprofiledet'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + //public $fk_element = 'fk_emailsenderprofile'; + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'EmailSenderProfileline'; + /** + * @var array List of child tables. To test if we can delete object. + */ + //protected $childtables=array(); + /** + * @var EmailSenderProfileLine[] Array of subtable lines + */ + //public $lines = array(); + /** @@ -278,9 +307,9 @@ $result = ''; $companylink = ''; - $label = $this->label; - - $url = ''; + $label = $this->label; + + $url = ''; //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id; $linkstart = ''; @@ -302,10 +331,10 @@ */ public function getLibStatut($mode = 0) { - return $this->LibStatut($this->active, $mode); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return the status * @@ -317,20 +346,40 @@ { global $langs; - if ($status == 1) { - $label = $labelshort = $langs->trans('Enabled'); - } else { - $label = $labelshort = $langs->trans('Disabled'); - } - - $statusType = 'status'.$status; - if ($status == self::STATUS_ENABLED) $statusType = 'status4'; - - return dolGetStatus($label, $labelshort, '', $statusType, $mode); - } - - /** - * Charge les informations d'ordre info dans l'objet commande + if ($mode == 0 || $mode == 1) + { + if ($status == 1) return $langs->trans('Enabled'); + elseif ($status == 0) return $langs->trans('Disabled'); + } + elseif ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); + elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); + } + elseif ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4'); + elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5'); + } + elseif ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); + elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); + } + elseif ($mode == 5) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); + elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + } + elseif ($mode == 6) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); + elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); + } + } + + /** + * Charge les informations d'ordre info dans l'objet commande * * @param int $id Id of order * @return void @@ -375,7 +424,9 @@ } $this->db->free($result); - } else { + } + else + { dol_print_error($this->db); } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_evalmath.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_evalmath.class.php @@ -149,8 +149,8 @@ $expr = trim($expr); if (substr($expr, - 1, 1) == ';') $expr = substr($expr, 0, strlen($expr) - 1); // strip semicolons at the end - // =============== - // is it a variable assignment? + // =============== + // is it a variable assignment? $matches = array(); if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) { if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant @@ -160,8 +160,8 @@ return false; // get the result and make sure it's good $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array return $this->v[$matches[1]]; // and return the resulting value - // =============== - // is it a function assignment? + // =============== + // is it a function assignment? } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) { $fnn = $matches[1]; // get the function name if (in_array($matches[1], $this->fb)) { // make sure it isn't built in @@ -235,7 +235,7 @@ $ops_p = array('+' => 0, '-' => 0, '*' => 1, '/' => 1, '_' => 1, '^' => 2); // operator precedence $expecting_op = false; // we use this in syntax-checking the expression - // and determining when a - is a negation + // and determining when a - is a negation $matches = array(); if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good @@ -244,7 +244,7 @@ while (1) { // 1 Infinite Loop ;) $op = substr($expr, $index, 1); // get the first character at the current index - // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand + // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand $match = array(); $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match); // =============== @@ -253,7 +253,7 @@ $index++; } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack return $this->trigger(4, "illegal character '_'", "_"); // but not in the input expression - // =============== + // =============== } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack? if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis? $op = '*'; @@ -372,7 +372,7 @@ $stack = new EvalMathStack(); foreach ($tokens as $token) { // nice and easy - // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on + // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on $matches = array(); if (in_array($token, array('+', '-', '*', '/', '^'))) { if (is_null($op2 = $stack->pop())) @@ -412,7 +412,7 @@ $fnn = 'log'; eval('$stack->push('.$fnn.'($op1));'); // perfectly safe eval() } elseif (array_key_exists($fnn, $this->f)) { // user function - // get args + // get args $args = array(); for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i--) { if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) --- /tmp/dsg/dolibarr/htdocs/core/class/github_events.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_events.class.php @@ -43,10 +43,10 @@ */ public $id; - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -58,7 +58,7 @@ */ public $tms; - /** + /** * @var string Type */ public $type; @@ -94,7 +94,7 @@ public $eventstolog = array( array('id'=>'USER_LOGIN', 'test'=>1), array('id'=>'USER_LOGIN_FAILED', 'test'=>1), - array('id'=>'USER_LOGOUT', 'test'=>1), + array('id'=>'USER_LOGOUT', 'test'=>1), array('id'=>'USER_CREATE', 'test'=>1), array('id'=>'USER_MODIFY', 'test'=>1), array('id'=>'USER_NEW_PASSWORD', 'test'=>1), @@ -141,7 +141,7 @@ // Clean parameters $this->description = trim($this->description); - if (empty($this->user_agent)) $this->user_agent = (empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT']); + if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent = $_SERVER['HTTP_USER_AGENT']; // Check parameters if (empty($this->description)) { $this->error = 'ErrorBadValueForParameterCreateEventDesc'; return -1; } @@ -173,7 +173,9 @@ { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."events"); return $this->id; - } else { + } + else + { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -187,7 +189,7 @@ * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - public function update($user = null, $notrigger = 0) + public function update($user = null, $notrigger = 0) { // Clean parameters $this->id = (int) $this->id; @@ -222,7 +224,7 @@ * @param User $user User that load * @return int <0 if KO, >0 if OK */ - public function fetch($id, $user = null) + public function fetch($id, $user = null) { $sql = "SELECT"; $sql .= " t.rowid,"; @@ -258,7 +260,9 @@ $this->db->free($resql); return 1; - } else { + } + else + { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -271,7 +275,7 @@ * @param User $user User that delete * @return int <0 if KO, >0 if OK */ - public function delete($user) + public function delete($user) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."events"; $sql .= " WHERE rowid=".$this->id; @@ -289,13 +293,13 @@ /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - public function initAsSpecimen() + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + public function initAsSpecimen() { $this->id = 0; @@ -306,5 +310,5 @@ $this->ip = '1.2.3.4'; $this->user_agent = 'Mozilla specimen User Agent X.Y'; $this->prefix_session = dol_getprefix(); - } + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_extrafields.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_extrafields.class.php @@ -38,116 +38,103 @@ class ExtraFields { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** - * @var array Array with type of element (for what object is the extrafield) + * @var array Array with type of element (for what object is the extrafield) * @deprecated - */ - public $attribute_elementtype; + */ + public $attribute_elementtype; + + /** + * @var array Array with type of the extra field + * @deprecated + */ + public $attribute_type; + + /** + * @var array Array with label of extra field + * @deprecated + */ + public $attribute_label; + + /** + * @var array Array with size of extra field + * @deprecated + */ + public $attribute_size; + + /** + * @var array Array with list of possible values for some types of extra fields + * @deprecated + */ + public $attribute_choice; + + /** + * @var array Array to store compute formula for computed fields + * @deprecated + */ + public $attribute_computed; + + /** + * @var array Array to store default value + * @deprecated + */ + public $attribute_default; + + /** + * @var array Array to store if attribute is unique or not + * @deprecated + */ + public $attribute_unique; + + /** + * @var array Array to store if attribute is required or not + * @deprecated + */ + public $attribute_required; + + /** + * @var array Array to store parameters of attribute (used in select type) + * @deprecated + */ + public $attribute_param; + + /** + * @var array Array to store position of attribute + * @deprecated + */ + public $attribute_pos; + + /** + * @var array Array to store if attribute is editable regardless of the document status + * @deprecated + */ + public $attribute_alwayseditable; + + /** + * @var array Array to store permission to check + * @deprecated + */ + public $attribute_perms; + + /** + * @var array Array to store language file to translate label of values + * @deprecated + */ + public $attribute_langfile; + + /** + * @var array Array to store if field is visible by default on list + * @deprecated + */ + public $attribute_list; /** - * @var array Array with type of the extra field - * @deprecated - */ - public $attribute_type; - - /** - * @var array Array with label of extra field - * @deprecated - */ - public $attribute_label; - - /** - * @var array Array with size of extra field - * @deprecated - */ - public $attribute_size; - - /** - * @var array Array with list of possible values for some types of extra fields - * @deprecated - */ - public $attribute_choice; - - /** - * @var array Array to store compute formula for computed fields - * @deprecated - */ - public $attribute_computed; - - /** - * @var array Array to store default value - * @deprecated - */ - public $attribute_default; - - /** - * @var array Array to store if attribute is unique or not - * @deprecated - */ - public $attribute_unique; - - /** - * @var array Array to store if attribute is required or not - * @deprecated - */ - public $attribute_required; - - /** - * @var array Array to store parameters of attribute (used in select type) - * @deprecated - */ - public $attribute_param; - - /** - * @var array Array to store position of attribute - * @deprecated - */ - public $attribute_pos; - - /** - * @var array Array to store if attribute is editable regardless of the document status - * @deprecated - */ - public $attribute_alwayseditable; - - /** - * @var array Array to store permission to check - * @deprecated - */ - public $attribute_perms; - - /** - * @var array Array to store language file to translate label of values - * @deprecated - */ - public $attribute_langfile; - - /** - * @var array Array to store if field is visible by default on list - * @deprecated - */ - public $attribute_list; - - /** - * @var array Array to store if field is summable - * @deprecated - */ - public $attribute_totalizable; - - /** - * @var array Array to store entity id of extrafield - * @deprecated - */ - public $attribute_entityid; - - - /** - * @var array New array to store extrafields definition - */ + * @var array New array to store extrafields definition + */ public $attributes; /** @@ -160,33 +147,33 @@ */ public $errors = array(); - /** + /** * @var string DB Error number */ public $errno; public static $type2label = array( - 'varchar'=>'String1Line', - 'text'=>'TextLongNLines', - 'html'=>'HtmlText', - 'int'=>'Int', - 'double'=>'Float', - 'date'=>'Date', - 'datetime'=>'DateAndTime', - 'boolean'=>'Boolean', - 'price'=>'ExtrafieldPrice', - 'phone'=>'ExtrafieldPhone', - 'mail'=>'ExtrafieldMail', - 'url'=>'ExtrafieldUrl', - 'password' => 'ExtrafieldPassword', - 'select' => 'ExtrafieldSelect', - 'sellist' => 'ExtrafieldSelectList', - 'radio' => 'ExtrafieldRadio', - 'checkbox' => 'ExtrafieldCheckBox', - 'chkbxlst' => 'ExtrafieldCheckBoxFromList', - 'link' => 'ExtrafieldLink', - 'separate' => 'ExtrafieldSeparator', + 'varchar'=>'String', + 'text'=>'TextLong', + 'html'=>'HtmlText', + 'int'=>'Int', + 'double'=>'Float', + 'date'=>'Date', + 'datetime'=>'DateAndTime', + 'boolean'=>'Boolean', + 'price'=>'ExtrafieldPrice', + 'phone'=>'ExtrafieldPhone', + 'mail'=>'ExtrafieldMail', + 'url'=>'ExtrafieldUrl', + 'password' => 'ExtrafieldPassword', + 'select' => 'ExtrafieldSelect', + 'sellist' => 'ExtrafieldSelectList', + 'radio' => 'ExtrafieldRadio', + 'checkbox' => 'ExtrafieldCheckBox', + 'chkbxlst' => 'ExtrafieldCheckBoxFromList', + 'link' => 'ExtrafieldLink', + 'separate' => 'ExtrafieldSeparator', ); @@ -194,7 +181,7 @@ * Constructor * * @param DoliDB $db Database handler - */ + */ public function __construct($db) { $this->db = $db; @@ -238,7 +225,7 @@ * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is a measure. Must show a total on lists - * @param int $printable Is extrafield displayed on PDF + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK */ public function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique = 0, $required = 0, $default_value = '', $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) @@ -266,8 +253,11 @@ $this->error = ''; $this->errno = 0; return 1; - } else return -2; - } else { + } + else return -2; + } + else + { return -1; } } @@ -348,17 +338,21 @@ $resql = $this->db->query($sql, 1, 'dml'); } return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->errno = $this->db->lasterrno(); return -1; } - } else { + } + else + { return 0; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add description of a new optional attribute * @@ -381,13 +375,13 @@ * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is a measure. Must show a total on lists - * @param int $printable Is extrafield displayed on PDF + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK - * @throws Exception + * @throws Exception */ private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user; if ($elementtype == 'thirdparty') $elementtype = 'societe'; @@ -407,10 +401,13 @@ if (is_array($param) && count($param) > 0) { $params = serialize($param); - } elseif (strlen($param) > 0) + } + elseif (strlen($param) > 0) { $params = trim($param); - } else { + } + else + { $params = ''; } @@ -439,7 +436,7 @@ $sql .= " help,"; $sql .= " totalizable"; $sql .= " )"; - $sql .= " VALUES('".$this->db->escape($attrname)."',"; + $sql .= " VALUES('".$attrname."',"; $sql .= " '".$this->db->escape($label)."',"; $sql .= " '".$this->db->escape($type)."',"; $sql .= " ".$pos.","; @@ -468,7 +465,9 @@ if ($this->db->query($sql)) { return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->errno = $this->db->lasterrno(); return -1; @@ -498,42 +497,44 @@ $result = $this->delete_label($attrname, $elementtype); if ($result < 0) { - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); - $error++; + $error++; } if (!$error) { - $sql = "SELECT COUNT(rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; - $sql .= " WHERE elementtype = '".$this->db->escape($elementtype)."'"; - $sql .= " AND name = '".$this->db->escape($attrname)."'"; - //$sql.= " AND entity IN (0,".$conf->entity.")"; Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj->nb <= 0) - { - $result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key - if ($result < 0) - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $error++; - } - } - } + $sql = "SELECT COUNT(rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; + $sql .= " WHERE elementtype = '".$elementtype."'"; + $sql .= " AND name = '".$attrname."'"; + //$sql.= " AND entity IN (0,".$conf->entity.")"; Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb <= 0) + { + $result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key + if ($result < 0) + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $error++; + } + } + } } return $result; - } else { + } + else + { return 0; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete description of an optional attribute * @@ -543,7 +544,7 @@ */ private function delete_label($attrname, $elementtype = 'member') { - // phpcs:enable + // phpcs:enable global $conf; if ($elementtype == 'thirdparty') $elementtype = 'societe'; @@ -552,20 +553,24 @@ if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; - $sql .= " WHERE name = '".$this->db->escape($attrname)."'"; + $sql .= " WHERE name = '".$attrname."'"; $sql .= " AND entity IN (0,".$conf->entity.')'; - $sql .= " AND elementtype = '".$this->db->escape($elementtype)."'"; + $sql .= " AND elementtype = '".$elementtype."'"; dol_syslog(get_class($this)."::delete_label", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { return 1; - } else { + } + else + { dol_print_error($this->db); return -1; } - } else { + } + else + { return 0; } } @@ -591,17 +596,17 @@ * @param string $entity Entity of extrafields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not - * @param int $totalizable Is extrafield totalizable on list - * @param int $printable Is extrafield displayed on PDF + * @param int $totalizable Is extrafield totalizable on list + * @param int $printable Is extrafield displayed on PDF * @return int >0 if OK, <=0 if KO - * @throws Exception + * @throws Exception */ public function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { if ($elementtype == 'thirdparty') $elementtype = 'societe'; if ($elementtype == 'contact') $elementtype = 'socpeople'; - $table = $elementtype.'_extrafields'; + $table = $elementtype.'_extrafields'; if ($elementtype == 'categorie') $table = 'categories_extrafields'; if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) @@ -654,26 +659,34 @@ if ($unique) { $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")"; - } else { + } + else + { $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname; } dol_syslog(get_class($this).'::update', LOG_DEBUG); $resql = $this->db->query($sql, 1, 'dml'); return 1; - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } - } else { + } + else + { $this->error = $this->db->lasterror(); return -1; } - } else { + } + else + { return 0; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Modify description of personalized attribute * @@ -695,14 +708,14 @@ * @param string $entity Entity of extrafields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not - * @param int $totalizable Is extrafield totalizable on list - * @param int $printable Is extrafield displayed on PDF - * @return int <=0 if KO, >0 if OK - * @throws Exception + * @param int $totalizable Is extrafield totalizable on list + * @param int $printable Is extrafield displayed on PDF + * @return int <=0 if KO, >0 if OK + * @throws Exception */ private function update_label($attrname, $label, $type, $size, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '0', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user; dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable.", ".$printable); @@ -712,9 +725,9 @@ if (empty($pos)) $pos = 0; if (empty($list)) $list = '0'; - if (empty($totalizable)) { - $totalizable = 0; - } + if (empty($totalizable)) { + $totalizable = 0; + } if (empty($required)) $required = 0; if (empty($unique)) $unique = 0; if (empty($alwayseditable)) $alwayseditable = 0; @@ -726,10 +739,13 @@ if (is_array($param) && count($param) > 0) { $params = serialize($param); - } elseif (strlen($param) > 0) + } + elseif (strlen($param) > 0) { $params = trim($param); - } else { + } + else + { $params = ''; } @@ -737,15 +753,17 @@ { // We dont want on all entities, we delete all and current $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; - $sql_del .= " WHERE name = '".$this->db->escape($attrname)."'"; + $sql_del .= " WHERE name = '".$attrname."'"; $sql_del .= " AND entity IN (0, ".($entity === '' ? $conf->entity : $entity).")"; - $sql_del .= " AND elementtype = '".$this->db->escape($elementtype)."'"; - } else { + $sql_del .= " AND elementtype = '".$elementtype."'"; + } + else + { // We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity) $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; - $sql_del .= " WHERE name = '".$this->db->escape($attrname)."'"; + $sql_del .= " WHERE name = '".$attrname."'"; $sql_del .= " AND entity = 0"; - $sql_del .= " AND elementtype = '".$this->db->escape($elementtype)."'"; + $sql_del .= " AND elementtype = '".$elementtype."'"; } $resql1 = $this->db->query($sql_del); @@ -765,7 +783,7 @@ $sql .= " param,"; $sql .= " list,"; $sql .= " printable,"; - $sql .= " totalizable,"; + $sql .= " totalizable,"; $sql .= " fielddefault,"; $sql .= " fieldcomputed,"; $sql .= " fk_user_author,"; @@ -774,7 +792,7 @@ $sql .= " enabled,"; $sql .= " help"; $sql .= ") VALUES ("; - $sql .= "'".$this->db->escape($attrname)."',"; + $sql .= "'".$attrname."',"; $sql .= " ".($entity === '' ? $conf->entity : $entity).","; $sql .= " '".$this->db->escape($label)."',"; $sql .= " '".$this->db->escape($type)."',"; @@ -789,7 +807,7 @@ $sql .= " '".$this->db->escape($params)."',"; $sql .= " '".$this->db->escape($list)."', "; $sql .= " '".$this->db->escape($printable)."', "; - $sql .= " ".($totalizable ? 'TRUE' : 'FALSE').","; + $sql .= " ".($totalizable ? 'TRUE' : 'FALSE').","; $sql .= " ".(($default != '') ? "'".$this->db->escape($default)."'" : "null").","; $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").","; $sql .= " ".$user->id.","; @@ -805,28 +823,32 @@ { $this->db->commit(); return 1; - } else { + } + else + { $this->db->rollback(); dol_print_error($this->db); return -1; } - } else { + } + else + { return 0; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load array this->attributes, or old this->attribute_xxx like attribute_label, attribute_type, ... * - * @param string $elementtype Type of element ('' = all or $object->table_element like 'adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...). + * @param string $elementtype Type of element ('' = all, 'adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...). * @param boolean $forceload Force load of extra fields whatever is status of cache. * @return array Array of attributes keys+label for all extra fields. */ public function fetch_name_optionals_label($elementtype, $forceload = false) { - // phpcs:enable + // phpcs:enable global $conf; if (empty($elementtype)) return array(); @@ -834,15 +856,14 @@ if ($elementtype == 'thirdparty') $elementtype = 'societe'; if ($elementtype == 'contact') $elementtype = 'socpeople'; if ($elementtype == 'order_supplier') $elementtype = 'commande_fournisseur'; - if ($elementtype == 'stock_mouvement') $elementtype = 'movement'; $array_name_label = array(); // We should not have several time this request. If we have, there is some optimization to do by calling a simple $extrafields->fetch_optionals() in top of code and not into subcode - $sql = "SELECT rowid, name, label, type, size, elementtype, fieldunique, fieldrequired, param, pos, alwayseditable, perms, langs, list, printable, totalizable, fielddefault, fieldcomputed, entity, enabled, help"; + $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,printable,totalizable,fielddefault,fieldcomputed,entity,enabled,help"; $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; //$sql.= " WHERE entity IN (0,".$conf->entity.")"; // Filter is done later - if ($elementtype) $sql .= " WHERE elementtype = '".$this->db->escape($elementtype)."'"; // Filed with object->table_element + if ($elementtype) $sql .= " WHERE elementtype = '".$elementtype."'"; // Filed with object->table_element $sql .= " ORDER BY pos"; $resql = $this->db->query($sql); @@ -852,15 +873,15 @@ { while ($tab = $this->db->fetch_object($resql)) { - if ($tab->entity != 0 && $tab->entity != $conf->entity) - { - // This field is not in current entity. We discard but before we save it into the array of mandatory fields if it is a mandatory field without default value - if ($tab->fieldrequired && is_null($tab->fielddefault)) - { - $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name] = $tab->type; - } - continue; - } + if ($tab->entity != 0 && $tab->entity != $conf->entity) + { + // This field is not in current entity. We discard but before we save it into the array of mandatory fields if it is a mandatory field without default value + if ($tab->fieldrequired && is_null($tab->fielddefault)) + { + $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name] = $tab->type; + } + continue; + } // We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label'] if ($tab->type != 'separate') @@ -902,7 +923,7 @@ $this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs; $this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list; $this->attributes[$tab->elementtype]['printable'][$tab->name] = $tab->printable; - $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = ($tab->totalizable ? 1 : 0); + $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = ($tab->totalizable ? 1 : 0); $this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity; $this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled; $this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help; @@ -911,7 +932,9 @@ } } if ($elementtype) $this->attributes[$elementtype]['loaded'] = 1; // If nothing found, we also save tag 'loaded' - } else { + } + else + { $this->error = $this->db->lasterror(); dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR); } @@ -968,7 +991,8 @@ $totalizable = $this->attributes[$extrafieldsobjectkey]['totalizable'][$key]; $help = $this->attributes[$extrafieldsobjectkey]['help'][$key]; $hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) - } else // Old usage + } + else // Old usage { $label = $this->attribute_label[$key]; $type = $this->attribute_type[$key]; @@ -991,82 +1015,103 @@ else return ''; } - if (empty($morecss)) { - if ($type == 'date') { + if (empty($morecss)) + { + if ($type == 'date') + { $morecss = 'minwidth100imp'; - } elseif ($type == 'datetime' || $type == 'link') { + } + elseif ($type == 'datetime' || $type == 'link') + { $morecss = 'minwidth200imp'; - } elseif (in_array($type, array('int', 'integer', 'double', 'price'))) { + } + elseif (in_array($type, array('int', 'integer', 'double', 'price'))) + { $morecss = 'maxwidth75'; - } elseif ($type == 'password') { + } + elseif ($type == 'password') + { $morecss = 'maxwidth100'; - } elseif ($type == 'url') { + } + elseif ($type == 'url') + { $morecss = 'minwidth400'; - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { $morecss = ''; - } else { - if (empty($size) || round($size) < 12) { + } + else + { + if (round($size) < 12) + { $morecss = 'minwidth100'; - } elseif (round($size) <= 48) { + } + elseif (round($size) <= 48) + { $morecss = 'minwidth200'; - } else { + } + else + { $morecss = 'minwidth400'; } } } - if (in_array($type, array('date'))) { + if (in_array($type, array('date', 'datetime'))) + { $tmp = explode(',', $size); $newsize = $tmp[0]; - $showtime = 0; + + $showtime = in_array($type, array('datetime')) ? 1 : 0; // Do not show current date when field not required (see selectDate() method) if (!$required && $value == '') $value = '-1'; // TODO Must also support $moreparam $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); - } elseif (in_array($type, array('datetime'))) { - $tmp = explode(',', $size); - $newsize = $tmp[0]; - $showtime = 1; - - // Do not show current date when field not required (see selectDate() method) - if (!$required && $value == '') $value = '-1'; - - // TODO Must also support $moreparam - $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel'); - } elseif (in_array($type, array('int', 'integer'))) + } + elseif (in_array($type, array('int', 'integer'))) { $tmp = explode(',', $size); $newsize = $tmp[0]; $out = ''; - } elseif (preg_match('/varchar/', $type)) + } + elseif (preg_match('/varchar/', $type)) { $out = ''; - } elseif (in_array($type, array('mail', 'phone', 'url'))) + } + elseif (in_array($type, array('mail', 'phone', 'url'))) { $out = ''; - } elseif ($type == 'text') + } + elseif ($type == 'text') { if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); $out = $doleditor->Create(1); - } else { + } + else + { $out = ''; } - } elseif ($type == 'html') + } + elseif ($type == 'html') { if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); $out = $doleditor->Create(1); - } else { + } + else + { $out = ''; } - } elseif ($type == 'boolean') + } + elseif ($type == 'boolean') { if (empty($mode)) { @@ -1077,22 +1122,27 @@ $checked = ' value="1" '; } $out = ''; - } else { + } + else + { $out .= $form->selectyesno($keyprefix.$key.$keysuffix, $value, 1, false, 1); } - } elseif ($type == 'price') + } + elseif ($type == 'price') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value = price($value); } $out = ' '.$langs->getCurrencySymbol($conf->currency); - } elseif ($type == 'double') + } + elseif ($type == 'double') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value = price($value); } $out = ' '; - } elseif ($type == 'select') + } + elseif ($type == 'select') { $out = ''; if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) @@ -1116,7 +1166,8 @@ $out .= ''; } $out .= ''; - } elseif ($type == 'sellist') + } + elseif ($type == 'sellist') { $out = ''; if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) @@ -1137,8 +1188,8 @@ // 2 : key fields name (if differ of rowid) // 3 : key field parent (for dependent lists) // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value - // 5 : id category type - // 6 : ids categories list separated by comma for category root + // 5 : id category type + // 6 : ids categories list separated by comma for category root $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); @@ -1157,129 +1208,131 @@ $keyList .= ', '.$parentField; } - $filter_categorie = false; - if (count($InfoFieldList) > 5) { - if ($InfoFieldList[0] == 'categorie') { - $filter_categorie = true; - } - } - - if ($filter_categorie === false) { - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $keyList .= ', '; - $keyList .= implode(', ', $fields_label); - } - - $sqlwhere = ''; - $sql = 'SELECT '.$keyList; - $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; - if (!empty($InfoFieldList[4])) { - // can use curent entity filter - if (strpos($InfoFieldList[4], '$ENTITY$') !== false) { - $InfoFieldList[4] = str_replace('$ENTITY$', $conf->entity, $InfoFieldList[4]); - } - // can use SELECT request - if (strpos($InfoFieldList[4], '$SEL$') !== false) { - $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); - } - - // current object id can be use into filter - if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { - $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); - } else { - $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); - } - //We have to join on extrafield table - if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; - } else { - $sqlwhere .= ' WHERE '.$InfoFieldList[4]; - } - } else { - $sqlwhere .= ' WHERE 1=1'; - } - // Some tables may have field, some other not. For the moment we disable it. - if (in_array($InfoFieldList[0], array('tablewithentity'))) { - $sqlwhere .= ' AND entity = '.$conf->entity; - } - $sql .= $sqlwhere; - //print $sql; - - $sql .= ' ORDER BY '.implode(', ', $fields_label); - - dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $out .= ''; - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) { - $labeltoshow = ''; - $obj = $this->db->fetch_object($resql); - - // Several field into label (eq table:code|libelle:rowid) - $notrans = false; - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label) && count($fields_label) > 1) { - $notrans = true; - foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow.' '; - } - } else { - $labeltoshow = $obj->{$InfoFieldList[1]}; - } - $labeltoshow = $labeltoshow; - - if ($value == $obj->rowid) { - if (!$notrans) { - foreach ($fields_label as $field_toshow) { - $translabel = $langs->trans($obj->$field_toshow); - $labeltoshow = $translabel.' '; - } - } - $out .= ''; - } else { - if (!$notrans) { - $translabel = $langs->trans($obj->{$InfoFieldList[1]}); - $labeltoshow = $translabel; - } - if (empty($labeltoshow)) $labeltoshow = '(not defined)'; - - if (!empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName.':'.$obj->{$parentField}; - } - - $out .= ''; - } - - $i++; - } - $this->db->free($resql); - } else { - print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
    '; - } - } else { + $filter_categorie = false; + if (count($InfoFieldList) > 5) { + if ($InfoFieldList[0] == 'categorie') { + $filter_categorie = true; + } + } + + if ($filter_categorie === false) { + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } + + $sqlwhere = ''; + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; + if (!empty($InfoFieldList[4])) { + // can use curent entity filter + if (strpos($InfoFieldList[4], '$ENTITY$') !== false) { + $InfoFieldList[4] = str_replace('$ENTITY$', $conf->entity, $InfoFieldList[4]); + } + // can use SELECT request + if (strpos($InfoFieldList[4], '$SEL$') !== false) { + $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); + } + + // current object id can be use into filter + if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { + $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); + } else { + $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); + } + //We have to join on extrafield table + if (strpos($InfoFieldList[4], 'extra') !== false) { + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; + } else { + $sqlwhere .= ' WHERE '.$InfoFieldList[4]; + } + } else { + $sqlwhere .= ' WHERE 1=1'; + } + // Some tables may have field, some other not. For the moment we disable it. + if (in_array($InfoFieldList[0], array('tablewithentity'))) { + $sqlwhere .= ' AND entity = '.$conf->entity; + } + $sql .= $sqlwhere; + //print $sql; + + $sql .= ' ORDER BY '.implode(', ', $fields_label); + + dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $out .= ''; + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $labeltoshow = ''; + $obj = $this->db->fetch_object($resql); + + // Several field into label (eq table:code|libelle:rowid) + $notrans = false; + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label) && count($fields_label) > 1) { + $notrans = true; + foreach ($fields_label as $field_toshow) { + $labeltoshow .= $obj->$field_toshow.' '; + } + } else { + $labeltoshow = $obj->{$InfoFieldList[1]}; + } + $labeltoshow = dol_trunc($labeltoshow, 45); + + if ($value == $obj->rowid) { + if (!$notrans) { + foreach ($fields_label as $field_toshow) { + $translabel = $langs->trans($obj->$field_toshow); + $labeltoshow = dol_trunc($translabel, 18).' '; + } + } + $out .= ''; + } else { + if (!$notrans) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + $labeltoshow = dol_trunc($translabel, 18); + } + if (empty($labeltoshow)) $labeltoshow = '(not defined)'; + + if (!empty($InfoFieldList[3]) && $parentField) { + $parent = $parentName.':'.$obj->{$parentField}; + } + + $out .= ''; + } + + $i++; + } + $this->db->free($resql); + } else { + print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
    '; + } + } else { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1); - $out .= ''; - foreach ($data as $data_key => $data_value) { - $out .= ''; + foreach ($data as $data_key => $data_value) { + $out .= '
    '; $ret .= ''."\n"; - } else { + } + else + { if ($fieldrequired) $ret .= ''; if ($help) { $ret .= $this->textwithpicto($langs->trans($text), $help); @@ -134,7 +135,9 @@ } if ($fieldrequired) $ret .= ''; } - } else { + } + else + { if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= ''; if (empty($notabletag)) $ret .= '
    '; if ($fieldrequired) $ret .= ''; if ($help) { @@ -187,9 +190,10 @@ if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) // TODO add jquery timepicker and support select { $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg); - } else { - $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname); - if ($editmode) + } + else + { + if (GETPOST('action', 'aZ09') == 'edit'.$htmlname) { $ret .= "\n"; $ret .= '
    '; @@ -201,13 +205,15 @@ if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) { $tmp = explode(':', $typeofdata); - $ret .= ''; - } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) + $ret .= ''; + } + elseif (preg_match('/^(numeric|amount)/', $typeofdata)) { $tmp = explode(':', $typeofdata); $valuetoshow = price2num($editvalue ? $editvalue : $value); - $ret .= ''; - } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) // if wysiwyg is enabled $typeofdata = 'ckeditor' + $ret .= ''; + } + elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) // if wysiwyg is enabled $typeofdata = 'ckeditor' { $tmp = explode(':', $typeofdata); $cols = $tmp[2]; @@ -219,19 +225,22 @@ } $valuetoshow = ($editvalue ? $editvalue : $value); - $ret .= ''; - } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') + } + elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') { $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0); - } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') + } + elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') { $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0); - } elseif (preg_match('/^select;/', $typeofdata)) + } + elseif (preg_match('/^select;/', $typeofdata)) { $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata)); $arraylist = array(); @@ -242,7 +251,8 @@ $arraylist[$tmpkey] = $tmp[1]; } $ret .= $this->selectarray($htmlname, $arraylist, $value); - } elseif (preg_match('/^ckeditor/', $typeofdata)) + } + elseif (preg_match('/^ckeditor/', $typeofdata)) { $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -253,21 +263,22 @@ if (empty($notabletag)) $ret .= '
    '; //else $ret.='
    '; - $ret .= ''; + $ret .= ''; if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) $ret .= '
    '."\n"; - $ret .= ''; + $ret .= ''; if (empty($notabletag)) $ret .= '
    '."\n"; $ret .= ''."\n"; - } else { + } + else + { if (preg_match('/^(email)/', $typeofdata)) $ret .= dol_print_email($value, 0, 0, 0, 0, 1); elseif (preg_match('/^(amount|numeric)/', $typeofdata)) $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : ''); elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) $ret .= dol_htmlentitiesbr($value); elseif (preg_match('/^safehtmlstring/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value); - elseif (preg_match('/^restricthtml/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value); - elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= ''.dol_print_date($value, 'day').''; - elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= ''.dol_print_date($value, 'dayhour').''; + elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= dol_print_date($value, 'day'); + elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= dol_print_date($value, 'dayhour'); elseif (preg_match('/^select;/', $typeofdata)) { $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata)); @@ -278,7 +289,8 @@ $arraylist[$tmp[0]] = $tmp[1]; } $ret .= $arraylist[$value]; - } elseif (preg_match('/^ckeditor/', $typeofdata)) + } + elseif (preg_match('/^ckeditor/', $typeofdata)) { $tmpcontent = dol_htmlentitiesbr($value); if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) @@ -290,7 +302,8 @@ // We dont use dol_escape_htmltag to get the html formating active, but this need we must also // clean data from some dangerous html $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent)); - } else { + } + else { $ret .= dol_escape_htmltag($value); } @@ -428,7 +441,8 @@ if (!empty($tmp[1])) $inputOption = $tmp[1]; if (!empty($tmp[2])) $savemethod = $tmp[2]; $out .= ''."\n"; - } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) + } + elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) { $tmp = explode(':', $inputType); $inputType = $tmp[0]; @@ -436,19 +450,22 @@ if (!empty($tmp[2])) $savemethod = $tmp[2]; $out .= ''."\n"; // Use for timestamp format - } elseif (preg_match('/^(select|autocomplete)/', $inputType)) + } + elseif (preg_match('/^(select|autocomplete)/', $inputType)) { $tmp = explode(':', $inputType); $inputType = $tmp[0]; $loadmethod = $tmp[1]; if (!empty($tmp[2])) $savemethod = $tmp[2]; if (!empty($tmp[3])) $button_only = true; - } elseif (preg_match('/^textarea/', $inputType)) + } + elseif (preg_match('/^textarea/', $inputType)) { $tmp = explode(':', $inputType); $inputType = $tmp[0]; $rows = (empty($tmp[1]) ? '8' : $tmp[1]); $cols = (empty($tmp[2]) ? '80' : $tmp[2]); - } elseif (preg_match('/^ckeditor/', $inputType)) + } + elseif (preg_match('/^ckeditor/', $inputType)) { $tmp = explode(':', $inputType); $inputType = $tmp[0]; $toolbar = $tmp[1]; @@ -459,7 +476,9 @@ if (!empty($conf->fckeditor->enabled)) { $out .= ''."\n"; - } else { + } + else + { $inputType = 'textarea'; } } @@ -478,7 +497,9 @@ $out .= ''."\n"; if (!empty($custommsg['error'])) $out .= ''."\n"; - } else $out .= ''."\n"; + } + else + $out .= ''."\n"; } if ($inputType == 'textarea') { $out .= ''."\n"; @@ -486,7 +507,9 @@ } $out .= ''.$value.''."\n"; $out .= ''.(!empty($editvalue) ? $editvalue : $value).''."\n"; - } else { + } + else + { $out = $value; } @@ -510,6 +533,7 @@ * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only) * @return string Code html du tooltip (texte+picto) * @see textwithpicto() Use thisfunction if you can. + * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip */ public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0) { @@ -533,7 +557,9 @@ if ($tooltiptrigger == '') { $htmltext = str_replace('"', '"', $htmltext); - } else { + } + else + { $classfortooltip = 'classfortooltiponclick'; $textfordialog .= ''; } @@ -542,13 +568,15 @@ $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"'; if ($tooltiptrigger == '') $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip else $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"'; - } else $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag + } + else $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag if ($tooltipon == 1 || $tooltipon == 3) { $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" '; if ($tooltiptrigger == '') $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip else $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"'; - } else $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag + } + else $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag if (empty($notabs)) $s .= ''; elseif ($notabs == 2) $s .= '
    '; // Define value if value is before @@ -603,7 +631,8 @@ if (empty($conf->use_javascript_ajax)) { if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text; - else { + else + { $alt = $htmltext; $htmltext = ''; } @@ -636,20 +665,18 @@ * Generate select HTML to choose massaction * * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default. - * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action. + * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action. * @param int $alwaysvisible 1=select button always visible - * @param string $name Name for massaction - * @param string $cssclass CSS class used to check for select - * @return string|void Select list - */ - public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect') + * @return string|void Select list + */ + public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0) { global $conf, $langs, $hookmanager; $disabled = 0; $ret = '
    '; - $ret .= ''; // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks. $parameters = array(); @@ -668,46 +695,46 @@ $ret .= ''; - if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select'); + if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.massactionselect'); // Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button $ret .= ''; // Hidden button BEFORE so it is the one used when we submit with ENTER. - $ret .= ''; + $ret .= ''; $ret .= '
    '; if (!empty($conf->use_javascript_ajax)) { $ret .= ' '; + $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter); + $out .= ' '; + $out .= '
    '; + } $assignedtouser = array(); if (!empty($_SESSION['assignedtouser'])) { @@ -1869,7 +1932,7 @@ } $nbassignetouser = count($assignedtouser); - //if ($nbassignetouser && $action != 'view') $out .= '
    '; + if ($nbassignetouser && $action != 'view') $out .= '
    '; if ($nbassignetouser) $out .= '
      '; $i = 0; $ownerid = 0; foreach ($assignedtouser as $key => $value) @@ -1890,7 +1953,7 @@ if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) { $out .= '
      '; - $out .= ' - '.$langs->trans("Availability").': '; + $out .= ' - '.$langs->trans("Availability").': '.$langs->trans("Busy"); $out .= '
      '; } } @@ -1902,22 +1965,7 @@ } if ($nbassignetouser) $out .= '
    '; - // Method with no ajax - if ($action != 'view') - { - $out .= ''; - $out .= ''; - $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter); - $out .= ' '; - $out .= '
    '; - } - + //$out.=''; return $out; } @@ -1927,7 +1975,7 @@ * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list * * @param int $selected Preselected products - * @param string $htmlname Name of HTML select field (must be unique in page). + * @param string $htmlname Name of HTML select field (must be unique in page) * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service) * @param int $limit Limit on number of returned lines * @param int $price_level Level of price to show @@ -1946,15 +1994,12 @@ * 'warehouseclosed' = count products from closed warehouses, * 'warehouseinternal' = count products from warehouses for internal correct/transfer only * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) - * @param string $nooutput No print, return the output into a string - * @return void|string - */ - public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0) + * @return void + */ + public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = array()) { // phpcs:enable global $langs, $conf; - - $out = ''; // check parameters $price_level = (!empty($price_level) ? $price_level : 0); @@ -1963,7 +2008,8 @@ if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { if (!empty($conf->product->enabled) && empty($conf->service->enabled)) { $filtertype = '0'; - } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) { + } + elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) { $filtertype = '1'; } } @@ -1985,7 +2031,8 @@ { if (empty($conf->product->enabled)) { // when product module is disabled, show services only $filtertype = 1; - } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only + } + elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only $filtertype = 0; } } @@ -1995,107 +2042,102 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { $urloption .= '&socid='.$socid; } - $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions); - - if (!empty($conf->variants->enabled) && is_array($selected_combinations)) { - // Code to automatically insert with javascript the select of attributes under the select of product - // when a parent of variant has been selected. - $out .= ' - + print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + + if (!empty($conf->variants->enabled)) { + ?> - '; - } - - if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : '; + trans("RefOrLabel").' : '; elseif ($hidelabel > 1) { $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"'; if ($hidelabel == 2) { - $out .= img_picto($langs->trans("Search"), 'search'); - } - } - $out .= 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + print img_picto($langs->trans("Search"), 'search'); + } + } + print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; if ($hidelabel == 3) { - $out .= img_picto($langs->trans("Search"), 'search'); - } - } else { - $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus); - } - - if (empty($nooutput)) print $out; - else return $out; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of products for a customer. - * Called by select_produits. + print img_picto($langs->trans("Search"), 'search'); + } + } + else + { + print $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus); + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of products for a customer * * @param int $selected Preselected product * @param string $htmlname Name of select html @@ -2117,18 +2159,18 @@ * 'warehouseinternal' = count products from warehouses for internal correct/transfer only * @return array Array of keys for json */ - public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '') - { - // phpcs:enable + public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '') + { + // phpcs:enable global $langs, $conf, $user, $db; $out = ''; $outarray = array(); - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $langs->load('other'); - } + // Units + if ($conf->global->PRODUCT_USE_UNITS) { + $langs->load('other'); + } $warehouseStatusArray = array(); if (!empty($warehouseStatus)) @@ -2151,9 +2193,11 @@ $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; if (count($warehouseStatusArray)) { - $selectFieldsGrouped = ", sum(".$this->db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock - } else { - $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock"; + $selectFieldsGrouped = ", sum(".$db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock + } + else + { + $selectFieldsGrouped = ", ".$db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock"; } $sql = "SELECT "; @@ -2176,11 +2220,11 @@ $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; } - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; - $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units'; - } + // Units + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; + $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units'; + } // Multilang : we add translation if (!empty($conf->global->MAIN_MULTILANGS)) @@ -2206,27 +2250,27 @@ { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")"; - $sql .= ' AND e.statut IN ('.$this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0. + $sql .= ' AND e.statut IN ('.$this->db->escape(implode(',', $warehouseStatusArray)).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0. } // include search in supplier ref if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; } //Price by customer if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; } - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit"; - } + // Units + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit"; + } // Multilang : we add translation if (!empty($conf->global->MAIN_MULTILANGS)) { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$this->db->escape($langs->getDefaultLang())."'"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$langs->getDefaultLang()."'"; } if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { @@ -2242,11 +2286,13 @@ if ($finished == 0) { $sql .= " AND p.finished = ".$finished; - } elseif ($finished == 1) + } + elseif ($finished == 1) { $sql .= " AND p.finished = ".$finished; if ($status >= 0) $sql .= " AND p.tosell = ".$status; - } elseif ($status >= 0) + } + elseif ($status >= 0) { $sql .= " AND p.tosell = ".$status; } @@ -2254,7 +2300,8 @@ if (strval($filtertype) != '') $sql .= " AND p.fk_product_type = ".$filtertype; elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only $sql .= " AND p.fk_product_type = 1"; - } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only + } + elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only $sql .= " AND p.fk_product_type = 0"; } // Add criteria on ref/label @@ -2269,19 +2316,19 @@ foreach ($scrit as $crit) { if ($i > 0) $sql .= " AND "; - $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'"; - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'"; + $sql .= "(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; + if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) { - $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'"; - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'"; - } - if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'"; + $sql .= " OR p.description LIKE '".$db->escape($prefix.$crit)."%'"; + if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$db->escape($prefix.$crit)."%'"; + } + if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'"; $sql .= ")"; $i++; } if (count($scrit) > 1) $sql .= ")"; - if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; $sql .= ')'; } if (count($warehouseStatusArray)) @@ -2295,14 +2342,16 @@ $sql .= " ORDER BY categorie_product_id "; //ASC OR DESC order ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC"; - } else { - $sql .= $this->db->order("p.ref"); - } - - $sql .= $this->db->plimit($limit, 0); + } + else + { + $sql .= $db->order("p.ref"); + } + + $sql .= $db->plimit($limit, 0); // Build output string - dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG); + dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -2329,8 +2378,10 @@ { if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty); else $textifempty .= $langs->trans("All"); - } else { - if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty); + } + else + { + if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty); } if ($showempty) $out .= ''; @@ -2348,7 +2399,7 @@ $sql .= " WHERE fk_product_price=".$objp->price_rowid; $sql .= " ORDER BY quantity ASC"; - dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG); + dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG); $result2 = $this->db->query($sql); if ($result2) { @@ -2380,7 +2431,9 @@ array_push($outarray, $optJson); } } - } else { + } + else + { if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) { $price_product = new Product($this->db); $price_product->fetch($objp->rowid, '', '', 1); @@ -2412,7 +2465,9 @@ if (empty($outputmode)) return $out; return $outarray; - } else { + } + else + { dol_print_error($db); } } @@ -2470,43 +2525,43 @@ if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - // Units - $outvalUnits = ''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - if (!empty($objp->unit_short)) { - $outvalUnits .= ' - '.$objp->unit_short; - } - } - if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) { - if (!empty($objp->weight) && $objp->weight_units !== null) { - $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs); - $outvalUnits .= ' - '.$unitToShow; - } - if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) { - $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units); - $outvalUnits .= ' - '.$unitToShow; - } - if (!empty($objp->surface) && $objp->surface_units !== null) { - $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs); - $outvalUnits .= ' - '.$unitToShow; - } - if (!empty($objp->volume) && $objp->volume_units !== null) { - $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs); - $outvalUnits .= ' - '.$unitToShow; - } - } - if ($outdurationvalue && $outdurationunit) { - $da = array( - 'h' => $langs->trans('Hour'), - 'd' => $langs->trans('Day'), - 'w' => $langs->trans('Week'), - 'm' => $langs->trans('Month'), - 'y' => $langs->trans('Year') - ); - if (isset($da[$outdurationunit])) { - $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : '')); - } - } + // Units + $outvalUnits = ''; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + if (!empty($objp->unit_short)) { + $outvalUnits .= ' - '.$objp->unit_short; + } + } + if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) { + if (!empty($objp->weight) && $objp->weight_units !== null) { + $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs); + $outvalUnits .= ' - '.$unitToShow; + } + if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) { + $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units); + $outvalUnits .= ' - '.$unitToShow; + } + if (!empty($objp->surface) && $objp->surface_units !== null) { + $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs); + $outvalUnits .= ' - '.$unitToShow; + } + if (!empty($objp->volume) && $objp->volume_units !== null) { + $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs); + $outvalUnits .= ' - '.$unitToShow; + } + } + if ($outdurationvalue && $outdurationunit) { + $da = array( + 'h' => $langs->trans('Hour'), + 'd' => $langs->trans('Day'), + 'w' => $langs->trans('Week'), + 'm' => $langs->trans('Month'), + 'y' => $langs->trans('Year') + ); + if (isset($da[$outdurationunit])) { + $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : '')); + } + } $opt = '\n"; $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'pbq'=>$outpbq); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list) * @@ -2709,9 +2774,9 @@ * @param string $morecss More CSS * @return void */ - public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '') - { - // phpcs:enable + public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '') + { + // phpcs:enable global $langs, $conf; global $price_level, $status, $finished; @@ -2731,12 +2796,14 @@ $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').''; - } else { + } + else + { print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', -1, 0, 0, $alsoproductwithnosupplierprice, $morecss); } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of suppliers products * @@ -2751,13 +2818,12 @@ * @param int $limit Limit of line number * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices * @param string $morecss Add more CSS - * @param int $showstockinlist Show stock information (slower). * @return array Array of keys for json */ - public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0) - { - // phpcs:enable - global $langs, $conf, $db, $user; + public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '') + { + // phpcs:enable + global $langs, $conf, $db; $out = ''; $outarray = array(); @@ -2765,28 +2831,28 @@ $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO); $langs->load('stocks'); - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $langs->load('other'); - } - - $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,"; + // Units + if ($conf->global->PRODUCT_USE_UNITS) { + $langs->load('other'); + } + + $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type,"; $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; $sql .= " pfp.supplier_reputation"; - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; - } - if (!empty($conf->barcode->enabled)) $sql .= ", pfp.barcode"; + // Units + if ($conf->global->PRODUCT_USE_UNITS) { + $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; + } + if (!empty($conf->barcode->enabled)) $sql .= ", pfp.barcode"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )"; if ($socid) $sql .= " AND pfp.fk_soc = ".$socid; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit"; - } + // Units + if ($conf->global->PRODUCT_USE_UNITS) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit"; + } $sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " AND p.tobuy = 1"; if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$this->db->escape($filtertype); @@ -2808,13 +2874,13 @@ } if (count($scrit) > 1) $sql .= ")"; if (!empty($conf->barcode->enabled)) { - $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; - $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; - } + $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + } $sql .= ')'; } $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; - $sql .= $this->db->plimit($limit, 0); + $sql .= $db->plimit($limit, 0); // Build output string @@ -2849,41 +2915,41 @@ $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : ''; $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : ''; - // Units - $outvalUnits = ''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - if (!empty($objp->unit_short)) { - $outvalUnits .= ' - '.$objp->unit_short; - } - if (!empty($objp->weight) && $objp->weight_units !== null) { - $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs); - $outvalUnits .= ' - '.$unitToShow; - } - if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) { - $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units); - $outvalUnits .= ' - '.$unitToShow; - } - if (!empty($objp->surface) && $objp->surface_units !== null) { - $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs); - $outvalUnits .= ' - '.$unitToShow; - } - if (!empty($objp->volume) && $objp->volume_units !== null) { - $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs); - $outvalUnits .= ' - '.$unitToShow; - } - if ($outdurationvalue && $outdurationunit) { - $da = array( - 'h' => $langs->trans('Hour'), - 'd' => $langs->trans('Day'), - 'w' => $langs->trans('Week'), - 'm' => $langs->trans('Month'), - 'y' => $langs->trans('Year') - ); - if (isset($da[$outdurationunit])) { - $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : '')); - } - } - } + // Units + $outvalUnits = ''; + if ($conf->global->PRODUCT_USE_UNITS) { + if (!empty($objp->unit_short)) { + $outvalUnits .= ' - '.$objp->unit_short; + } + if (!empty($objp->weight) && $objp->weight_units !== null) { + $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs); + $outvalUnits .= ' - '.$unitToShow; + } + if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) { + $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units); + $outvalUnits .= ' - '.$unitToShow; + } + if (!empty($objp->surface) && $objp->surface_units !== null) { + $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs); + $outvalUnits .= ' - '.$unitToShow; + } + if (!empty($objp->volume) && $objp->volume_units !== null) { + $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs); + $outvalUnits .= ' - '.$unitToShow; + } + if ($outdurationvalue && $outdurationunit) { + $da = array( + 'h' => $langs->trans('Hour'), + 'd' => $langs->trans('Day'), + 'w' => $langs->trans('Week'), + 'm' => $langs->trans('Month'), + 'y' => $langs->trans('Year') + ); + if (isset($da[$outdurationunit])) { + $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : '')); + } + } + } $objRef = $objp->ref; if ($filterkey && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '$1', $objRef, 1); @@ -2910,7 +2976,7 @@ } $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle); - // Units + // Units $optlabel .= $outvalUnits; $outvallabel .= $outvalUnits; @@ -2941,7 +3007,9 @@ $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/"; $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding $outvallabel .= $langs->transnoentities("Unit"); - } else { + } + else + { $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity; $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity; $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding @@ -2976,54 +3044,18 @@ $optlabel .= " - ".$reputations[$objp->supplier_reputation]; $outvallabel .= " - ".$reputations[$objp->supplier_reputation]; } - } else { + } + else + { if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier { $optlabel .= " - ".$langs->trans("NoPriceDefinedForThisSupplier").''; $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier"); - } else // No supplier price defined for product, even on other suppliers + } + else // No supplier price defined for product, even on other suppliers { $optlabel .= " - ".$langs->trans("NoPriceDefinedForThisSupplier").''; $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier"); - } - } - - if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) - { - $novirtualstock = ($showstockinlist == 2); - - if (!empty($user->rights->stock->lire)) { - $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS')); - - if ($objp->stock > 0) { - $optlabel .= ' - '; - } elseif ($objp->stock <= 0) { - $optlabel .= ' - '; - } - $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS')); - $optlabel .= ''; - if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation - { - $langs->load("stocks"); - - $tmpproduct = new Product($this->db); - $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after) - $tmpproduct->load_virtual_stock(); - $virtualstock = $tmpproduct->stock_theorique; - - $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock; - - $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':'; - if ($virtualstock > 0) { - $optlabel .= ''; - } elseif ($virtualstock <= 0) { - $optlabel .= ''; - } - $optlabel .= $virtualstock; - $optlabel .= ''; - - unset($tmpproduct); - } } } @@ -3044,10 +3076,10 @@ // Add new entry - // "key" value of json key array is used by jQuery automatically as selected value. Example: 'type' = product or service, 'price_ht' = unit price without tax + // "key" value of json key array is used by jQuery automatically as selected value // "label" value of json key array is used by jQuery automatically as text for combo box $out .= $opt; - array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'price_ht'=>price2num($objp->unitprice, 'MT'), 'up'=>price2num($objp->unitprice, 'MT'), 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false))); + array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'up'=>$objp->unitprice, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false))); // Exemple of var_dump $outarray // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp" // ["label"]=>string(76) "ppp (fff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)" @@ -3068,12 +3100,14 @@ if (empty($outputmode)) return $out; return $outarray; - } else { + } + else + { dol_print_error($this->db); } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of suppliers prices for a product * @@ -3082,9 +3116,9 @@ * @param int $selected_supplier Pre-selected supplier if more than 1 result * @return string */ - public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '') - { - // phpcs:enable + public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '') + { + // phpcs:enable global $langs, $conf; $langs->load('stocks'); @@ -3113,7 +3147,9 @@ if (!$num) { $form .= ''; - } else { + } + else + { require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; $form .= ''; @@ -3156,7 +3192,9 @@ if ($objp->quantity == 1) { $opt .= $langs->trans("Unit"); - } else { + } + else + { $opt .= $langs->trans("Units"); } if ($objp->quantity > 1) @@ -3175,12 +3213,14 @@ $form .= ''; $this->db->free($result); return $form; - } else { + } + else + { dol_print_error($this->db); } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of delivery address * @@ -3190,9 +3230,9 @@ * @param int $showempty Add an empty field * @return integer|null */ - public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0) - { - // phpcs:enable + public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0) + { + // phpcs:enable // looking for users $sql = "SELECT a.rowid, a.label"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a"; @@ -3216,7 +3256,9 @@ if ($selected && $selected == $obj->rowid) { print ''; - } else { + } + else + { print ''; } $i++; @@ -3224,21 +3266,23 @@ } print ''; return $num; - } else { + } + else + { dol_print_error($this->db); } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load into cache list of payment terms * * @return int Nb of lines loaded, <0 if KO */ - public function load_cache_conditions_paiements() - { - // phpcs:enable + public function load_cache_conditions_paiements() + { + // phpcs:enable global $langs; $num = count($this->cache_conditions_paiements); @@ -3271,21 +3315,23 @@ //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table return $num; - } else { + } + else + { dol_print_error($this->db); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Charge dans cache la liste des délais de livraison possibles * * @return int Nb of lines loaded, <0 if KO */ - public function load_cache_availability() - { - // phpcs:enable + public function load_cache_availability() + { + // phpcs:enable global $langs; $num = count($this->cache_availability); @@ -3318,7 +3364,9 @@ $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1); return $num; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -3333,7 +3381,7 @@ * @param int $addempty Add empty entry * @return void */ - public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0) + public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0) { global $langs, $user; @@ -3348,7 +3396,9 @@ if ($selected == $id) { print ''; } $return .= ''; - if ($addjscombo) $return .= ajax_combobox('select_'.$htmlname); return $return; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load in cache list of transport mode - * - * @return int Nb of lines loaded, <0 if KO - */ - public function load_cache_transport_mode() - { - // phpcs:enable - global $langs; - - $num = count($this->cache_transport_mode); - if ($num > 0) return $num; // Cache already loaded - - dol_syslog(__METHOD__, LOG_DEBUG); - - $this->cache_transport_mode = array(); - - $sql = "SELECT rowid, code, label, active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_transport_mode"; - $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")"; - //if ($active >= 0) $sql.= " AND active = ".$active; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // If traduction exist, we use it else we take the default label - $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : '')); - $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid; - $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code; - $this->cache_transport_mode[$obj->rowid]['label'] = $label; - $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active; - $i++; - } - - $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1); - - return $num; - } - else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Return list of transport mode for intracomm report - * - * @param string $selected Id of the transport mode pre-selected - * @param string $htmlname Name of the select field - * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code - * @param int $empty 1=can be empty, 0 else - * @param int $noadmininfo 0=Add admin info, 1=Disable admin info - * @param int $maxlength Max length of label - * @param int $active Active or not, -1 = all - * @param string $morecss Add more CSS on select tag - * @return void - */ - public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '') - { - global $langs, $user; - - dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG); - - $this->load_cache_transport_mode(); - - print ''; - if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } /** @@ -3754,7 +3709,7 @@ * @param string $moreattrib To add more attribute on select * @return void */ - public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '') + public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '') { global $langs, $conf, $user; @@ -3790,8 +3745,6 @@ } print ""; if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - - print ajax_combobox('select'.$htmlname); } else { print $langs->trans("NoShippingMethodDefined"); } @@ -3809,7 +3762,7 @@ * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. * @return void */ - public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0) + public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0) { global $langs, $db; @@ -3840,7 +3793,7 @@ * * @return string HTML select */ - public function selectSituationInvoices($selected = '', $socid = 0) + public function selectSituationInvoices($selected = '', $socid = 0) { global $langs; @@ -3851,33 +3804,36 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'facture'; $sql .= ' WHERE entity IN ('.getEntity('invoice').')'; $sql .= ' AND situation_counter >= 1'; - $sql .= ' AND fk_soc = '.(int) $socid; $sql .= ' AND type <> 2'; $sql .= ' ORDER by situation_cycle_ref, situation_counter desc'; $resql = $this->db->query($sql); - if ($resql && $this->db->num_rows($resql) > 0) { // Last seen cycle $ref = 0; while ($obj = $this->db->fetch_object($resql)) { - //Same cycle ? - if ($obj->situation_cycle_ref != $ref) { - // Just seen this cycle - $ref = $obj->situation_cycle_ref; - //not final ? - if ($obj->situation_final != 1) { - //Not prov? - if (substr($obj->ref, 1, 4) != 'PROV') { - if ($selected == $obj->rowid) { - $opt .= ''; - } else { - $opt .= ''; + //Same company ? + if ($socid == $obj->fk_soc) { + //Same cycle ? + if ($obj->situation_cycle_ref != $ref) { + // Just seen this cycle + $ref = $obj->situation_cycle_ref; + //not final ? + if ($obj->situation_final != 1) { + //Not prov? + if (substr($obj->ref, 1, 4) != 'PROV') { + if ($selected == $obj->rowid) { + $opt .= ''; + } else { + $opt .= ''; + } } } } } } - } else { + } + else + { dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR); } if ($opt == '') @@ -3895,7 +3851,7 @@ * @param int $showempty Add a nempty line * @return string HTML select */ - public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0) + public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0) { global $langs; @@ -3913,17 +3869,19 @@ while ($res = $this->db->fetch_object($resql)) { - $unitLabel = $res->label; - if (!empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before - { - $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label; - } + $unitLabel = $res->label; + if (!empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before + { + $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label; + } if ($selected == $res->rowid) { - $return .= ''; - } else { - $return .= ''; + $return .= ''; + } + else + { + $return .= ''; } } $return .= ''; @@ -3931,7 +3889,7 @@ return $return; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return a HTML select list of bank accounts * @@ -3943,15 +3901,12 @@ * @param string $moreattrib To add more attribute on select * @param int $showcurrency Show currency in label * @param string $morecss More CSS - * @param int $nooutput 1=Return string, do not send to output * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...) */ - public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0) - { - // phpcs:enable + public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '') + { + // phpcs:enable global $langs, $conf; - - $out = ''; $langs->load("admin"); $num = 0; @@ -3971,40 +3926,40 @@ $i = 0; if ($num) { - $out .= ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { - $out .= ''; + print ''; } while ($i < $num) { $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) + if ($selected == $obj->rowid) { - $out .= ''; + print ''; $i++; } - $out .= ""; - $out .= ajax_combobox('select'.$htmlname); - } else { - if ($status == 0) $out .= ''.$langs->trans("NoActiveBankAccountDefined").''; - else $out .= ''.$langs->trans("NoBankAccountFound").''; - } - } else { + print ""; + } + else + { + if ($status == 0) print ''.$langs->trans("NoActiveBankAccountDefined").''; + else print ''.$langs->trans("NoBankAccountFound").''; + } + } + else { dol_print_error($this->db); } - - // Output or return - if (empty($nooutput)) print $out; - else return $out; return $num; } @@ -4022,7 +3977,7 @@ */ public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '') { - // phpcs:enable + // phpcs:enable global $langs, $conf; $langs->load("admin"); @@ -4055,7 +4010,9 @@ if ($selected == $obj->rowid) { print '
    '."\n"; - } elseif ($input['type'] == 'password') + } + elseif ($input['type'] == 'password') { $more .= '
    '.$input['label'].'
    '."\n"; - } elseif ($input['type'] == 'select') + } + elseif ($input['type'] == 'select') { $more .= '
    '; if (!empty($input['label'])) $more .= $input['label'].'
    '; $more .= $this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss); $more .= '
    '."\n"; - } elseif ($input['type'] == 'checkbox') + } + elseif ($input['type'] == 'checkbox') { $more .= '
    '; $more .= '
    '.$input['label'].'
    '; @@ -4309,7 +4278,8 @@ if (isset($input['disabled'])) $more .= ' disabled'; $more .= ' />
    '; $more .= '
    '."\n"; - } elseif ($input['type'] == 'radio') + } + elseif ($input['type'] == 'radio') { $i = 0; foreach ($input['values'] as $selkey => $selval) @@ -4317,15 +4287,15 @@ $more .= '
    '; if ($i == 0) $more .= '
    '.$input['label'].'
    '; else $more .= '
     
    '; - $more .= '
    '.$selval.''; + $more .= $selval; $more .= '
    '."\n"; $i++; } - } elseif ($input['type'] == 'date') + } + elseif ($input['type'] == 'date') { $more .= '
    '.$input['label'].'
    '; $more .= '
    '; @@ -4336,13 +4306,16 @@ $formquestion[] = array('name'=>$input['name'].'year'); $formquestion[] = array('name'=>$input['name'].'hour'); $formquestion[] = array('name'=>$input['name'].'min'); - } elseif ($input['type'] == 'other') + } + elseif ($input['type'] == 'other') { $more .= '
    '; if (!empty($input['label'])) $more .= $input['label'].'
    '; $more .= $input['value']; $more .= '
    '."\n"; - } elseif ($input['type'] == 'onecolumn') + } + + elseif ($input['type'] == 'onecolumn') { $moreonecolumn .= '
    '; $moreonecolumn .= $input['value']; @@ -4423,19 +4396,15 @@ if (inputok.length>0) { $.each(inputok, function(i, inputname) { var more = ""; - var inputvalue; - if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") { - inputvalue = $("input[name=\'" + inputname + "\']").val(); - } else { - if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; } - inputvalue = $("#" + inputname + more).val(); - } + if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; } + if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; } + var inputvalue = $("#" + inputname + more).val(); if (typeof inputvalue == "undefined") { inputvalue=""; } - console.log("check inputname="+inputname+" inputvalue="+inputvalue); options += "&" + inputname + "=" + encodeURIComponent(inputvalue); }); } var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options; + //alert(urljump); if (pageyes.length > 0) { location.href = urljump; } $(this).dialog("close"); }, @@ -4471,8 +4440,10 @@ }); '; $formconfirm .= "\n"; - } else { - $formconfirm .= "\n\n"; + } + else + { + $formconfirm .= "\n\n"; if (empty($disableformtag)) $formconfirm .= '
    '."\n"; @@ -4503,7 +4474,7 @@ $formconfirm .= '
    '; - $formconfirm .= ''; + $formconfirm .= ''; $formconfirm .= ''."\n"; $formconfirm .= '
    '; $formconfirm .= $this->selectyesno("confirm", $newselectedchoice); $formconfirm .= '
    '."\n"; @@ -4511,23 +4482,6 @@ if (empty($disableformtag)) $formconfirm .= "\n"; $formconfirm .= '
    '; - if (empty($conf->use_javascript_ajax)) { - $formconfirm .= ''; - $formconfirm .= ''."\n"; - } - $formconfirm .= "\n"; } @@ -4535,7 +4489,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a form to select a project * @@ -4549,9 +4503,9 @@ * @param int $nooutput No print is done. String is returned. * @return string Return html content */ - public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0) - { - // phpcs:enable + public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0) + { + // phpcs:enable global $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; @@ -4569,16 +4523,20 @@ $out .= ''; $out .= ''; $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); - $out .= ''; + $out .= ''; $out .= ''; - } else { + } + else + { if ($selected) { $projet = new Project($this->db); $projet->fetch($selected); //print ''.$projet->title.''; $out .= $projet->getNomUrl(0, '', 1); - } else { + } + else + { $out .= " "; } } @@ -4591,7 +4549,7 @@ return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a form to select payment conditions * @@ -4601,9 +4559,9 @@ * @param int $addempty Add empty entry * @return void */ - public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0) - { - // phpcs:enable + public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0) + { + // phpcs:enable global $langs; if ($htmlname != "none") { @@ -4611,9 +4569,11 @@ print ''; print ''; $this->select_conditions_paiements($selected, $htmlname, -1, $addempty); - print ''; + print ''; print ''; - } else { + } + else + { if ($selected) { $this->load_cache_conditions_paiements(); @@ -4624,7 +4584,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a form to select a delivery delay * @@ -4634,9 +4594,9 @@ * @param int $addempty Ajoute entree vide * @return void */ - public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0) - { - // phpcs:enable + public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0) + { + // phpcs:enable global $langs; if ($htmlname != "none") { @@ -4644,9 +4604,11 @@ print ''; print ''; $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty); - print ''; + print ''; print ''; - } else { + } + else + { if ($selected) { $this->load_cache_availability(); @@ -4666,9 +4628,9 @@ * @param string $htmlname Name of select html field * @param int $addempty Add empty entry * @return void - */ - public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0) - { + */ + public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0) + { global $langs; if ($htmlname != "none") { @@ -4676,9 +4638,11 @@ print ''; print ''; $this->selectInputReason($selected, $htmlname, -1, $addempty); - print ''; + print ''; print ''; - } else { + } + else + { if ($selected) { $this->loadCacheInputReason(); @@ -4696,7 +4660,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a form + html select a date * @@ -4709,9 +4673,9 @@ * @return string * @see selectDate() */ - public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0) - { - // phpcs:enable + public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0) + { + // phpcs:enable global $langs; $ret = ''; @@ -4725,9 +4689,11 @@ $ret .= ''; $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0); $ret .= ''; - $ret .= ''; + $ret .= ''; $ret .= ''; - } else { + } + else + { if ($displayhour) $ret .= dol_print_date($selected, 'dayhour'); else $ret .= dol_print_date($selected, 'day'); } @@ -4737,7 +4703,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a select form to choose a user * @@ -4748,9 +4714,9 @@ * @param array $include List of users id to include * @return void */ - public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '') - { - // phpcs:enable + public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '') + { + // phpcs:enable global $langs; if ($htmlname != "none") @@ -4759,9 +4725,11 @@ print ''; print ''; print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include); - print ''; + print ''; print ''; - } else { + } + else + { if ($selected) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; @@ -4775,7 +4743,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show form with payment mode * @@ -4787,9 +4755,9 @@ * @param int $addempty 1=Add empty entry * @return void */ - public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0) - { - // phpcs:enable + public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0) + { + // phpcs:enable global $langs; if ($htmlname != "none") { @@ -4797,9 +4765,11 @@ print ''; print ''; $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active); - print ''; + print ''; print ''; - } else { + } + else + { if ($selected) { $this->load_cache_types_paiements(); @@ -4810,40 +4780,7 @@ } } - /** - * Show form with transport mode - * - * @param string $page Page - * @param int $selected Id mode pre-select - * @param string $htmlname Name of select html field - * @param int $active Active or not, -1 = all - * @param int $addempty 1=Add empty entry - * @return void - */ - public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0) - { - global $langs; - if ($htmlname != "none") - { - print '
    '; - print ''; - print ''; - $this->selectTransportMode($selected, $htmlname, 2, $addempty, 0, 0, $active); - print ''; - print '
    '; - } - else { - if ($selected) - { - $this->load_cache_transport_mode(); - print $this->cache_transport_mode[$selected]['label']; - } else { - print " "; - } - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show form with multicurrency code * @@ -4852,9 +4789,9 @@ * @param string $htmlname Name of select html field * @return void */ - public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code') - { - // phpcs:enable + public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code') + { + // phpcs:enable global $langs; if ($htmlname != "none") { @@ -4862,15 +4799,17 @@ print ''; print ''; print $this->selectMultiCurrency($selected, $htmlname, 0); - print ''; + print ''; print ''; - } else { + } + else + { dol_include_once('/core/lib/company.lib.php'); print !empty($selected) ? currency_name($selected, 1) : ' '; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show form with multicurrency rate * @@ -4880,9 +4819,9 @@ * @param string $currency Currency code to explain the rate * @return void */ - public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '') - { - // phpcs:enable + public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '') + { + // phpcs:enable global $langs, $mysoc, $conf; if ($htmlname != "none") @@ -4890,26 +4829,30 @@ print '
    '; print ''; print ''; - print ' '; + print ' '; print ' '; - print ''; + print ''; print '
    '; - } else { + } + else + { if (!empty($rate)) { print price($rate, 1, $langs, 1, 0); if ($currency && $rate != 1) print '   ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')'; - } else { + } + else + { print 1; } } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a select box with available absolute discounts * @@ -4925,9 +4868,9 @@ * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return void */ - public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0) - { - // phpcs:enable + public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0) + { + // phpcs:enable global $conf, $langs; if ($htmlname != "none") { @@ -4940,7 +4883,9 @@ { if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice else $translationKey = 'HasCreditNoteFromSupplier'; - } else { + } + else + { if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier'; else $translationKey = 'HasCreditNoteFromSupplier'; } @@ -4949,7 +4894,9 @@ { if (!$filter || $filter == "fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice else $translationKey = 'CompanyHasCreditNote'; - } else { + } + else + { if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount'; else $translationKey = 'CompanyHasCreditNote'; } @@ -4970,7 +4917,7 @@ $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue); if ($nbqualifiedlines > 0) { - print '   '; } print ''; - } else { + } + else + { if ($selected) { print $selected; - } else { + } + else + { print "0"; } } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Show forms to select a contact - * - * @param string $page Page - * @param Societe $societe Filter on third party - * @param int $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML select. If 'none', we just show contact link. - * @return void - */ - public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid') - { - // phpcs:enable + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Show forms to select a contact + * + * @param string $page Page + * @param Societe $societe Filter on third party + * @param int $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML select. If 'none', we just show contact link. + * @return void + */ + public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid') + { + // phpcs:enable global $langs, $conf; if ($htmlname != "none") @@ -5020,17 +4971,18 @@ print ''; print ''; print ''; - print ''; + print ''; print '
    '; - print $this->selectcontacts($societe->id, $selected, $htmlname); - $num = $this->num; + $num = $this->select_contacts($societe->id, $selected, $htmlname); if ($num == 0) { $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); print ''.$addcontact.''; } print '
    '; - } else { + } + else + { if ($selected) { require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; @@ -5043,7 +4995,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Output html select to select thirdparty * @@ -5058,9 +5010,9 @@ * @param int $nooutput No print output. Return it only. * @return void|string */ - public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0) - { - // phpcs:enable + public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0) + { + // phpcs:enable global $langs; $out = ''; @@ -5070,16 +5022,20 @@ $out .= ''; $out .= ''; $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); - $out .= ''; + $out .= ''; $out .= ''; - } else { + } + else + { if ($selected) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $soc = new Societe($this->db); $soc->fetch($selected); $out .= $soc->getNomUrl($langs); - } else { + } + else + { $out .= " "; } } @@ -5088,18 +5044,18 @@ else print $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Retourne la liste des devises, dans la langue de l'utilisateur * * @param string $selected preselected currency code * @param string $htmlname name of HTML select list - * @deprecated + * @deprecated * @return void */ - public function select_currency($selected = '', $htmlname = 'currency_id') - { - // phpcs:enable + public function select_currency($selected = '', $htmlname = 'currency_id') + { + // phpcs:enable print $this->selectCurrency($selected, $htmlname); } @@ -5111,7 +5067,7 @@ * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code * @return string */ - public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0) + public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0) { global $conf, $langs, $user; @@ -5124,21 +5080,23 @@ $out .= ''; @@ -5157,11 +5115,9 @@ * @param string $selected preselected currency code * @param string $htmlname name of HTML select list * @param integer $useempty 1=Add empty line - * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)') - * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available. true = we are in currency_rate update , we don't want to see conf->currency in select * @return string */ - public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false) + public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0) { global $db, $conf, $langs, $user; @@ -5171,18 +5127,17 @@ $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency'; $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')"; - if ($filter) $sql .= " AND ".$filter; - $resql = $this->db->query($sql); + $resql = $db->query($sql); if ($resql) { - while ($obj = $this->db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code; + while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code; } $out = ''; $out .= ''; - } else { + } + else + { $return .= $this->error; } @@ -5459,9 +5430,9 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. * Fields are preselected with : * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) @@ -5481,46 +5452,22 @@ * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field. * @param datetime $adddateof Add a link "Date of invoice" using the following date. * @return string|void Nothing or string if nooutput is 1 - * @deprecated + * @deprecated * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek() */ - public function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '') - { - // phpcs:enable - $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof); - if (!empty($nooutput)) { - return $retstring; - } - print $retstring; - return; - } - - /** - * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. - * Fields are preselected with : - * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') - * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) - * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1) - * - * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2). - * @param integer $set_time_end Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2). - * @param string $prefix Prefix for fields name - * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only - * @return string Html for selectDate - * @see form_date(), select_month(), select_year(), select_dayofweek() - */ - public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0) - { - global $langs; - - $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel'); - $ret .= '
    '; - $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel'); - return $ret; - } - - /** - * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. + public function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '') + { + // phpcs:enable + $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof); + if (!empty($nooutput)) { + return $retstring; + } + print $retstring; + return; + } + + /** + * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. * Fields are preselected with : * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) @@ -5535,24 +5482,18 @@ * @param int $d 1=Show days, month, years * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time * @param int $disabled Disable input fields - * @param int $fullday When a checkbox with id #fullday is checked, hours are set with 00:00 (if value if 'fulldaystart') or 23:59 (if value is 'fulldayend') + * @param int $fullday When a checkbox with id #fullday is cheked, hours are set with 00:00 (if value if 'fulldaystart') or 23:59 (if value is 'fulldayend') * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used. - * @param string $openinghours Specify hour start and hour end for the select ex 8,20 - * @param int $stepminutes Specify step for minutes between 1 and 30 - * @param string $labeladddateof Label to use for the $adddateof parameter. - * @param string $placeholder Placeholder - * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel' + * @param string $openinghours Specify hour start and hour end for the select ex 8,20 + * @param int $stepminutes Specify step for minutes between 1 and 30 + * @param string $labeladddateof Label to use for the $adddateof parameter. * @return string Html for selectDate * @see form_date(), select_month(), select_year(), select_dayofweek() */ - public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '', $placeholder = '', $gm = 'auto') + public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '') { global $conf, $langs; - - if ($gm === 'auto') { - $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey); - } $retstring = ''; @@ -5561,7 +5502,7 @@ if ($m == '') $m = 0; $emptydate = 0; $emptyhours = 0; - if ($stepminutes <= 0 || $stepminutes > 30) $stepminutes = 1; + if ($stepminutes <= 0 || $stepminutes > 30) $stepminutes = 1; if ($empty == 1) { $emptydate = 1; $emptyhours = 1; } if ($empty == 2) { $emptydate = 0; $emptyhours = 1; } $orig_set_time = $set_time; @@ -5569,15 +5510,10 @@ if ($set_time === '' && $emptydate == 0) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - if ($gm == 'tzuser' || $gm == 'tzuserrel') { - $set_time = dol_now($gm); - } else { - $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone - } + $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone } // Analysis of the pre-selection date - $reg = array(); if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage { // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' @@ -5586,23 +5522,28 @@ $sday = (!empty($reg[3]) ? $reg[3] : ''); $shour = (!empty($reg[4]) ? $reg[4] : ''); $smin = (!empty($reg[5]) ? $reg[5] : ''); - } elseif (strval($set_time) != '' && $set_time != -1) + } + elseif (strval($set_time) != '' && $set_time != -1) { // set_time est un timestamps (0 possible) - $syear = dol_print_date($set_time, "%Y", $gm); - $smonth = dol_print_date($set_time, "%m", $gm); - $sday = dol_print_date($set_time, "%d", $gm); + $syear = dol_print_date($set_time, "%Y"); + $smonth = dol_print_date($set_time, "%m"); + $sday = dol_print_date($set_time, "%d"); if ($orig_set_time != '') { - $shour = dol_print_date($set_time, "%H", $gm); - $smin = dol_print_date($set_time, "%M", $gm); - $ssec = dol_print_date($set_time, "%S", $gm); - } else { + $shour = dol_print_date($set_time, "%H"); + $smin = dol_print_date($set_time, "%M"); + $ssec = dol_print_date($set_time, "%S"); + } + else + { $shour = ''; $smin = ''; $ssec = ''; } - } else { + } + else + { // Date est '' ou vaut -1 $syear = ''; $smonth = ''; @@ -5614,9 +5555,6 @@ if ($h == 3) $shour = ''; if ($m == 3) $smin = ''; - $nowgmt = dol_now('gmt'); - //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel')); - // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' $usecalendar = 'combo'; if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) { @@ -5633,31 +5571,33 @@ if (strval($set_time) != '' && $set_time != -1) { //$formated_date=dol_print_date($set_time,$conf->format_date_short); - $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript } // Calendrier popup version eldy if ($usecalendar == "eldy") { - // Input area to enter date manually - $retstring .= 'trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript $retstring .= '>'; - // Icon calendar + // Icone calendrier if (!$disabled) { $retstring .= ''; - } else $retstring .= ''; + } + else $retstring .= ''; $retstring .= ''."\n"; $retstring .= ''."\n"; $retstring .= ''."\n"; - } elseif ($usecalendar == 'jquery') + } + elseif ($usecalendar == 'jquery') { if (!$disabled) { @@ -5693,9 +5633,8 @@ // Zone de saisie manuelle de la date $retstring .= '
    '; - $retstring .= 'trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript $retstring .= '>'; @@ -5711,7 +5650,9 @@ $retstring.=' });'; $retstring.='});'; $retstring.="";*/ - } else { + } + else + { $retstring .= ''; } @@ -5719,12 +5660,16 @@ $retstring .= ''."\n"; $retstring .= ''."\n"; $retstring .= ''."\n"; - } else { + } + else + { $retstring .= "Bad value of MAIN_POPUP_CALENDAR"; } } // Show date with combo selects - else { + else + { + //$retstring.='
    '; // Day $retstring .= ''; @@ -5759,7 +5704,9 @@ if ($emptydate || $set_time == -1) { $retstring .= ''; - } else { + } + else + { $retstring .= ''; for ($year = $syear - 10; $year < $syear + 10; $year++) @@ -5768,13 +5715,11 @@ } $retstring .= "\n"; } - } - } - - if ($d && $h) { - $retstring .= ($h == 2 ? '
    ' : ' '); - $retstring .= ''; - } + //$retstring.='
    '; + } + } + + if ($d && $h) $retstring .= ($h == 2 ? '
    ' : ' '); if ($h) { @@ -5792,13 +5737,10 @@ for ($hour = $hourstart; $hour < $hourend; $hour++) { if (strlen($hour) < 2) $hour = "0".$hour; - $retstring .= ''; + $retstring .= ''; } $retstring .= ''; - //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; - if ($m) $retstring .= ":"; + if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; } if ($m) @@ -5816,44 +5758,44 @@ $retstring .= ''; } - if ($d && $h) { - $retstring .= ''; - } - // Add a "Now" link if ($conf->use_javascript_ajax && $addnowlink) { // Script which will be inserted in the onClick of the "Now" link $reset_scripts = ""; - if ($addnowlink == 2) { // local computer time - // pad add leading 0 on numbers - $reset_scripts .= "Number.prototype.pad = function(size) { + if ($addnowlink == 2) // local computer time + { + // pad add leading 0 on numbers + $reset_scripts .= "Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) {s = '0' + s;} return s; }; var d = new Date();"; - } + } // Generate the date part, depending on the use or not of the javascript calendar - if ($addnowlink == 1) { // server time expressed in user time setup - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; - } elseif ($addnowlink == 2) { - /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix. + if ($addnowlink == 1) // server time expressed in user time setup + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');'; + } + elseif ($addnowlink == 2) + { + /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix. * This break application for foreign languages. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));'; $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());'; $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);'; $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());'; */ - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; - } + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');'; + } /*if ($usecalendar == "eldy") { $base=DOL_URL_ROOT.'/core/'; @@ -5870,15 +5812,14 @@ { if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; - if ($addnowlink == 1) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; - } elseif ($addnowlink == 2) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; - } + if ($addnowlink == 1) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');'; + } + elseif ($addnowlink == 2) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; + } if ($fullday) $reset_scripts .= ' } '; } @@ -5887,15 +5828,14 @@ { if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; - if ($addnowlink == 1) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; - } elseif ($addnowlink == 2) - { - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; - } + if ($addnowlink == 1) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');'; + } + elseif ($addnowlink == 2) + { + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; + } if ($fullday) $reset_scripts .= ' } '; } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick @@ -5914,22 +5854,22 @@ $reset_scripts = ""; // Generate the date part, depending on the use or not of the javascript calendar - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');'; // Update the hour part if ($h) { if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');'; if ($fullday) $reset_scripts .= ' } '; } // Update the minute part if ($m) { if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');'; if ($fullday) $reset_scripts .= ' } '; } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick @@ -5941,61 +5881,20 @@ } } - // Add a link to set data + // Add a "Plus one hour" link if ($conf->use_javascript_ajax && $adddateof) { $tmparray = dol_getdate($adddateof); if (empty($labeladddateof)) $labeladddateof = $langs->trans("DateInvoice"); - $retstring .= ' -
    '; + } + } + } + $ret .= ''; return $ret; } - - /** - * selectModelMail - * - * @param string $prefix Prefix - * @param string $modelType Model type - * @param int $default 1=Show also Default mail template - * @param int $addjscombo Add js combobox - * @return string HTML select string - */ - public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0) - { - global $langs, $db, $user; - - $retstring = ''; - - $TModels = array(); - - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs); - - if ($default) $TModels[0] = $langs->trans('DefaultMailModel'); - if ($result > 0) { - foreach ($formmail->lines_model as $model) { - $TModels[$model->id] = $model->label; - } - } - - $retstring .= '"; - - if ($addjscombo) $retstring .= ajax_combobox('select_'.$prefix.'model_mail'); - - return $retstring; - } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formaccounting.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formaccounting.class.php @@ -36,26 +36,26 @@ private $options_cache = array(); /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) */ public $error = ''; - /** + /** * Constructor * * @param DoliDB $db Database handler */ public function __construct($db) { - $this->db = $db; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + $this->db = $db; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of journals with label by nature * @@ -72,17 +72,19 @@ */ public function select_journal($selectid, $htmlname = 'journal', $nature = 0, $showempty = 0, $select_in = 0, $select_out = 0, $morecss = 'maxwidth300 maxwidthonsmartphone', $usecache = '', $disabledajaxcombo = 0) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $out = ''; - $options = array(); + $options = array(); if ($usecache && !empty($this->options_cache[$usecache])) { - $options = $this->options_cache[$usecache]; - $selected = $selectid; - } else { + $options = $this->options_cache[$usecache]; + $selected = $selectid; + } + else + { $sql = "SELECT rowid, code, label, nature, entity, active"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal"; $sql .= " WHERE active = 1"; @@ -99,27 +101,27 @@ return -1; } - $selected = 0; + $selected = 0; $langs->load('accountancy'); while ($obj = $this->db->fetch_object($resql)) { $label = $obj->code.' - '.$langs->trans($obj->label); - $select_value_in = $obj->rowid; + $select_value_in = $obj->rowid; $select_value_out = $obj->rowid; // Try to guess if we have found default value - if ($select_in == 1) { - $select_value_in = $obj->code; - } - if ($select_out == 1) { - $select_value_out = $obj->code; - } - // Remember guy's we store in database llx_accounting_bookkeeping the code of accounting_journal and not the rowid - if ($selectid != '' && $selectid == $select_value_in) { - //var_dump("Found ".$selectid." ".$select_value_in); - $selected = $select_value_out; - } + if ($select_in == 1) { + $select_value_in = $obj->code; + } + if ($select_out == 1) { + $select_value_out = $obj->code; + } + // Remember guy's we store in database llx_accounting_bookkeeping the code of accounting_journal and not the rowid + if ($selectid != '' && $selectid == $select_value_in) { + //var_dump("Found ".$selectid." ".$select_value_in); + $selected = $select_value_out; + } $options[$select_value_out] = $label; } @@ -136,83 +138,89 @@ return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of accounting category. - * Use mysoc->country_id or mysoc->country_code so they must be defined. - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param int $useempty Set to 1 if we want an empty value - * @param int $maxlen Max length of text in combo box - * @param int $help Add or not the admin help picto - * @param int $allcountries All countries - * @return void - */ - public function select_accounting_category($selected = '', $htmlname = 'account_category', $useempty = 0, $maxlen = 0, $help = 1, $allcountries = 0) - { - // phpcs:enable - global $db, $langs, $user, $mysoc; - - if (empty($mysoc->country_id) && empty($mysoc->country_code) && empty($allcountries)) - { - dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined'); - exit; - } - - if (!empty($mysoc->country_id)) - { - $sql = "SELECT c.rowid, c.label as type, c.range_account"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c"; - $sql .= " WHERE c.active = 1"; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of accounting category. + * Use mysoc->country_id or mysoc->country_code so they must be defined. + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in form + * @param int $useempty Set to 1 if we want an empty value + * @param int $maxlen Max length of text in combo box + * @param int $help Add or not the admin help picto + * @param int $allcountries All countries + * @return void + */ + public function select_accounting_category($selected = '', $htmlname = 'account_category', $useempty = 0, $maxlen = 0, $help = 1, $allcountries = 0) + { + // phpcs:enable + global $db, $langs, $user, $mysoc; + + if (empty($mysoc->country_id) && empty($mysoc->country_code) && empty($allcountries)) + { + dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined'); + exit; + } + + if (!empty($mysoc->country_id)) + { + $sql = "SELECT c.rowid, c.label as type, c.range_account"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c"; + $sql .= " WHERE c.active = 1"; $sql .= " AND c.category_type = 0"; - if (empty($allcountries)) $sql .= " AND c.fk_country = ".$mysoc->country_id; - $sql .= " ORDER BY c.label ASC"; - } else { - $sql = "SELECT c.rowid, c.label as type, c.range_account"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co"; - $sql .= " WHERE c.active = 1"; + if (empty($allcountries)) $sql .= " AND c.fk_country = ".$mysoc->country_id; + $sql .= " ORDER BY c.label ASC"; + } + else + { + $sql = "SELECT c.rowid, c.label as type, c.range_account"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co"; + $sql .= " WHERE c.active = 1"; $sql .= " AND c.category_type = 0"; $sql .= " AND c.fk_country = co.rowid"; - if (empty($allcountries)) $sql .= " AND co.code = '".$this->db->escape($mysoc->country_code)."'"; - $sql .= " ORDER BY c.label ASC"; - } - - dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - $out = ''; + $i = 0; + + if ($useempty) $out .= ''; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $out .= ''; - if ($key == '50' && $onlyselect == 2) - { - print ''; - } + $newcardbutton .= dolGetButtonTitle($langs->trans("AddEvent"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(), 'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid > 0 ? '&socid='.$object->socid : ($socid > 0 ? '&socid='.$socid : '')).($projectid > 0 ? '&projectid='.$projectid : '').'&backtopage='.urlencode($urlbacktopage)); } - print ''; - if ($selected == 0 || $selected == 100) $canedit = 0; - - if (empty($onlyselect)) - { - print ' = 0) ? '' : ' disabled').'>'; - print '%'; - } - } else { - print ' %'; - } - } - - - /** - * Show list of actions for element - * - * @param Object $object Object - * @param string $typeelement 'invoice', 'propal', 'order', 'invoice_supplier', 'order_supplier', 'fichinter' - * @param int $socid Socid of user - * @param int $forceshowtitle Show title even if there is no actions to show - * @param string $morecss More css on table - * @param int $max Max number of record - * @param string $moreparambacktopage More param for the backtopage - * @param string $morehtmlcenter More html text on center of title line - * @return int <0 if KO, >=0 if OK - */ - public function showactions($object, $typeelement, $socid = 0, $forceshowtitle = 0, $morecss = 'listactions', $max = 0, $moreparambacktopage = '', $morehtmlcenter = '') - { - global $langs, $conf, $user; - - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - - $sortfield = 'a.datep,a.id'; - $sortorder = 'DESC,DESC'; - - $listofactions = ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max ? ($max + 1) : 0)); - if (!is_array($listofactions)) dol_print_error($this->db, 'FailedToGetActions'); - - $num = count($listofactions); - if ($num || $forceshowtitle) - { - if ($typeelement == 'invoice') $title = $langs->trans('ActionsOnBill'); - elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title = $langs->trans('ActionsOnBill'); - elseif ($typeelement == 'propal') $title = $langs->trans('ActionsOnPropal'); - elseif ($typeelement == 'supplier_proposal') $title = $langs->trans('ActionsOnSupplierProposal'); - elseif ($typeelement == 'order') $title = $langs->trans('ActionsOnOrder'); - elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order') $title = $langs->trans('ActionsOnOrder'); - elseif ($typeelement == 'shipping') $title = $langs->trans('ActionsOnShipping'); - elseif ($typeelement == 'fichinter') $title = $langs->trans('ActionsOnFicheInter'); - elseif ($typeelement == 'project') $title = $langs->trans('LatestLinkedEvents', $max ? $max : ''); - elseif ($typeelement == 'task') $title = $langs->trans('LatestLinkedEvents', $max ? $max : ''); - elseif ($typeelement == 'member') $title = $langs->trans('LatestLinkedEvents', $max ? $max : ''); - else $title = $langs->trans("LatestLinkedEvents", $max ? $max : ''); - - $urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id.($moreparambacktopage ? '&'.$moreparambacktopage : ''); - - $projectid = $object->fk_project; - if ($typeelement == 'project') $projectid = $object->id; - - $newcardbutton = ''; - if (!empty($conf->agenda->enabled) && !empty($user->rights->agenda->myactions->create)) - { - $newcardbutton .= dolGetButtonTitle($langs->trans("AddEvent"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.urlencode(dol_print_date(dol_now(), 'dayhourlog', 'tzuser')).'&origin='.urlencode($typeelement).'&originid='.$object->id.($object->socid > 0 ? '&socid='.$object->socid : ($socid > 0 ? '&socid='.$socid : '')).($projectid > 0 ? '&projectid='.$projectid : '').'&backtopage='.urlencode($urlbacktopage)); - } - - - print ''."\n"; - print load_fiche_titre($title, $newcardbutton, '', 0, 0, '', $morehtmlcenter); - - $page = 0; $param = ''; - - print '
    '; - print ''; - print ''; - print getTitleFieldOfList('Ref', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); - print getTitleFieldOfList('By', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); - print getTitleFieldOfList('Type', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); - print getTitleFieldOfList('Title', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); - print getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, '', $sortfield, $sortorder, 'center ', 1); - print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, 'right ', 1); - print ''; - print "\n"; - - if (is_array($listofactions) && count($listofactions)) - { - $cacheusers = array(); - - $cursorevent = 0; - foreach ($listofactions as $actioncomm) - { - if ($max && $cursorevent >= $max) break; - - $ref = $actioncomm->getNomUrl(1, -1); - $label = $actioncomm->getNomUrl(0, 36); - - print ''; - - // Ref + + + print ''."\n"; + print load_fiche_titre($title, $newcardbutton, '', 0, 0, '', $morehtmlcenter); + + $page = 0; $param = ''; + + print '
    '; + print '
    '; + print ''; + print getTitleFieldOfList('Ref', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); + print getTitleFieldOfList('By', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); + print getTitleFieldOfList('Type', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); + print getTitleFieldOfList('Title', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1); + print getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, '', $sortfield, $sortorder, 'center ', 1); + print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, 'right ', 1); + print ''; + print "\n"; + + if (is_array($listofactions) && count($listofactions)) + { + $cacheusers = array(); + + $cursorevent = 0; + foreach ($listofactions as $actioncomm) + { + if ($max && $cursorevent >= $max) break; + + $ref = $actioncomm->getNomUrl(1, -1); + $label = $actioncomm->getNomUrl(0, 38); + + print ''; + // Ref print ''; - // Onwer - print ''; + print ''; // Type - print ''; - - // Label - print ''; - - // Date - print ''; - print ''; - print ''; - - $cursorevent++; - } - } else { - print ''; - } - - if ($max && $num > $max) - { - print ''; - } - - print '
    '.$ref.''; - if (!empty($actioncomm->userownerid)) - { - if (is_object($cacheusers[$actioncomm->userownerid])) - { - $tmpuser = $cacheusers[$actioncomm->userownerid]; - } else { - $tmpuser = new User($this->db); - $tmpuser->fetch($actioncomm->userownerid); - $cacheusers[$actioncomm->userownerid] = $tmpuser; - } - if ($tmpuser->id > 0) - { - print $tmpuser->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); - } - } - print ''; + if (!empty($actioncomm->userownerid)) + { + if (is_object($cacheusers[$actioncomm->userownerid])) + { + $tmpuser = $cacheusers[$actioncomm->userownerid]; + } + else + { + $tmpuser = new User($this->db); + $tmpuser->fetch($actioncomm->userownerid); + $cacheusers[$actioncomm->userownerid] = $tmpuser; + } + if ($tmpuser->id > 0) + { + print $tmpuser->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); + } + } + print ''; - // TODO Code common with code into comm/action/list.php + print ''; + // TODO Code common with code into comm/action/list.php $imgpicto = ''; if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { if ($actioncomm->type_picto) { $imgpicto = img_picto('', $actioncomm->type_picto); - } else { - if ($actioncomm->type_code == 'AC_RDV') $imgpicto = img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_TEL') $imgpicto = img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_FAX') $imgpicto = img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_EMAIL') $imgpicto = img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_INT') $imgpicto = img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright'); - elseif ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') $imgpicto = img_picto('', 'object_conversation', '', false, 0, 0, '', 'paddingright'); - elseif (!preg_match('/_AUTO/', $actioncomm->type_code)) $imgpicto = img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright'); + } + else { + if ($actioncomm->type_code == 'AC_RDV') $imgpicto = img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actioncomm->type_code == 'AC_TEL') $imgpicto = img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actioncomm->type_code == 'AC_FAX') $imgpicto = img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actioncomm->type_code == 'AC_EMAIL') $imgpicto = img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actioncomm->type_code == 'AC_INT') $imgpicto = img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') $imgpicto = img_picto('', 'object_conversation', '', false, 0, 0, '', 'paddingright').' '; + elseif (!preg_match('/_AUTO/', $actioncomm->type_code)) $imgpicto = img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; } } print $imgpicto; @@ -283,102 +286,105 @@ } else { print $actioncomm->type_short ? $actioncomm->type_short : $actioncomm->type; } - print ''.$label.''.dol_print_date($actioncomm->datep, 'dayhour', 'tzuserrel'); - if ($actioncomm->datef) - { - $tmpa = dol_getdate($actioncomm->datep); - $tmpb = dol_getdate($actioncomm->datef); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) - { - if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($actioncomm->datef, 'hour', 'tzuserrel'); - } else print '-'.dol_print_date($actioncomm->datef, 'dayhour', 'tzuserrel'); - } - print ''; - print $actioncomm->getLibStatut(3); - print '
    '.$langs->trans("None").'
    '.$langs->trans("More").'...
    '; - print '
    '; - } - - return $num; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output html select list of type of event - * - * @param array|string $selected Type pre-selected (can be 'manual', 'auto' or 'AC_xxx'). Can be an array too. - * @param string $htmlname Name of select field - * @param string $excludetype A type to exclude ('systemauto', 'system', '') - * @param integer $onlyautoornot 1=Group all type AC_XXX into 1 line AC_MANUAL. 0=Keep details of type, -1=Keep details and add a combined line "All manual" - * @param int $hideinfohelp 1=Do not show info help, 0=Show, -1=Show+Add info to tell how to set default value - * @param int $multiselect 1=Allow multiselect of action type - * @param int $nooutput 1=No output - * @param string $morecss More css to add to SELECT component. - * @return string - */ - public function select_type_actions($selected = '', $htmlname = 'actioncode', $excludetype = '', $onlyautoornot = 0, $hideinfohelp = 0, $multiselect = 0, $nooutput = 0, $morecss = '') - { - // phpcs:enable - global $langs, $user, $form, $conf; - - if (!is_object($form)) $form = new Form($this->db); - - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $caction = new CActionComm($this->db); - - // Suggest a list with manual events or all auto events - $arraylist = $caction->liste_array(1, 'code', $excludetype, $onlyautoornot); - if (empty($multiselect)) { - // Add empty line at start only if no multiselect - array_unshift($arraylist, ' '); - } - //asort($arraylist); - - if ($selected == 'manual') $selected = 'AC_OTH'; - if ($selected == 'auto') $selected = 'AC_OTH_AUTO'; - - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']); - - $out = ''; + print ''; + // Label + print ''.$label.''; + // Date + print ''.dol_print_date($actioncomm->datep, 'dayhour', 'tzuserrel'); + if ($actioncomm->datef) + { + $tmpa = dol_getdate($actioncomm->datep); + $tmpb = dol_getdate($actioncomm->datef); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) + { + if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($actioncomm->datef, 'hour', 'tzuserrel'); + } + else print '-'.dol_print_date($actioncomm->datef, 'dayhour', 'tzuserrel'); + } + print ''; + print ''; + print $actioncomm->getLibStatut(3); + print ''; + print ''; + + $cursorevent++; + } + } + else + { + print ''.$langs->trans("None").''; + } + + if ($max && $num > $max) + { + print ''.$langs->trans("More").'...'; + } + + print ''; + print ''; + } + + return $num; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Output html select list of type of event + * + * @param array|string $selected Type pre-selected (can be 'manual', 'auto' or 'AC_xxx'). Can be an array too. + * @param string $htmlname Name of select field + * @param string $excludetype A type to exclude ('systemauto', 'system', '') + * @param integer $onlyautoornot 1=Group all type AC_XXX into 1 line AC_MANUAL. 0=Keep details of type, -1=Keep details and add a combined line "All manual" + * @param int $hideinfohelp 1=Do not show info help, 0=Show, -1=Show+Add info to tell how to set default value + * @param int $multiselect 1=Allow multiselect of action type + * @param int $nooutput 1=No output + * @param string $morecss More css to add to SELECT component. + * @return string + */ + public function select_type_actions($selected = '', $htmlname = 'actioncode', $excludetype = '', $onlyautoornot = 0, $hideinfohelp = 0, $multiselect = 0, $nooutput = 0, $morecss = '') + { + // phpcs:enable + global $langs, $user, $form, $conf; + + if (!is_object($form)) $form = new Form($this->db); + + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $caction = new CActionComm($this->db); + + // Suggest a list with manual events or all auto events + $arraylist = $caction->liste_array(1, 'code', $excludetype, $onlyautoornot); + if (empty($multiselect)) { + // Add empty line at start only if no multiselect + array_unshift($arraylist, ' '); + } + //asort($arraylist); + + if ($selected == 'manual') $selected = 'AC_OTH'; + if ($selected == 'auto') $selected = 'AC_OTH_AUTO'; + + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']); + + $out = ''; if (!empty($multiselect)) { - if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected); + if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected); $out .= $form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0); - } else { + } + else + { $out .= $form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200'.($morecss ? ' '.$morecss : ''), 1); } - if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0) - { - $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1); - } - - if ($nooutput) return $out; - else print $out; - return ''; - } + if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0) + { + $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1); + } + + if ($nooutput) return $out; + else print $out; + return ''; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formadmin.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formadmin.class.php @@ -29,40 +29,40 @@ */ class FormAdmin { - public $db; - public $error; + public $db; + public $error; /** * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return html select list with available languages (key='en_US', value='United States' for example) - * - * @param string $selected Language pre-selected - * @param string $htmlname Name of HTML select - * @param int $showauto Show 'auto' choice + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return html select list with available languages (key='en_US', value='United States' for example) + * + * @param string $selected Language pre-selected + * @param string $htmlname Name of HTML select + * @param int $showauto Show 'auto' choice * @param array $filter Array of keys to exclude in list (opposite of $onlykeys) - * @param string $showempty '1'=Add empty value or 'string to show' + * @param string $showempty '1'=Add empty value or string to show * @param int $showwarning Show a warning if language is not complete * @param int $disabled Disable edit of select * @param string $morecss Add more css styles * @param int $showcode 1=Add language code into label at begining, 2=Add language code into label at end - * @param int $forcecombo Force to use combo box (so no ajax beautify effect) - * @param int $multiselect Make the combo a multiselect - * @param array $onlykeys Array of language keys to restrict list with the following keys (opposite of $filter). Example array('fr', 'es', ...) - * @param int $mainlangonly 1=Show only main languages ('fr_FR' no' fr_BE', 'es_ES' not 'es_MX', ...) - * @return string Return HTML select string with list of languages - */ - public function select_language($selected = '', $htmlname = 'lang_id', $showauto = 0, $filter = null, $showempty = '', $showwarning = 0, $disabled = 0, $morecss = '', $showcode = 0, $forcecombo = 0, $multiselect = 0, $onlykeys = null, $mainlangonly = 0) + * @param int $forcecombo Force to use combo box (so no ajax beautify effect) + * @param int $multiselect Make the combo a multiselect + * @param array $onlykeys Show only the following keys (opposite of $filter). Example array('fr', 'es', ...) + * @param int $mainlangonly 1=Show only main languages ('fr_FR' no' fr_BE', 'es_ES' not 'es_MX', ...) + * @return string Return HTML select string with list of languages + */ + public function select_language($selected = '', $htmlname = 'lang_id', $showauto = 0, $filter = null, $showempty = '', $showwarning = 0, $disabled = 0, $morecss = '', $showcode = 0, $forcecombo = 0, $multiselect = 0, $onlykeys = null, $mainlangonly = 0) { // phpcs:enable global $conf, $langs; @@ -95,13 +95,10 @@ foreach ($langs_available as $key => $value) { $valuetoshow = $value; - if ($showcode == 1) { - if ($mainlangonly) $valuetoshow = ''.preg_replace('/[_-].*$/', '', $key).' - '.$value; - else $valuetoshow = ''.$key.' - '.$value; - } + if ($showcode == 1) $valuetoshow = $key.' - '.$value; if ($showcode == 2) { - if ($mainlangonly) $valuetoshow = $value.' ('.preg_replace('/[_-].*$/', '', $key).')'; - else $valuetoshow = $value.' ('.$key.')'; + if ($mainlangonly) $valuetoshow = $value.' ('.preg_replace('/[_-].*$/', '', $key).')'; + else $valuetoshow = $value.' ('.$key.')'; } $keytouse = $key; @@ -114,11 +111,13 @@ continue; } - $valuetoshow .= ' '.picto_from_langcode($key, 'class="saturatemedium"'); - if ($selected == $keytouse) { - $out .= ''; - } else { - $out .= ''; + if ($selected == $keytouse) + { + $out .= ''; + } + else + { + $out .= ''; } } $out .= ''; @@ -133,73 +132,75 @@ return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of available menus (eldy_backoffice, ...) - * - * @param string $selected Preselected menu value - * @param string $htmlname Name of html select - * @param array $dirmenuarray Array of directories to scan - * @param string $moreattrib More attributes on html select tag - * @return integer|null - */ - public function select_menu($selected, $htmlname, $dirmenuarray, $moreattrib = '') - { + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of available menus (eldy_backoffice, ...) + * + * @param string $selected Preselected menu value + * @param string $htmlname Name of html select + * @param array $dirmenuarray Array of directories to scan + * @param string $moreattrib More attributes on html select tag + * @return integer|null + */ + public function select_menu($selected, $htmlname, $dirmenuarray, $moreattrib = '') + { // phpcs:enable - global $langs, $conf; - - // Clean parameters - - - // Check parameters - if (!is_array($dirmenuarray)) return -1; + global $langs, $conf; + + // Clean parameters + + + // Check parameters + if (!is_array($dirmenuarray)) return -1; $menuarray = array(); - foreach ($conf->file->dol_document_root as $dirroot) - { - foreach ($dirmenuarray as $dirtoscan) - { - $dir = $dirroot.$dirtoscan; - //print $dir.'
    '; - if (is_dir($dir)) - { - $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') - { - if (preg_match('/lib\.php$/i', $file)) continue; // We exclude library files - if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - - $filelib = preg_replace('/\.php$/i', '', $file); - $prefix = ''; - // 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other - if (preg_match('/^eldy/i', $file)) $prefix = '0'; - elseif (preg_match('/^smartphone/i', $file)) $prefix = '2'; - else $prefix = '3'; - - if ($file == $selected) - { - $menuarray[$prefix.'_'.$file] = ''; - } else { - $menuarray[$prefix.'_'.$file] = ''; - } - } - } - closedir($handle); - } - } - } - } + foreach ($conf->file->dol_document_root as $dirroot) + { + foreach ($dirmenuarray as $dirtoscan) + { + $dir = $dirroot.$dirtoscan; + //print $dir.'
    '; + if (is_dir($dir)) + { + $handle = opendir($dir); + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') + { + if (preg_match('/lib\.php$/i', $file)) continue; // We exclude library files + if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + + $filelib = preg_replace('/\.php$/i', '', $file); + $prefix = ''; + // 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other + if (preg_match('/^eldy/i', $file)) $prefix = '0'; + elseif (preg_match('/^smartphone/i', $file)) $prefix = '2'; + else $prefix = '3'; + + if ($file == $selected) + { + $menuarray[$prefix.'_'.$file] = ''; + } + else + { + $menuarray[$prefix.'_'.$file] = ''; + } + } + } + closedir($handle); + } + } + } + } ksort($menuarray); // Output combo list of menus - print ''; + $oldprefix = ''; foreach ($menuarray as $key => $val) { $tab = explode('_', $key); @@ -211,7 +212,7 @@ // Affiche titre print ''; @@ -220,69 +221,69 @@ print $val."\n"; // Show menu entry } print ''; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return combo list of available menu families - * - * @param string $selected Menu pre-selected - * @param string $htmlname Name of html select - * @param string[] $dirmenuarray Directories to scan - * @return void - */ - public function select_menu_families($selected, $htmlname, $dirmenuarray) - { - // phpcs:enable - global $langs, $conf; - - //$expdevmenu=array('smartphone_backoffice.php','smartphone_frontoffice.php'); // Menu to disable if $conf->global->MAIN_FEATURES_LEVEL is not set - $expdevmenu = array(); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return combo list of available menu families + * + * @param string $selected Menu pre-selected + * @param string $htmlname Name of html select + * @param string[] $dirmenuarray Directories to scan + * @return void + */ + public function select_menu_families($selected, $htmlname, $dirmenuarray) + { + // phpcs:enable + global $langs, $conf; + + //$expdevmenu=array('smartphone_backoffice.php','smartphone_frontoffice.php'); // Menu to disable if $conf->global->MAIN_FEATURES_LEVEL is not set + $expdevmenu = array(); $menuarray = array(); foreach ($dirmenuarray as $dirmenu) { - foreach ($conf->file->dol_document_root as $dirroot) - { - $dir = $dirroot.$dirmenu; - if (is_dir($dir)) - { - $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') - { - $filelib = preg_replace('/(_backoffice|_frontoffice)?\.php$/i', '', $file); - if (preg_match('/^index/i', $filelib)) continue; - if (preg_match('/^default/i', $filelib)) continue; - if (preg_match('/^empty/i', $filelib)) continue; - if (preg_match('/\.lib/i', $filelib)) continue; - if (empty($conf->global->MAIN_FEATURES_LEVEL) && in_array($file, $expdevmenu)) continue; - - $menuarray[$filelib] = 1; - } - $menuarray['all'] = 1; - } - closedir($handle); - } - } - } + foreach ($conf->file->dol_document_root as $dirroot) + { + $dir = $dirroot.$dirmenu; + if (is_dir($dir)) + { + $handle = opendir($dir); + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') + { + $filelib = preg_replace('/(_backoffice|_frontoffice)?\.php$/i', '', $file); + if (preg_match('/^index/i', $filelib)) continue; + if (preg_match('/^default/i', $filelib)) continue; + if (preg_match('/^empty/i', $filelib)) continue; + if (preg_match('/\.lib/i', $filelib)) continue; + if (empty($conf->global->MAIN_FEATURES_LEVEL) && in_array($file, $expdevmenu)) continue; + + $menuarray[$filelib] = 1; + } + $menuarray['all'] = 1; + } + closedir($handle); + } + } + } } ksort($menuarray); // Affichage liste deroulante des menus - print ''; + $oldprefix = ''; foreach ($menuarray as $key => $val) { $tab = explode('_', $key); $newprefix = $tab[0]; print ''; + + $arraytz = array( "Pacific/Midway"=>"GMT-11:00", "Pacific/Fakaofo"=>"GMT-10:00", "America/Anchorage"=>"GMT-09:00", @@ -338,17 +339,17 @@ "Pacific/Auckland"=>"GMT+12:00", "Pacific/Enderbury"=>"GMT+13:00" ); - foreach ($arraytz as $lib => $gmt) { - print ''."\n"; - } - print ''; - } - - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + foreach ($arraytz as $lib => $gmt) { + print ''."\n"; + } + print ''; + } + + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return html select list with available languages (key='en_US', value='United States' for example) * @@ -368,23 +369,25 @@ $sql = "SELECT code, label, width, height, unit"; $sql .= " FROM ".MAIN_DB_PREFIX."c_paper_format"; $sql .= " WHERE active=1"; - if ($filter) $sql .= " AND code LIKE '%".$this->db->escape($filter)."%'"; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $unitKey = $langs->trans('SizeUnit'.$obj->unit); - - $paperformat[$obj->code] = $langs->trans('PaperFormat'.strtoupper($obj->code)).' - '.round($obj->width).'x'.round($obj->height).' '.($unitKey == 'SizeUnit'.$obj->unit ? $obj->unit : $unitKey); - - $i++; - } - } else { + if ($filter) $sql .= " AND code LIKE '%".$this->db->escape($filter)."%'"; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $unitKey = $langs->trans('SizeUnit'.$obj->unit); + + $paperformat[$obj->code] = $langs->trans('PaperFormat'.strtoupper($obj->code)).' - '.round($obj->width).'x'.round($obj->height).' '.($unitKey == 'SizeUnit'.$obj->unit ? $obj->unit : $unitKey); + + $i++; + } + } + else + { dol_print_error($this->db); return ''; } @@ -399,10 +402,12 @@ } foreach ($paperformat as $key => $value) { - if ($selected == $key) + if ($selected == $key) { $out .= ''; - } else { + } + else + { $out .= ''; } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formbank.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formbank.class.php @@ -23,48 +23,46 @@ * \brief File of class with all html predefined components */ -include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - /** * Class to manage generation of HTML components for bank module */ class FormBank { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** + /** * @var string Error code (or message) */ public $error = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Retourne la liste des types de comptes financiers - * - * @param integer $selected Type pre-selectionne - * @param string $htmlname Nom champ formulaire - * @return void - */ - public function selectTypeOfBankAccount($selected = Account::TYPE_CURRENT, $htmlname = 'type') - { - $account = new Account($this->db); + /** + * Retourne la liste des types de comptes financiers + * + * @param integer $selected Type pre-selectionne + * @param string $htmlname Nom champ formulaire + * @return void + */ + public function selectTypeOfBankAccount($selected = Account::TYPE_CURRENT, $htmlname = 'type') + { + $account = new Account($this->db); - print Form::selectarray($htmlname, $account->type_lib, $selected); - } + print Form::selectarray($htmlname, $account->type_lib, $selected); + } /** * Returns the name of the Iban label. India uses 'IFSC' and the rest of the world 'IBAN' name. --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formbarcode.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formbarcode.class.php @@ -29,198 +29,199 @@ */ class FormBarCode { - /** - * @var DoliDB Database handler. - */ - public $db; - - /** - * @var string Error code (or message) - */ - public $error = ''; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Return HTML select with list of bar code generators - * - * @param int $selected Id code pre-selected - * @param array $barcodelist Array of barcodes generators - * @param int $code_id Id du code barre - * @param int $idForm Id du formulaire - * @return string HTML select string - */ - public function setBarcodeEncoder($selected, $barcodelist, $code_id, $idForm = 'formbarcode') - { - global $conf, $langs; - - $disable = ''; - - if (!empty($conf->use_javascript_ajax)) - { - print "\n".''."\n"; - //onChange="barcode_coder_save(\''.$idForm.'\') - } - - // We check if barcode is already selected by default - if (((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE == $code_id) || - (!empty($conf->societe->enabled) && $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY == $code_id)) - { - $disable = 'disabled'; - } - - if (!empty($conf->use_javascript_ajax)) - { - $select_encoder = '
    '; - $select_encoder .= ''; - $select_encoder .= ''; - $select_encoder .= ''; - } - - $selectname = (!empty($conf->use_javascript_ajax) ? 'coder' : 'coder'.$code_id); - $select_encoder .= ''; - - if (!empty($conf->use_javascript_ajax)) - { - $select_encoder .= '
    '; - } - - return $select_encoder; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Print form to select type of barcode - * - * @param int $selected Id code pre-selected - * @param string $htmlname Name of HTML select field - * @param int $useempty Affiche valeur vide dans liste - * @return void - * @deprecated - */ - public function select_barcode_type($selected = '', $htmlname = 'barcodetype_id', $useempty = 0) - { - // phpcs:enable - print $this->selectBarcodeType($selected, $htmlname, $useempty); - } - - /** - * Return html form to select type of barcode - * - * @param int $selected Id code pre-selected - * @param string $htmlname Name of HTML select field - * @param int $useempty Display empty value in select - * @return string - */ - public function selectBarcodeType($selected = '', $htmlname = 'barcodetype_id', $useempty = 0) - { - global $langs, $conf; - - $out = ''; - - $sql = "SELECT rowid, code, libelle"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; - $sql .= " WHERE coder <> '0'"; - $sql .= " AND entity = ".$conf->entity; - $sql .= " ORDER BY code"; - - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - - if ($useempty && $num > 0) { - $out .= ''; - $out .= ''; - } - - while ($i < $num) { - $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid) { - $out .= ''; - $i++; - } - $out .= ""; - $out .= ajax_combobox("select_".$htmlname); - } else { - dol_print_error($this->db); - } - return $out; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Show form to select type of barcode - * - * @param string $page Page - * @param int $selected Id condition preselected - * @param string $htmlname Nom du formulaire select - * @return void - * @deprecated - */ - public function form_barcode_type($page, $selected = '', $htmlname = 'barcodetype_id') - { - // phpcs:enable - print $this->formBarcodeType($page, $selected, $htmlname); - } - - /** - * Return html form to select type of barcode - * - * @param string $page Page - * @param int $selected Id condition preselected - * @param string $htmlname Nom du formulaire select - * @return string - */ - public function formBarcodeType($page, $selected = '', $htmlname = 'barcodetype_id') - { - global $langs, $conf; - $out = ''; - if ($htmlname != "none") { - $out .= '
    '; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= '
    '; - $out .= $this->selectBarcodeType($selected, $htmlname, 1); - $out .= ''; - $out .= '
    '; - } - return $out; - } + print ''."\n"; + //onChange="barcode_coder_save(\''.$idForm.'\') + } + + // We check if barcode is already selected by default + if (((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE == $code_id) || + (!empty($conf->societe->enabled) && $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY == $code_id)) + { + $disable = 'disabled'; + } + + if (!empty($conf->use_javascript_ajax)) + { + $select_encoder = '
    '; + $select_encoder .= ''; + $select_encoder .= ''; + $select_encoder .= ''; + } + + $selectname = (!empty($conf->use_javascript_ajax) ? 'coder' : 'coder'.$code_id); + $select_encoder .= ''; + + if (!empty($conf->use_javascript_ajax)) + { + $select_encoder .= '
    '; + } + + return $select_encoder; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Print form to select type of barcode + * + * @param int $selected Id code pre-selected + * @param string $htmlname Name of HTML select field + * @param int $useempty Affiche valeur vide dans liste + * @return void + * @deprecated + */ + public function select_barcode_type($selected = '', $htmlname = 'barcodetype_id', $useempty = 0) + { + // phpcs:enable + print $this->selectBarcodeType($selected, $htmlname, $useempty); + } + + /** + * Return html form to select type of barcode + * + * @param int $selected Id code pre-selected + * @param string $htmlname Name of HTML select field + * @param int $useempty Display empty value in select + * @return string + */ + public function selectBarcodeType($selected = '', $htmlname = 'barcodetype_id', $useempty = 0) + { + global $langs, $conf; + + $out = ''; + + $sql = "SELECT rowid, code, libelle"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; + $sql .= " WHERE coder <> '0'"; + $sql .= " AND entity = ".$conf->entity; + $sql .= " ORDER BY code"; + + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + + if ($useempty && $num > 0) { + $out .= ''; + $out .= ''; + } + + while ($i < $num) { + $obj = $this->db->fetch_object($result); + if ($selected == $obj->rowid) { + $out .= ''; + $i++; + } + $out .= ""; + $out .= ajax_combobox("select_".$htmlname); + } + else { + dol_print_error($this->db); + } + return $out; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Show form to select type of barcode + * + * @param string $page Page + * @param int $selected Id condition preselected + * @param string $htmlname Nom du formulaire select + * @return void + * @deprecated + */ + public function form_barcode_type($page, $selected = '', $htmlname = 'barcodetype_id') + { + // phpcs:enable + print $this->formBarcodeType($page, $selected, $htmlname); + } + + /** + * Return html form to select type of barcode + * + * @param string $page Page + * @param int $selected Id condition preselected + * @param string $htmlname Nom du formulaire select + * @return string + */ + public function formBarcodeType($page, $selected = '', $htmlname = 'barcodetype_id') + { + global $langs, $conf; + $out = ''; + if ($htmlname != "none") { + $out .= '
    '; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= '
    '; + $out .= $this->selectBarcodeType($selected, $htmlname, 1); + $out .= ''; + $out .= '
    '; + } + return $out; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formcategory.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formcategory.class.php @@ -32,12 +32,13 @@ /** * Return a HTML filter box for a list filter view * - * @param string $type The categorie type (e.g Categorie::TYPE_WAREHOUSE) - * @param Array $preSelected A list with the elements that should pre-selected - * @return string A HTML filter box (Note: selected results can get with GETPOST("search_category_".$type."_list")) + * @param string $type The categorie type (e.g Categorie::TYPE_WAREHOUSE) + * @param Array $preSelected A list with the elements that should pre-selected + * @return string A HTML filter box (Note: selected results can get with GETPOST("search_category_".$type."_list")) */ - public function getFilterBox($type, array $preSelected) + public function getFilterBox($type, $preSelected) { + // phpcs:enable global $langs; if (empty($preSelected) || !is_array($preSelected)) --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formcompany.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formcompany.class.php @@ -3,7 +3,6 @@ * Copyright (C) 2008-2012 Regis Houssin * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2017 Rui Strecht - * Copyright (C) 2020 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -40,7 +39,7 @@ class FormCompany extends Form { - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of labels (translated) of third parties type * @@ -50,7 +49,7 @@ */ public function typent_array($mode = 0, $filter = '') { - // phpcs:enable + // phpcs:enable global $langs, $mysoc; $effs = array(); @@ -83,7 +82,7 @@ return $effs; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Renvoie la liste des types d'effectifs possibles (pas de traduction car nombre) * @@ -93,7 +92,7 @@ */ public function effectif_array($mode = 0, $filter = '') { - // phpcs:enable + // phpcs:enable $effs = array(); $sql = "SELECT id, code, libelle"; @@ -123,7 +122,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Affiche formulaire de selection des modes de reglement * @@ -135,7 +134,7 @@ */ public function form_prospect_level($page, $selected = '', $htmlname = 'prospect_level_id', $empty = 0) { - // phpcs:enable + // phpcs:enable global $user, $langs; print '
    '; @@ -167,57 +166,6 @@ } print Form::selectarray($htmlname, $options, $selected); - } else dol_print_error($this->db); - if (!empty($htmlname) && $user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print ''; - print '
    '; - } - - /** - * Affiche formulaire de selection des niveau de prospection pour les contacts - * - * @param int $page Page - * @param int $selected Id or code preselected - * @param string $htmlname Nom du formulaire select - * @param int $empty Add empty value in list - * @return void - */ - public function formProspectContactLevel($page, $selected = '', $htmlname = 'prospect_contact_level_id', $empty = 0) - { - global $user, $langs; - - print '
    '; - print ''; - print ''; - - dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_prospectcontactlevel"; - $sql .= " WHERE active > 0"; - $sql .= " ORDER BY sortorder"; - $resql = $this->db->query($sql); - if ($resql) - { - $options = array(); - - if ($empty) - { - $options[''] = ''; - } - - while ($obj = $this->db->fetch_object($resql)) - { - $level = $langs->trans($obj->code); - - if ($level == $obj->code) - { - $level = $langs->trans($obj->label); - } - - $options[$obj->code] = $level; - } - - print Form::selectarray($htmlname, $options, $selected); } else dol_print_error($this->db); if (!empty($htmlname) && $user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); @@ -225,12 +173,12 @@ print '
    '; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns the drop-down list of departments/provinces/cantons for all countries or for a given country. - * In the case of an all-country list, the display breaks on the country. - * The key of the list is the code (there can be several entries for a given code but in this case, the country field differs). - * Thus the links with the departments are done on a department independently of its name. + * In the case of an all-country list, the display breaks on the country. + * The key of the list is the code (there can be several entries for a given code but in this case, the country field differs). + * Thus the links with the departments are done on a department independently of its name. * * @param string $selected Code state preselected * @param int $country_codeid 0=list for all countries, otherwise country code or country rowid to show @@ -239,16 +187,16 @@ */ public function select_departement($selected = '', $country_codeid = 0, $htmlname = 'state_id') { - // phpcs:enable + // phpcs:enable print $this->select_state($selected, $country_codeid, $htmlname); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns the drop-down list of departments/provinces/cantons for all countries or for a given country. - * In the case of an all-country list, the display breaks on the country. - * The key of the list is the code (there can be several entries for a given code but in this case, the country field differs). - * Thus the links with the departments are done on a department independently of its name. + * In the case of an all-country list, the display breaks on the country. + * The key of the list is the code (there can be several entries for a given code but in this case, the country field differs). + * Thus the links with the departments are done on a department independently of its name. * * @param int $selected Code state preselected (mus be state id) * @param integer $country_codeid Country code or id: 0=list for all countries, otherwise country code or country rowid to show @@ -258,7 +206,7 @@ */ public function select_state($selected = 0, $country_codeid = 0, $htmlname = 'state_id') { - // phpcs:enable + // phpcs:enable global $conf, $langs, $user; dol_syslog(get_class($this)."::select_departement selected=".$selected.", country_codeid=".$country_codeid, LOG_DEBUG); @@ -293,7 +241,8 @@ if ($obj->code == '0') // Le code peut etre une chaine { $out .= ''; - } else { + } + else { if (!$country || $country != $obj->country) { // Affiche la rupture si on est en mode liste multipays @@ -307,7 +256,9 @@ if (!empty($selected) && $selected == $obj->rowid) { $out .= ''; - } else { + } + else { if ($country == '' || $country != $obj->country) { // Show break @@ -399,7 +356,9 @@ if ($selected > 0 && $selected == $obj->code) { print ''; - } else { + } + else + { print ''; } } @@ -407,25 +366,25 @@ } } print ''; - print ajax_combobox($htmlname); - } else { + } + else + { dol_print_error($this->db); } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return combo list with people title * * @param string $selected Civility/Title code preselected * @param string $htmlname Name of HTML select combo field * @param string $morecss Add more css on SELECT element - * @param int $addjscombo Add js combo * @return string String with HTML select */ - public function select_civility($selected = '', $htmlname = 'civility_id', $morecss = 'maxwidth150', $addjscombo = 0) - { - // phpcs:enable + public function select_civility($selected = '', $htmlname = 'civility_id', $morecss = 'maxwidth100') + { + // phpcs:enable global $conf, $langs, $user; $langs->load("dict"); @@ -450,10 +409,12 @@ if ($selected == $obj->code) { $out .= ''; $i++; @@ -461,20 +422,16 @@ } $out .= ''; if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - - if ($addjscombo) { - // Enhance with select2 - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $out .= ajax_combobox($htmlname); - } - } else { + } + else + { dol_print_error($this->db); } return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Retourne la liste deroulante des formes juridiques tous pays confondus ou pour un pays donne. * Dans le cas d'une liste tous pays confondu, on affiche une rupture sur le pays. @@ -488,25 +445,25 @@ */ public function select_forme_juridique($selected = '', $country_codeid = 0, $filter = '') { - // phpcs:enable + // phpcs:enable print $this->select_juridicalstatus($selected, $country_codeid, $filter); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Retourne la liste deroulante des formes juridiques tous pays confondus ou pour un pays donne. * Dans le cas d'une liste tous pays confondu, on affiche une rupture sur le pays * * @param string $selected Preselected code of juridical type * @param int $country_codeid 0=list for all countries, otherwise list only country requested - * @param string $filter Add a SQL filter on list - * @param string $htmlname HTML name of select - * @param string $morecss More CSS - * @return string String with HTML select + * @param string $filter Add a SQL filter on list + * @param string $htmlname HTML name of select + * @param string $morecss More CSS + * @return string String with HTML select */ public function select_juridicalstatus($selected = '', $country_codeid = 0, $filter = '', $htmlname = 'forme_juridique_code', $morecss = '') { - // phpcs:enable + // phpcs:enable global $conf, $langs, $user; $langs->load("dict"); @@ -517,7 +474,7 @@ $sql .= " FROM ".MAIN_DB_PREFIX."c_forme_juridique as f, ".MAIN_DB_PREFIX."c_country as c"; $sql .= " WHERE f.fk_pays=c.rowid"; $sql .= " AND f.active = 1 AND c.active = 1"; - if ($country_codeid) $sql .= " AND c.code = '".$this->db->escape($country_codeid)."'"; + if ($country_codeid) $sql .= " AND c.code = '".$country_codeid."'"; if ($filter) $sql .= " ".$filter; $sql .= " ORDER BY c.code"; @@ -568,7 +525,9 @@ if ($selected > 0 && $selected == $val['code']) { $out .= ''; $firstCompany = $obj->rowid; - } else { + } + else + { print ''; @@ -740,28 +705,30 @@ print "\n"; print ajax_combobox($htmlname); return $firstCompany; - } else { + } + else + { dol_print_error($this->db); return 0; } } } - /** - * Return a select list with types of contacts - * - * @param object $object Object to use to find type of contact - * @param string $selected Default selected value - * @param string $htmlname HTML select name - * @param string $source Source ('internal' or 'external') - * @param string $sortorder Sort criteria ('position', 'code', ...) - * @param int $showempty 1=Add en empty line - * @param string $morecss Add more css to select component - * @return void - */ - public function selectTypeContact($object, $selected, $htmlname = 'type', $source = 'internal', $sortorder = 'position', $showempty = 0, $morecss = '') - { - global $user, $langs; + /** + * Return a select list with types of contacts + * + * @param object $object Object to use to find type of contact + * @param string $selected Default selected value + * @param string $htmlname HTML select name + * @param string $source Source ('internal' or 'external') + * @param string $sortorder Sort criteria ('position', 'code', ...) + * @param int $showempty 1=Add en empty line + * @param string $morecss Add more css to select component + * @return void + */ + public function selectTypeContact($object, $selected, $htmlname = 'type', $source = 'internal', $sortorder = 'position', $showempty = 0, $morecss = '') + { + global $user, $langs; if (is_object($object) && method_exists($object, 'liste_type_contact')) { @@ -798,7 +765,7 @@ if ($rendermode === 'view') { $toprint = array(); foreach ($contact->roles as $key => $val) { - $toprint[] = '
  • '.$val['label'].'
  • '; + $toprint[] = '
  • '.$val['label'].'
  • '; } return '
      '.implode(' ', $toprint).'
    '; } @@ -823,13 +790,13 @@ return 'ErrorBadValueForParameterRenderMode'; // Should not happened } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return a select list with zip codes and their town * * @param string $selected Preselected value * @param string $htmlname HTML select name - * @param array $fields Array with key of fields to refresh after selection + * @param string $fields Fields * @param int $fieldsize Field size * @param int $disableautocomplete 1 To disable ajax autocomplete features (browser autocomplete may still occurs) * @param string $moreattrib Add more attribute on HTML input field @@ -838,7 +805,7 @@ */ public function select_ziptown($selected = '', $htmlname = 'zipcode', $fields = '', $fieldsize = 0, $disableautocomplete = 0, $moreattrib = '', $morecss = '') { - // phpcs:enable + // phpcs:enable global $conf; $out = ''; @@ -856,197 +823,158 @@ return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML string to use as input of professional id into a HTML page (siren, siret, etc...) - * - * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm) - * @param string $htmlname Name of HTML select - * @param string $preselected Default value to show - * @param string $country_code FR, IT, ... - * @param string $morecss More css - * @return string HTML string with prof id - */ - public function get_input_id_prof($idprof, $htmlname, $preselected, $country_code, $morecss = 'maxwidth100onsmartphone quatrevingtpercent') - { - // phpcs:enable - global $conf, $langs, $hookmanager; - - $formlength = 0; - if (empty($conf->global->MAIN_DISABLEPROFIDRULES)) { - if ($country_code == 'FR') - { - if (isset($idprof)) { - if ($idprof == 1) $formlength = 9; - elseif ($idprof == 2) $formlength = 14; - elseif ($idprof == 3) $formlength = 5; // 4 chiffres et 1 lettre depuis janvier - elseif ($idprof == 4) $formlength = 32; // No maximum as we need to include a town name in this id - } - } elseif ($country_code == 'ES') - { - if ($idprof == 1) $formlength = 9; //CIF/NIF/NIE 9 digits - if ($idprof == 2) $formlength = 12; //NASS 12 digits without / - if ($idprof == 3) $formlength = 5; //CNAE 5 digits - if ($idprof == 4) $formlength = 32; //depend of college - } - } - - $selected = $preselected; - if (!$selected && isset($idprof)) { - if ($idprof == 1 && !empty($this->idprof1)) $selected = $this->idprof1; - elseif ($idprof == 2 && !empty($this->idprof2)) $selected = $this->idprof2; - elseif ($idprof == 3 && !empty($this->idprof3)) $selected = $this->idprof3; - elseif ($idprof == 4 && !empty($this->idprof4)) $selected = $this->idprof4; - } - - $maxlength = $formlength; - if (empty($formlength)) { $formlength = 24; $maxlength = 128; } - - $out = ''; - - // Execute hook getInputIdProf to complete or replace $out - $parameters = array('formlength'=>$formlength, 'selected'=>$preselected, 'idprof'=>$idprof, 'htmlname'=>$htmlname, 'country_code'=>$country_code); - $reshook = $hookmanager->executeHooks('getInputIdProf', $parameters); - if (empty($reshook)) - { - $out .= ''; - } - $out .= $hookmanager->resPrint; - - return $out; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select with localtax values for thirdparties - * - * @param int $local LocalTax - * @param int $selected Preselected value - * @param string $htmlname HTML select name - * @return void - */ - public function select_localtax($local, $selected, $htmlname) - { - // phpcs:enable - $tax = get_localtax_by_third($local); - - $num = $this->db->num_rows($tax); - $i = 0; - if ($num) - { - $valors = explode(":", $tax); - - if (count($valors) > 1) - { - //montar select - print ''; - } - } - } - - /** - * Return a HTML select for thirdparty type - * - * @param int $selected selected value - * @param string $htmlname HTML select name - * @param string $htmlidname HTML select id - * @param string $typeinput HTML output - * @param string $morecss More css - * @return string HTML string - */ - public function selectProspectCustomerType($selected, $htmlname = 'client', $htmlidname = 'customerprospect', $typeinput = 'form', $morecss = '') - { - - global $conf, $langs; - - $out = ''; - $out .= ajax_combobox($htmlidname); - - return $out; - } - - /** - * Output html select to select third-party type - * - * @param string $page Page - * @param string $selected Id preselected - * @param string $htmlname Name of HTML select - * @param string $filter optional filters criteras - * @param int $nooutput No print output. Return it only. - * @return void|string - */ - public function formThirdpartyType($page, $selected = '', $htmlname = 'socid', $filter = '', $nooutput = 0) - { - // phpcs:enable - global $conf, $langs; - - $out = ''; - if ($htmlname != "none") { - $out .= '
    '; - $out .= ''; - $out .= ''; - $sortparam = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. - $out .= $this->selectarray($htmlname, $this->typent_array(0, $filter), $selected, 0, 0, 0, '', 0, 0, 0, $sortparam, '', 1); - $out .= ''; - $out .= '
    '; - } else { - if ($selected) { - $arr = $this->typent_array(0); - $typent = $arr[$selected]; - $out .= $typent; - } else { - $out .= " "; - } - } - - if ($nooutput) { - return $out; - } else { - print $out; - } - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML string to use as input of professional id into a HTML page (siren, siret, etc...) + * + * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm) + * @param string $htmlname Name of HTML select + * @param string $preselected Default value to show + * @param string $country_code FR, IT, ... + * @param string $morecss More css + * @return string HTML string with prof id + */ + public function get_input_id_prof($idprof, $htmlname, $preselected, $country_code, $morecss = 'maxwidth100onsmartphone quatrevingtpercent') + { + // phpcs:enable + global $conf, $langs, $hookmanager; + + $formlength = 0; + if (empty($conf->global->MAIN_DISABLEPROFIDRULES)) { + if ($country_code == 'FR') + { + if (isset($idprof)) { + if ($idprof == 1) $formlength = 9; + elseif ($idprof == 2) $formlength = 14; + elseif ($idprof == 3) $formlength = 5; // 4 chiffres et 1 lettre depuis janvier + elseif ($idprof == 4) $formlength = 32; // No maximum as we need to include a town name in this id + } + } + elseif ($country_code == 'ES') + { + if ($idprof == 1) $formlength = 9; //CIF/NIF/NIE 9 digits + if ($idprof == 2) $formlength = 12; //NASS 12 digits without / + if ($idprof == 3) $formlength = 5; //CNAE 5 digits + if ($idprof == 4) $formlength = 32; //depend of college + } + } + + $selected = $preselected; + if (!$selected && isset($idprof)) { + if ($idprof == 1 && !empty($this->idprof1)) $selected = $this->idprof1; + elseif ($idprof == 2 && !empty($this->idprof2)) $selected = $this->idprof2; + elseif ($idprof == 3 && !empty($this->idprof3)) $selected = $this->idprof3; + elseif ($idprof == 4 && !empty($this->idprof4)) $selected = $this->idprof4; + } + + $maxlength = $formlength; + if (empty($formlength)) { $formlength = 24; $maxlength = 128; } + + $out = ''; + + // Execute hook getInputIdProf to complete or replace $out + $parameters = array('formlength'=>$formlength, 'selected'=>$preselected, 'idprof'=>$idprof, 'htmlname'=>$htmlname, 'country_code'=>$country_code); + $reshook = $hookmanager->executeHooks('getInputIdProf', $parameters); + if (empty($reshook)) + { + $out .= ''; + } + $out .= $hookmanager->resPrint; + + return $out; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return a HTML select with localtax values for thirdparties + * + * @param int $local LocalTax + * @param int $selected Preselected value + * @param string $htmlname HTML select name + * @return void + */ + public function select_localtax($local, $selected, $htmlname) + { + // phpcs:enable + $tax = get_localtax_by_third($local); + + $num = $this->db->num_rows($tax); + $i = 0; + if ($num) + { + $valors = explode(":", $tax); + + if (count($valors) > 1) + { + //montar select + print ''; + } + } + } + + /** + * Return a HTML select for thirdparty type + * + * @param int $selected selected value + * @param string $htmlname HTML select name + * @param string $htmlidname HTML select id + * @param string $typeinput HTML output + * @param string $morecss More css + * @return string HTML string + */ + public function selectProspectCustomerType($selected, $htmlname = 'client', $htmlidname = 'customerprospect', $typeinput = 'form', $morecss = '') + { + + global $conf, $langs; + + $out = ''; + + return $out; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formcontract.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formcontract.class.php @@ -27,29 +27,29 @@ */ class FormContract { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** + /** * @var string Error code (or message) */ public $error = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a combo list with contracts qualified for a third party * @@ -58,68 +58,63 @@ * @param string $htmlname Nom de la zone html * @param int $maxlength Maximum length of label * @param int $showempty Show empty line - * @param int $showRef Show customer and supplier reference on each contract (when found) * @return int Nbr of project if OK, <0 if KO */ - public function select_contract($socid = -1, $selected = '', $htmlname = 'contrattid', $maxlength = 16, $showempty = 1, $showRef = 0) - { - // phpcs:enable + public function select_contract($socid = -1, $selected = '', $htmlname = 'contrattid', $maxlength = 16, $showempty = 1) + { + // phpcs:enable global $db, $user, $conf, $langs; $hideunselectables = false; if (!empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true; // Search all contacts - $sql = 'SELECT c.rowid, c.ref, c.fk_soc, c.statut,'; - $sql .= ' c.ref_customer, c.ref_supplier'; + $sql = 'SELECT c.rowid, c.ref, c.fk_soc, c.statut'; $sql .= ' FROM '.MAIN_DB_PREFIX.'contrat as c'; $sql .= " WHERE c.entity = ".$conf->entity; //if ($contratListId) $sql.= " AND c.rowid IN (".$contratListId.")"; if ($socid > 0) { // CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma. - if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY)) { - $sql .= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)"; + if (empty($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY)) { + $sql .= " AND (c.fk_soc=".$socid." OR c.fk_soc IS NULL)"; } elseif ($conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all') { - $sql .= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") "; + $sql .= " AND (c.fk_soc IN (".$socid.", ".$conf->global->CONTRACT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") "; $sql .= " OR c.fk_soc IS NULL)"; - } + } } if ($socid == 0) $sql .= " AND (c.fk_soc = 0 OR c.fk_soc IS NULL)"; $sql .= " ORDER BY c.ref "; dol_syslog(get_class($this)."::select_contract", LOG_DEBUG); - $resql = $this->db->query($sql); + $resql = $db->query($sql); if ($resql) { print ''; - $this->db->free($resql); + $db->free($resql); if (!empty($conf->use_javascript_ajax)) { @@ -160,34 +157,35 @@ } return $num; - } else { - dol_print_error($this->db); + } + else + { + dol_print_error($db); return -1; } - } + } - /** - * Show a form to select a contract - * - * @param int $page Page - * @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) - * @param int $selected Id contract preselected - * @param string $htmlname Nom de la zone html - * @param int $maxlength Maximum length of label - * @param int $showempty Show empty line - * @param int $showRef Show customer and supplier reference on each contract (when found) - * @return int Nbr of project if OK, <0 if KO - */ - public function formSelectContract($page, $socid = -1, $selected = '', $htmlname = 'contrattid', $maxlength = 16, $showempty = 1, $showRef = 0) - { - global $langs; + /** + * Show a form to select a contract + * + * @param int $page Page + * @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) + * @param int $selected Id contract preselected + * @param string $htmlname Nom de la zone html + * @param int $maxlength Maximum length of label + * @param int $showempty Show empty line + * @return int Nbr of project if OK, <0 if KO + */ + public function formSelectContract($page, $socid = -1, $selected = '', $htmlname = 'contrattid', $maxlength = 16, $showempty = 1) + { + global $langs; - print "\n"; - print '
    '; - print ''; - print ''; - $this->select_contract($socid, $selected, $htmlname, $maxlength, $showempty, $showRef); - print ''; - print '
    '; - } + print "\n"; + print '
    '; + print ''; + print ''; + $this->select_contract($socid, $selected, $htmlname, $maxlength, $showempty); + print ''; + print '
    '; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formcron.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formcron.class.php @@ -28,75 +28,75 @@ */ class FormCron extends Form { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** - * @var string Error code (or message) - */ - public $error = ''; + /** + * @var string Error code (or message) + */ + public $error = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Display On Off selector - * - * @param string $htmlname Html control name - * @param integer $selected selected value - * @param integer $readonly Select is read only or not - * @return string HTML select field - */ - public function select_typejob($htmlname, $selected = 0, $readonly = 0) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Display On Off selector + * + * @param string $htmlname Html control name + * @param integer $selected selected value + * @param integer $readonly Select is read only or not + * @return string HTML select field + */ + public function select_typejob($htmlname, $selected = 0, $readonly = 0) + { + // phpcs:enable + global $langs; - $langs->load('cron@cron'); - $out = ''; - if (!empty($readonly)) { - if ($selected == 'command') { - $out = $langs->trans('CronType_command'); - $out .= ''; - } elseif ($selected == 'method') { - $out = $langs->trans('CronType_method'); - $out .= ''; - } - } else { - $out = ''; + $out .= ''; + $out .= ''; + } elseif ($selected == 'method') { + $out = $langs->trans('CronType_method'); + $out .= ''; + } + } else { + $out = ''; - } + $out .= ''; + } - return $out; - } + return $out; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formfile.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formfile.class.php @@ -58,7 +58,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show form to upload a new file. * @@ -70,8 +70,8 @@ * @param int $size Length of input file area. Deprecated. * @param Object $object Object to use (when attachment is done on an element) * @param string $options Add an option column - * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). - * Deprecated 2 should never be used and if 1 is used, option should no be enabled. + * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). + * Deprecated 2 should never be used and if 1 is used, option should no be enabled. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__' * @param integer $linkfiles 1=Also add form to link files, 0=Do not show form to link files * @param string $htmlname Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM) @@ -79,19 +79,18 @@ * @param string $sectiondir If upload must be done inside a particular directory (if sectiondir defined, sectionid must not be) * @param int $usewithoutform 0=Default, 1=Disable
    and style to use in existing area * @param int $capture 1=Add tag capture="capture" to force use of micro or video recording to generate file. When setting this to 1, you must also provide a value for $accept. - * @param int $disablemulti 0=Default, 1=Disable multiple file upload * @return int <0 if KO, >0 if OK */ - public function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '', $sectiondir = '', $usewithoutform = 0, $capture = 0, $disablemulti = 0) + public function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '', $sectiondir = '', $usewithoutform = 0, $capture = 0) { - // phpcs:enable + // phpcs:enable global $conf, $langs, $hookmanager; $hookmanager->initHooks(array('formfile')); - // Deprecation warning - if ($useajax == 2) { - dol_syslog(__METHOD__.": using 2 for useajax is deprecated and should be not used", LOG_WARNING); - } + // Deprecation warning + if ($useajax == 2) { + dol_syslog(__METHOD__.": using 2 for useajax is deprecated and should be not used", LOG_WARNING); + } if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax = 0; @@ -102,7 +101,9 @@ // TODO: This does not support option savingdocmask // TODO: This break feature to upload links too return $this->_formAjaxFileUpload($object); - } else { + } + else + { //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { return 1; @@ -115,18 +116,15 @@ if (empty($usewithoutform)) // Try to avoid this and set instead the form by the caller. { - // Add a param as GET parameter to detect when POST were cleaned by PHP because a file larger than post_max_size - $url .= (strpos($url, '?') === false ? '?' : '&').'uploadform=1'; - - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - } - - $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + } + + $out .= '
    '; $out .= ''; if (!empty($options)) $out .= ''; @@ -171,7 +169,7 @@ $out .= 'global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic') ? ' name="userfile"' : ' name="userfile[]" multiple'); - $out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $disablemulti) ? ' name="userfile"' : ' name="userfile[]" multiple'); + $out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD)) ? ' name="userfile"' : ' name="userfile[]" multiple'); $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : ''); $out .= (!empty($accept) ? ' accept="'.$accept.'"' : ' accept=""'); $out .= (!empty($capture) ? ' capture="capture"' : ''); @@ -188,7 +186,7 @@ if ($addcancel) { $out .= '   '; - $out .= ''; + $out .= ''; } if (!empty($conf->global->MAIN_UPLOAD_DOC)) @@ -199,33 +197,32 @@ $out .= ' '; $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1); } - } else { + } + else + { $out .= ' ('.$langs->trans("UploadDisabled").')'; } $out .= ""; if ($savingdocmask) - { - //add a global variable for disable the auto renaming on upload - $rename = (empty($conf->global->MAIN_DOC_UPLOAD_NOT_RENAME_BY_DEFAULT) ? 'checked' : ''); - - $out .= ''; - if (!empty($options)) $out .= ''; - $out .= ''; - $out .= ''; - } + { + //add a global variable for disable the auto renaming on upload + $rename = (empty($conf->global->MAIN_DOC_UPLOAD_NOT_RENAME_BY_DEFAULT) ? 'checked' : ''); + + $out .= ''; + if (!empty($options)) $out .= ''; + $out .= ''; + $out .= ''; + } $out .= "
    '.$options.'
    '.$options.''; - $out .= ' '; - $out .= ''; - $out .= $langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/', $langs->transnoentitiesnoconv("OriginFileName"), $savingdocmask), $langs->transnoentitiesnoconv("OriginFileName")); - $out .= ''; - $out .= '
    '.$options.''; + $out .= ' '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/', $langs->transnoentitiesnoconv("OriginFileName"), $savingdocmask), $langs->transnoentitiesnoconv("OriginFileName")); + $out .= '
    "; if (empty($usewithoutform)) { - $out .= '
    '; - if (empty($sectionid)) $out .= '
    '; + $out .= ''; + if (empty($sectionid)) $out .= '
    '; } $out .= "\n\n"; @@ -239,10 +236,10 @@ if (empty($usewithoutform)) { - $out .= '
    '; + $out .= '
    '; + $out .= '
    '; } $out .= "\n\n"; @@ -275,7 +272,7 @@ $res = $hookmanager->executeHooks('formattachOptions', $parameters, $object); if (empty($res)) { - print '
    '; + print '
    '; print $out; print '
    '; } @@ -285,7 +282,7 @@ } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show the box with list of available documents for object * @@ -310,7 +307,7 @@ */ public function show_documents($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '') { - // phpcs:enable + // phpcs:enable $this->numoffiles = 0; print $this->showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed, $modelselected, $allowgenifempty, $forcenomultilang, $iconPDF, $notused, $noform, $param, $title, $buttonlabel, $codelang); return $this->numoffiles; @@ -363,11 +360,11 @@ // Add entity in $param if not already exists if (!preg_match('/entity\=[0-9]+/', $param)) { - $param .= ($param ? '&' : '').'entity='.(!empty($object->entity) ? $object->entity : $conf->entity); + $param .= 'entity='.(!empty($object->entity) ? $object->entity : $conf->entity); } $printer = 0; - if (in_array($modulepart, array('facture', 'supplier_proposal', 'propal', 'proposal', 'order', 'commande', 'expedition', 'commande_fournisseur', 'expensereport', 'delivery', 'ticket'))) // The direct print feature is implemented only for such elements + if (in_array($modulepart, array('facture', 'supplier_proposal', 'propal', 'proposal', 'order', 'commande', 'expedition', 'commande_fournisseur', 'expensereport', 'livraison', 'ticket'))) // The direct print feature is implemented only for such elements { $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled)) ?true:false; } @@ -426,210 +423,264 @@ if ($modulepart == 'company') { - $showempty = 1; // can have no template active - if (is_array($genallowed)) $modellist = $genallowed; - else { + $showempty = 1; + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php'; $modellist = ModeleThirdPartyDoc::liste_modeles($this->db); } - } elseif ($modulepart == 'propal') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'propal') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php'; $modellist = ModelePDFPropales::liste_modeles($this->db); } - } elseif ($modulepart == 'supplier_proposal') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'supplier_proposal') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php'; $modellist = ModelePDFSupplierProposal::liste_modeles($this->db); } - } elseif ($modulepart == 'commande') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'commande') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; $modellist = ModelePDFCommandes::liste_modeles($this->db); } - } elseif ($modulepart == 'expedition') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'expedition') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; $modellist = ModelePDFExpedition::liste_modeles($this->db); } - } elseif ($modulepart == 'reception') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'reception') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php'; $modellist = ModelePdfReception::liste_modeles($this->db); } - } elseif ($modulepart == 'delivery') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { - include_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/modules_delivery.php'; + } + elseif ($modulepart == 'livraison') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php'; $modellist = ModelePDFDeliveryOrder::liste_modeles($this->db); } - } elseif ($modulepart == 'ficheinter') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'ficheinter') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; $modellist = ModelePDFFicheinter::liste_modeles($this->db); } - } elseif ($modulepart == 'facture') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'facture') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; $modellist = ModelePDFFactures::liste_modeles($this->db); } - } elseif ($modulepart == 'contract') - { - $showempty = 1; // can have no template active - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'contract') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; $modellist = ModelePDFContract::liste_modeles($this->db); } - } elseif ($modulepart == 'project') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'project') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; $modellist = ModelePDFProjects::liste_modeles($this->db); } - } elseif ($modulepart == 'project_task') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'project_task') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php'; $modellist = ModelePDFTask::liste_modeles($this->db); } - } elseif ($modulepart == 'product') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'product') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; $modellist = ModelePDFProduct::liste_modeles($this->db); } - } elseif ($modulepart == 'product_batch') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'product_batch') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/product_batch/modules_product_batch.class.php'; $modellist = ModelePDFProductBatch::liste_modeles($this->db); } - } elseif ($modulepart == 'stock') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'stock') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_stock.php'; $modellist = ModelePDFStock::liste_modeles($this->db); } - } elseif ($modulepart == 'movement') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'movement') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_movement.php'; $modellist = ModelePDFMovement::liste_modeles($this->db); } - } elseif ($modulepart == 'export') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'export') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; $modellist = ModeleExports::liste_modeles($this->db); } - } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php'; $modellist = ModelePDFSuppliersOrders::liste_modeles($this->db); } - } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { - $showempty = 1; // can have no template active - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; $modellist = ModelePDFSuppliersInvoices::liste_modeles($this->db); } - } elseif ($modulepart == 'supplier_payment') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'supplier_payment') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; $modellist = ModelePDFSuppliersPayments::liste_modeles($this->db); } - } elseif ($modulepart == 'remisecheque') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'remisecheque') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php'; $modellist = ModeleChequeReceipts::liste_modeles($this->db); } - } elseif ($modulepart == 'donation') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'donation') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php'; $modellist = ModeleDon::liste_modeles($this->db); } - } elseif ($modulepart == 'member') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'member') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php'; $modellist = ModelePDFCards::liste_modeles($this->db); } - } elseif ($modulepart == 'agenda' || $modulepart == 'actions') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'agenda' || $modulepart == 'actions') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php'; $modellist = ModeleAction::liste_modeles($this->db); } - } elseif ($modulepart == 'expensereport') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'expensereport') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; $modellist = ModeleExpenseReport::liste_modeles($this->db); } - } elseif ($modulepart == 'unpaid') + } + elseif ($modulepart == 'unpaid') { $modellist = ''; - } elseif ($modulepart == 'user') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'user') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php'; $modellist = ModelePDFUser::liste_modeles($this->db); } - } elseif ($modulepart == 'usergroup') - { - if (is_array($genallowed)) $modellist = $genallowed; - else { + } + elseif ($modulepart == 'usergroup') + { + if (is_array($genallowed)) $modellist = $genallowed; + else + { include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php'; $modellist = ModelePDFUserGroup::liste_modeles($this->db); } - } else { - $submodulepart = $modulepart; - - // modulepart = 'nameofmodule' or 'nameofmodule:NameOfObject' - $tmp = explode(':', $modulepart); - if (!empty($tmp[1])) { - $modulepart = $tmp[0]; - $submodulepart = $tmp[1]; - } - - // For normalized standard modules + } + else + { + $submodulepart = $modulepart; + + // modulepart = 'nameofmodule' or 'nameofmodule:NameOfObject' + $tmp = explode(':', $modulepart); + if (!empty($tmp[1])) { + $modulepart = $tmp[0]; + $submodulepart = $tmp[1]; + } + + // For normalized standard modules $file = dol_buildpath('/core/modules/'.$modulepart.'/modules_'.strtolower($submodulepart).'.php', 0); if (file_exists($file)) { @@ -637,7 +688,7 @@ } // For normalized external modules. else { - $file = dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.strtolower($submodulepart).'.php', 0); + $file = dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.strtolower($submodulepart).'.php', 0); $res = include_once $file; } @@ -646,7 +697,9 @@ if (class_exists($class)) { $modellist = call_user_func($class.'::liste_modeles', $this->db); - } else { + } + else + { dol_print_error($this->db, "Bad value for modulepart '".$modulepart."' in showdocuments"); return -1; } @@ -690,7 +743,9 @@ { $out .= ajax_combobox('model'); } - } else { + } + else + { $out .= '
    '.$langs->trans("Files").'
    '; } @@ -703,7 +758,9 @@ $morecss = 'maxwidth150'; if ($conf->browser->layout == 'phone') $morecss = 'maxwidth100'; $out .= $formadmin->select_language($defaultlang, 'lang_id', 0, null, 0, 0, 0, $morecss); - } else { + } + else + { $out .= ' '; } @@ -839,7 +896,9 @@ { $out .= $hookmanager->resPrint; // Complete line $out .= ''; - } else { + } + else + { $out = $hookmanager->resPrint; // Replace all $out } } @@ -925,7 +984,9 @@ if (!empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP)) { $filterforfilesearch = preg_quote(basename($modulesubdir), '/'); - } else { + } + else + { $filterforfilesearch = preg_quote(basename($modulesubdir), '/').'[^\-]+'; } $file_list = dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // We also discard .meta and .png preview @@ -992,7 +1053,9 @@ '; if (!$found) $out = ''; - } else { + } + else + { // TODO Add link to regenerate doc ? //$out.= '
    '.img_picto('', 'refresh').'
    '."\n"; } @@ -1001,7 +1064,7 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show list of documents in $filearray (may be they are all in same directory but may not) * This also sync database if $upload_dir is defined. @@ -1036,29 +1099,29 @@ */ public function list_of_documents($filearray, $object, $modulepart, $param = '', $forcedownload = 0, $relativepath = '', $permonobject = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $title = '', $url = '', $showrelpart = 0, $permtoeditline = -1, $upload_dir = '', $sortfield = '', $sortorder = 'ASC', $disablemove = 1, $addfilterfields = 0, $disablecrop = -1) { - // phpcs:enable - global $user, $conf, $langs, $hookmanager, $form; + // phpcs:enable + global $user, $conf, $langs, $hookmanager; global $sortfield, $sortorder, $maxheightmini; global $dolibarr_main_url_root; + global $form; if ($disablecrop == -1) { $disablecrop = 1; - // Values here must be supported by the photo_resize.php page. - if (in_array($modulepart, array('bank', 'bom', 'expensereport', 'facture', 'facture_fournisseur', 'holiday', 'medias', 'member', 'mrp', 'project', 'product', 'produit', 'propal', 'service', 'societe', 'tax', 'tax-vat', 'ticket', 'user'))) $disablecrop = 0; + if (in_array($modulepart, array('bank', 'bom', 'expensereport', 'holiday', 'medias', 'member', 'mrp', 'project', 'product', 'produit', 'propal', 'service', 'societe', 'tax', 'tax-vat', 'ticket', 'user'))) $disablecrop = 0; } // Define relative path used to store the file if (empty($relativepath)) { - $relativepath = (!empty($object->ref) ? dol_sanitizeFileName($object->ref) : '').'/'; + $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/'; if ($object->element == 'invoice_supplier') $relativepath = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath if ($object->element == 'project_task') $relativepath = 'Call_not_supported_._Call_function_using_a_defined_relative_path_.'; } // For backward compatiblity, we detect file stored into an old path if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos') { - $relativepath = preg_replace('/^.*\/produit\//', '', $filearray[0]['path']).'/'; + $relativepath = preg_replace('/^.*\/produit\//', '', $filearray[0]['path']).'/'; } // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; @@ -1090,7 +1153,9 @@ if (isset($reshook) && $reshook != '') // null or '' for bypass { return $reshook; - } else { + } + else + { if (!is_object($form)) { include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // The compoent may be included into ajax page that does not include the Form class @@ -1206,14 +1271,16 @@ { print ''; $section_dir = dirname(GETPOST('urlfile', 'alpha')); - if (!preg_match('/\/$/', $section_dir)) $section_dir .= '/'; + if (! preg_match('/\/$/', $section_dir)) $section_dir.='/'; print ''; print ''; print ''; $editline = 1; - } else { + } + else + { $filenametoshow = preg_replace('/\.noexe$/', '', $file['name']); - print dol_escape_htmltag(dol_trunc($filenametoshow, 200)); + print dol_trunc($filenametoshow, 200); print ''; } // Preview link @@ -1224,6 +1291,7 @@ // Size $sizetoshow = dol_print_size($file['size'], 1, 1); $sizetoshowbytes = dol_print_size($file['size'], 0, 1); + print ''; if ($sizetoshow == $sizetoshowbytes) print $sizetoshow; else { @@ -1241,13 +1309,15 @@ print ''; if (image_format_supported($file['name']) >= 0) { - if ($useinecm == 5 || $useinecm == 6) - { - $smallfile = getImageFileNameForSize($file['name'], ''); // There is no thumb for ECM module and Media filemanager, so we use true image. TODO Change this it is slow on image dir. - } else { - $smallfile = getImageFileNameForSize($file['name'], '_small'); // For new thumbs using same ext (in lower case however) than original - } - if (!dol_is_file($file['path'].'/'.$smallfile)) $smallfile = getImageFileNameForSize($file['name'], '_small', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension + if ($useinecm == 5 || $useinecm == 6) + { + $smallfile = getImageFileNameForSize($file['name'], ''); // There is no thumb for ECM module and Media filemanager, so we use true image. TODO Change this it is slow on image dir. + } + else + { + $smallfile = getImageFileNameForSize($file['name'], '_small'); // For new thumbs using same ext (in lower case however) than original + } + if (!dol_is_file($file['path'].'/'.$smallfile)) $smallfile = getImageFileNameForSize($file['name'], '_small', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension //print $file['path'].'/'.$smallfile.'
    '; $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); @@ -1257,9 +1327,10 @@ } else { print ''; } - print ''; + print ''; print ''; - } else print ' '; + } + else print ' '; print ''; } @@ -1271,7 +1342,9 @@ { print $langs->trans("FileSharedViaALink").' '; print ' '; - } else { + } + else + { if ($file['share']) { // Define $urlwithroot @@ -1289,7 +1362,9 @@ print img_picto($langs->trans("FileSharedViaALink"), 'globe').' '; print ''; - } else { + } + else + { //print ''.$langs->trans("FileNotShared").''; } } @@ -1305,9 +1380,9 @@ if ($useinecm == 1 || $useinecm == 5) // ECM manual tree only { // $section is inside $param - $newparam .= preg_replace('/&file=.*$/', '', $param); // We don't need param file= + $newparam.=preg_replace('/&file=.*$/', '', $param); // We don't need param file= $backtopage = DOL_URL_ROOT.'/ecm/index.php?§ion_dir='.urlencode($relativepath).$newparam; - print ''.img_edit('default', 0, 'class="paddingrightonly"').''; + print ''.img_edit('default', 0, 'class="paddingrightonly"').''; } if (empty($useinecm) || $useinecm == 2 || $useinecm == 6) // 6=Media file manager @@ -1333,7 +1408,7 @@ if ($permtoeditline) { $paramsectiondir = (in_array($modulepart, array('medias', 'ecm')) ? '§ion_dir='.urlencode($relativepath) : ''); - print ''.img_edit('default', 0, 'class="paddingrightonly"').''; + print ''.img_edit('default', 0, 'class="paddingrightonly"').''; } } if ($permonobject) @@ -1342,7 +1417,7 @@ if (!empty($conf->dol_use_jmobile)) $useajax = 0; if (empty($conf->use_javascript_ajax)) $useajax = 0; if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax = 0; - print ''.img_delete().''; + print ''.img_delete().''; } print ""; @@ -1357,16 +1432,19 @@ print 'id.'">'.img_down('default', 0, 'imgdownforline').''; } print ''; - } else { + } + else { print 'browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'>'; print ''; } - } - } else { + } + } + else + { print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; if (empty($disablemove)) print ''; } @@ -1406,11 +1484,11 @@ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Show list of documents in a directory of ECM module. + * Show list of documents in a directory * - * @param string $upload_dir Directory that was scanned. This directory will contains files into subdirs REF/files + * @param string $upload_dir Directory that was scanned * @param array $filearray Array of files loaded by dol_dir_list function before calling this function * @param string $modulepart Value for modulepart used by download wrapper * @param string $param Parameters on sort links @@ -1427,11 +1505,10 @@ */ public function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload = 0, $relativepath = '', $permissiontodelete = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $url = '', $addfilterfields = 0) { - // phpcs:enable - global $user, $conf, $langs, $hookmanager, $form; + // phpcs:enable + global $user, $conf, $langs, $form; global $sortfield, $sortorder; global $search_doc_ref; - global $dolibarr_main_url_root; dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart); @@ -1479,92 +1556,82 @@ { include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $object_instance = new Societe($this->db); - } elseif ($modulepart == 'invoice') + } + elseif ($modulepart == 'invoice') { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object_instance = new Facture($this->db); - } elseif ($modulepart == 'invoice_supplier') + } + elseif ($modulepart == 'invoice_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $object_instance = new FactureFournisseur($this->db); - } elseif ($modulepart == 'propal') + } + elseif ($modulepart == 'propal') { include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $object_instance = new Propal($this->db); - } elseif ($modulepart == 'supplier_proposal') + } + elseif ($modulepart == 'supplier_proposal') { include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; $object_instance = new SupplierProposal($this->db); - } elseif ($modulepart == 'order') + } + elseif ($modulepart == 'order') { include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $object_instance = new Commande($this->db); - } elseif ($modulepart == 'order_supplier') + } + elseif ($modulepart == 'order_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $object_instance = new CommandeFournisseur($this->db); - } elseif ($modulepart == 'contract') + } + elseif ($modulepart == 'contract') { include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; $object_instance = new Contrat($this->db); - } elseif ($modulepart == 'product') + } + elseif ($modulepart == 'product') { include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $object_instance = new Product($this->db); - } elseif ($modulepart == 'tax') + } + elseif ($modulepart == 'tax') { include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; $object_instance = new ChargeSociales($this->db); - } elseif ($modulepart == 'project') + } + elseif ($modulepart == 'project') { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $object_instance = new Project($this->db); - } elseif ($modulepart == 'fichinter') + } + elseif ($modulepart == 'fichinter') { include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; $object_instance = new Fichinter($this->db); - } elseif ($modulepart == 'user') + } + elseif ($modulepart == 'user') { include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $object_instance = new User($this->db); - } elseif ($modulepart == 'expensereport') + } + elseif ($modulepart == 'expensereport') { include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $object_instance = new ExpenseReport($this->db); - } elseif ($modulepart == 'holiday') + } + elseif ($modulepart == 'holiday') { include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; $object_instance = new Holiday($this->db); - } elseif ($modulepart == 'recruitment-recruitmentcandidature') - { - include_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentcandidature.class.php'; - $object_instance = new RecruitmentCandidature($this->db); - } elseif ($modulepart == 'banque') - { - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $object_instance = new Account($this->db); - } elseif ($modulepart == 'mrp-mo') - { - include_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php'; - $object_instance = new Mo($this->db); - } - - //var_dump($filearray); - - // Get list of files stored into database for same relative directory - $relativepathfromroot = preg_replace('/'.preg_quote(DOL_DATA_ROOT.'/', '/').'/', '', $upload_dir); - if ($relativepathfromroot) - { - completeFileArrayWithDatabaseInfo($filearray, $relativepathfromroot.'/%'); - - //var_dump($sortfield.' - '.$sortorder); - if ($sortfield && $sortorder) // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name) - { - $filearray = dol_sort_array($filearray, $sortfield, $sortorder); - } - } - - //var_dump($filearray); + } + elseif ($modulepart == 'banque') + { + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $object_instance = new Account($this->db); + } foreach ($filearray as $key => $file) { @@ -1577,30 +1644,19 @@ // Define relative path used to store the file $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']); - $id = 0; $ref = ''; + $id = 0; $ref = ''; $label = ''; // To show ref or specific information according to view to show (defined by $module) - $reg = array(); if ($modulepart == 'company' || $modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); } elseif ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); if (is_numeric($ref)) { $id = $ref; $ref = ''; } } // $ref may be also id with old supplier invoices elseif ($modulepart == 'user' || $modulepart == 'holiday') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); } - elseif (in_array($modulepart, array( - 'invoice', - 'propal', - 'supplier_proposal', - 'order', - 'order_supplier', - 'contract', - 'product', - 'project', - 'fichinter', - 'expensereport', - 'recruitment-recruitmentcandidature', - 'mrp-mo', - 'banque'))) { + elseif (in_array($modulepart, array('invoice', 'propal', 'supplier_proposal', 'order', 'order_supplier', 'contract', 'product', 'project', 'fichinter', 'expensereport', 'banque'))) + { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); - } else { - //print 'Error: Value for modulepart = '.$modulepart.' is not yet implemented in function list_of_autoecmfiles'."\n"; + } + else + { + //print 'Error: Value for modulepart = '.$modulepart.' is not yet implemented in function list_of_autoecmfiles'."\n"; } if (!$id && !$ref) continue; @@ -1608,8 +1664,10 @@ if (!empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) { $found = 1; - } else { - //print 'Fetch '.$id." - ".$ref.' class='.get_class($object_instance).'
    '; + } + else + { + //print 'Fetch '.$id." - ".$ref.'
    '; if ($id) { $result = $object_instance->fetch($id); @@ -1638,12 +1696,13 @@ else print $langs->trans("ObjectDeleted", ($id ? $id : $ref)); //$modulesubdir=dol_sanitizeFileName($ref); - //$modulesubdir = dirname($relativefile); + $modulesubdir = dirname($relativefile); //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref); - //$filedir = $file['path']; + $filedir = $file['path']; //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; //print $formfile->getDocumentsLink($modulepart, $filename, $filedir); + print ''; // File @@ -1657,48 +1716,17 @@ print ''; //print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$'); - print $this->showPreview($file, $modulepart, $file['relativename']); print "\n"; - - // Size - $sizetoshow = dol_print_size($file['size'], 1, 1); - $sizetoshowbytes = dol_print_size($file['size'], 0, 1); - print ''; - if ($sizetoshow == $sizetoshowbytes) print $sizetoshow; - else { - print $form->textwithpicto($sizetoshow, $sizetoshowbytes, -1); - } - print ''; - - // Date + print ''.dol_print_size($file['size'], 1, 1).''; print ''.dol_print_date($file['date'], "dayhour").''; - - // Share link print ''; - if ($file['share']) { - // Define $urlwithroot - $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - - //print ''.$langs->trans("Hash").' : '.$file['share'].''; - $forcedownload = 0; - $paramlink = ''; - if (!empty($file['share'])) $paramlink .= ($paramlink ? '&' : '').'hashp='.$file['share']; // Hash for public share - if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1'; - - $fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : ''); - - print img_picto($langs->trans("FileSharedViaALink"), 'globe').' '; - print ''; - } //if (! empty($useinecm) && $useinecm != 6) print ''; //print img_view().'   '; - //if ($permissiontodelete) print ''.img_delete().''; + //if ($permissiontodelete) print ''.img_delete().''; //else print ' '; print "\n"; } @@ -1782,14 +1810,14 @@ print ''."\n"; // Show list of associated links - print load_fiche_titre($langs->trans("LinkedFiles"), '', 'link', 0, '', 'table-list-of-links'); + print load_fiche_titre($langs->trans("LinkedFiles"), '', 'external-link-square-alt', 0, '', 'table-list-of-links'); print '
    '; print ''; print ''; print ''; - print_liste_field_titre( + print_liste_field_titre( $langs->trans("Links"), $_SERVER['PHP_SELF'], "name", @@ -1798,20 +1826,20 @@ '', $sortfield, $sortorder, - '' + '' ); - print_liste_field_titre( + print_liste_field_titre( "", "", "", "", "", '', - '', - '', - 'right ' + '', + '', + 'right ' ); - print_liste_field_titre( + print_liste_field_titre( $langs->trans("Date"), $_SERVER['PHP_SELF'], "date", @@ -1820,18 +1848,18 @@ '', $sortfield, $sortorder, - 'center ' + 'center ' ); - print_liste_field_titre( + print_liste_field_titre( '', $_SERVER['PHP_SELF'], "", "", $param, '', - '', - '', - 'center ' + '', + '', + 'center ' ); print_liste_field_titre('', '', ''); print ''; @@ -1856,10 +1884,12 @@ print ''; print ''; print ''; - } else { + } + else + { print '
    '.dol_print_date(dol_now(), "dayhour", "tzuser").''; - print ''; - print ''; + print ''; + print ''; print ''; print img_picto('', 'globe').' '; print ''; @@ -1872,7 +1902,7 @@ print ''; print ''.img_edit().''; // id= is included into $param if ($permissiontodelete) { - print '   '.img_delete().''; // id= is included into $param + print '   '.img_delete().''; // id= is included into $param } else { print ' '; } @@ -1916,12 +1946,12 @@ { $out .= ''; //$out.= ''; - if (empty($ruleforpicto)) { + if (empty($ruleforpicto)) + { //$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); $out .= ''; - } else { - $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); - } + } + else $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); $out .= ''; } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formintervention.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formintervention.class.php @@ -27,29 +27,29 @@ */ class FormIntervention { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** + /** * @var string Error code (or message) */ public $error = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show a combo list with contracts qualified for a third party * @@ -62,7 +62,7 @@ */ public function select_interventions($socid = -1, $selected = '', $htmlname = 'interventionid', $maxlength = 16, $showempty = 1) { - // phpcs:enable + // phpcs:enable global $db, $user, $conf, $langs; $out = ''; @@ -80,28 +80,32 @@ } dol_syslog(get_class($this)."::select_intervention", LOG_DEBUG); - $resql = $this->db->query($sql); + $resql = $db->query($sql); if ($resql) { $out .= ''."\n"; - } + $out .= ''."\n"; } $modelmail_array = array(); @@ -434,33 +428,29 @@ { setEventMessages($this->error, $this->errors, 'errors'); } - $langs->trans("members"); foreach ($this->lines_model as $line) { - $reg = array(); - if (preg_match('/\((.*)\)/', $line->label, $reg)) { - $labeltouse = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__ - } else { - $labeltouse = $line->label; - } - - // We escape the $labeltouse to store it into $modelmail_array. - $modelmail_array[$line->id] = dol_escape_htmltag($labeltouse); - if ($line->lang) $modelmail_array[$line->id] .= ' '.picto_from_langcode($line->lang); - if ($line->private) $modelmail_array[$line->id] .= ' - '.dol_escape_htmltag($langs->trans("Private")).''; + $langs->trans("members"); + if (preg_match('/\((.*)\)/', $line->label, $reg)) + { + $modelmail_array[$line->id] = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__ + } + else + { + $modelmail_array[$line->id] = $line->label; + } + if ($line->lang) $modelmail_array[$line->id] .= ' ('.$line->lang.')'; + if ($line->private) $modelmail_array[$line->id] .= ' - '.$langs->trans("Private"); + //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' '; } } // Zone to select email template if (count($modelmail_array) > 0) { - $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ($arraydefaultmessage->id > 0 ? $arraydefaultmessage->id : 0); - // If list of template is filled $out .= '
    '."\n"; - - $out .= ''.$langs->trans('SelectMailModel').': '; - $out .= $this->selectarray('modelmailselected', $modelmail_array, $model_mail_selected_id, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100', 1, '', 0, 1); + $out .= ''.$langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100'); if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1); $out .= '   '; $out .= ''; @@ -469,8 +459,8 @@ } elseif (!empty($this->param['models']) && in_array($this->param['models'], array( 'propal_send', 'order_send', 'facture_send', 'shipping_send', 'fichinter_send', 'supplier_proposal_send', 'order_supplier_send', - 'invoice_supplier_send', 'thirdparty', 'contract', 'user', 'recruitmentcandidature_send', 'all' - ))) + 'invoice_supplier_send', 'thirdparty', 'contract', 'user', 'all' + ))) { // If list of template is empty $out .= '
    '."\n"; @@ -480,9 +470,8 @@ $out .= ''; $out .= '   '; $out .= '
    '; - } else { - $out .= ''; - } + } + $out .= ''."\n"; @@ -492,7 +481,7 @@ if (is_array($this->substit) && count($this->substit)) $helpforsubstitution .= $langs->trans('AvailableVariables').' :
    '."\n"; foreach ($this->substit as $key => $val) { - $helpforsubstitution .= $key.' -> '.$langs->trans(dol_string_nohtmltag(dolGetFirstLineOfText($val))).'
    '; + $helpforsubstitution .= $key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'
    '; } if (!empty($this->withsubstit)) // Unset or set ->withsubstit=0 to disable this. { @@ -530,7 +519,9 @@ if ($this->frommail) { $out .= ' <'.$this->frommail.'>'; - } else { + } + else + { if ($this->fromtype) { $langs->load('errors'); @@ -545,7 +536,9 @@ { $langs->load('errors'); $liste['user'] = $user->getFullName($langs).' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'>'; - } else { + } + else + { $liste['user'] = $user->getFullName($langs).' <'.$user->email.'>'; } @@ -586,7 +579,8 @@ } $i++; } - } else dol_print_error($this->db); + } + else dol_print_error($this->db); foreach ($listaliases as $typealias => $listalias) { @@ -621,7 +615,9 @@ } $out .= "\n"; - } else { + } + else + { $out .= '\n"; return $out; @@ -1159,7 +1157,7 @@ { global $conf, $langs, $form; - $defaulttopic = GETPOST('subject', 'restricthtml'); + $defaulttopic = GETPOST('subject', 'none'); if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') { if ($arraydefaultmessage && $arraydefaultmessage->topic) { $defaulttopic = $arraydefaultmessage->topic; @@ -1179,7 +1177,7 @@ $out .= $defaulttopic; $out .= ''; } else { - $out .= ''; + $out .= ''; } $out .= "\n"; return $out; @@ -1200,9 +1198,7 @@ */ public function getEMailTemplate($db, $type_template, $user, $outputlangs, $id = 0, $active = 1, $label = '') { - global $conf; - - $ret = new ModelMail(); + $ret = new ModelMail(); if ($id == -2 && empty($label)) { $this->error = 'LabelIsMandatoryWhenIdIs-2'; @@ -1215,7 +1211,7 @@ $languagetosearchmain = $tmparray[0].'_'.strtoupper($tmparray[0]); if ($languagetosearchmain == $languagetosearch) $languagetosearchmain = ''; - $sql = "SELECT rowid, module, label, type_template, topic, joinfiles, content, content_lines, lang"; + $sql = "SELECT rowid, label, topic, joinfiles, content, content_lines, lang"; $sql .= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; $sql .= " WHERE (type_template='".$db->escape($type_template)."' OR type_template='all')"; $sql .= " AND entity IN (".getEntity('c_email_templates').")"; @@ -1227,92 +1223,60 @@ if ($id == -1) $sql .= " AND position=0"; if ($languagetosearch) $sql .= $db->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or '' else $sql .= $db->order("position,lang,label", "ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined - //$sql .= $db->plimit(1); + $sql .= $db->plimit(1); //print $sql; $resql = $db->query($sql); - if (!$resql) + if ($resql) { - dol_print_error($db); - return -1; - } - - // Get first found - while (1) { + // Get first found $obj = $db->fetch_object($resql); if ($obj) { - // If template is for a module, check module is enabled; if not, take next template - if ($obj->module) { - $tempmodulekey = $obj->module; - if (empty($conf->$tempmodulekey) || empty($conf->$tempmodulekey->enabled)) { - continue; - } - } - - // If a record was found $ret->id = $obj->rowid; - $ret->module = $obj->module; $ret->label = $obj->label; $ret->lang = $obj->lang; $ret->topic = $obj->topic; $ret->content = $obj->content; $ret->content_lines = $obj->content_lines; $ret->joinfiles = $obj->joinfiles; - - break; - } else { - // If no record found - if ($id == -2) { - // Not found with the provided label - return -1; - } else { - // If there is no template at all - $defaultmessage = ''; - - if ($type_template == 'body') { - // Special case to use this->withbody as content - $defaultmessage = $this->withbody; - } elseif ($type_template == 'facture_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoice"); - } elseif ($type_template == 'facture_relance') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); - } elseif ($type_template == 'propal_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendProposal"); - } elseif ($type_template == 'supplier_proposal_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); - } elseif ($type_template == 'order_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendOrder"); - } elseif ($type_template == 'order_supplier_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); - } elseif ($type_template == 'invoice_supplier_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); - } elseif ($type_template == 'shipping_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendShipping"); - } elseif ($type_template == 'fichinter_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendFichInter"); - } elseif ($type_template == 'actioncomm_send') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendActionComm"); - } elseif ($type_template == 'thirdparty') { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentThirdparty"); - } elseif (!empty($type_template)) { - $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentGeneric"); - } - - $ret->label = 'default'; - $ret->lang = $outputlangs->defaultlang; - $ret->topic = ''; - $ret->joinfiles = 1; - $ret->content = $defaultmessage; - $ret->content_lines = ''; - - break; - } - } - } - - $db->free($resql); - return $ret; + } + elseif ($id == -2) { + // Not found with the provided label + return -1; + } + else { // If there is no template at all + $defaultmessage = ''; + if ($type_template == 'body') { $defaultmessage = $this->withbody; } // Special case to use this->withbody as content + elseif ($type_template == 'facture_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoice"); } + elseif ($type_template == 'facture_relance') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); } + elseif ($type_template == 'propal_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendProposal"); } + elseif ($type_template == 'supplier_proposal_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); } + elseif ($type_template == 'order_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendOrder"); } + elseif ($type_template == 'order_supplier_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); } + elseif ($type_template == 'invoice_supplier_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); } + elseif ($type_template == 'shipping_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendShipping"); } + elseif ($type_template == 'fichinter_send') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendFichInter"); } + elseif ($type_template == 'thirdparty') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentThirdparty"); } + elseif ($type_template == 'user') { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentUser"); } + elseif (!empty($type_template)) { $defaultmessage = $outputlangs->transnoentities("PredefinedMailContent".ucfirst($type_template)); } + + $ret->label = 'default'; + $ret->lang = $outputlangs->defaultlang; + $ret->topic = ''; + $ret->joinfiles = 1; + $ret->content = $defaultmessage; + $ret->content_lines = ''; + } + + $db->free($resql); + return $ret; + } + else + { + dol_print_error($db); + return -1; + } } /** @@ -1326,12 +1290,14 @@ */ public function isEMailTemplate($type_template, $user, $outputlangs) { + $ret = array(); + $sql = "SELECT label, topic, content, lang"; $sql .= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; $sql .= " WHERE type_template='".$this->db->escape($type_template)."'"; $sql .= " AND entity IN (".getEntity('c_email_templates').")"; $sql .= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".$user->id.")"; - if (is_object($outputlangs)) $sql .= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')"; + if (is_object($outputlangs)) $sql .= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')"; $sql .= $this->db->order("lang,label", "ASC"); //print $sql; @@ -1341,7 +1307,9 @@ $num = $this->db->num_rows($resql); $this->db->free($resql); return $num; - } else { + } + else + { $this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror(); return -1; } @@ -1359,15 +1327,15 @@ */ public function fetchAllEMailTemplate($type_template, $user, $outputlangs, $active = 1) { - global $conf; - - $sql = "SELECT rowid, module, label, topic, content, content_lines, lang, fk_user, private, position"; + $ret = array(); + + $sql = "SELECT rowid, label, topic, content, content_lines, lang, fk_user, private, position"; $sql .= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; $sql .= " WHERE type_template IN ('".$this->db->escape($type_template)."', 'all')"; $sql .= " AND entity IN (".getEntity('c_email_templates').")"; $sql .= " AND (private = 0 OR fk_user = ".$user->id.")"; // See all public templates or templates I own. if ($active >= 0) $sql .= " AND active = ".$active; - //if (is_object($outputlangs)) $sql.= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')"; // Return all languages + //if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')"; // Return all languages $sql .= $this->db->order("position,lang,label", "ASC"); //print $sql; @@ -1378,14 +1346,6 @@ $this->lines_model = array(); while ($obj = $this->db->fetch_object($resql)) { - // If template is for a module, check module is enabled. - if ($obj->module) { - $tempmodulekey = $obj->module; - if (empty($conf->$tempmodulekey) || empty($conf->$tempmodulekey->enabled)) { - continue; - } - } - $line = new ModelMail(); $line->id = $obj->rowid; $line->label = $obj->label; @@ -1401,7 +1361,9 @@ } $this->db->free($resql); return $num; - } else { + } + else + { $this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror(); return -1; } @@ -1419,7 +1381,7 @@ */ public function setSubstitFromObject($object, $outputlangs) { - global $conf, $user, $extrafields; + global $conf, $user; $parameters = array(); $tmparray = getCommonSubstitutionArray($outputlangs, 0, null, $object); @@ -1531,7 +1493,9 @@ if ($conf->commande->enabled) $tmparray['__SECUREKEYPAYMENT_ORDER__'] = 'SecureKeyPAYMENTUniquePerOrder'; if ($conf->contrat->enabled) $tmparray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'SecureKeyPAYMENTUniquePerContractLine'; } - } else { + } + else + { /* No need to show into tooltip help, option is not enabled $vars['__SECUREKEYPAYMENT__']=''; $vars['__SECUREKEYPAYMENT_MEMBER__']=''; @@ -1563,9 +1527,9 @@ public $id; /** - * @var string Model mail label - */ - public $label; + * @var string Model mail label + */ + public $label; public $topic; public $content; --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formmailing.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formmailing.class.php @@ -27,36 +27,36 @@ */ class FormMailing extends Form { - /** - * @var string[] Error codes (or messages) - */ - public $errors = array(); + /** + * @var string[] Error codes (or messages) + */ + public $errors = array(); - /** - * Output a select with destinaries status - * - * @param string $selectedid The selected id - * @param string $htmlname Name of controm - * @param integer $show_empty Show empty option - * @return string HTML select - */ - public function selectDestinariesStatus($selectedid = '', $htmlname = 'dest_status', $show_empty = 0) - { + /** + * Output a select with destinaries status + * + * @param string $selectedid The selected id + * @param string $htmlname Name of controm + * @param integer $show_empty Show empty option + * @return string HTML select + */ + public function selectDestinariesStatus($selectedid = '', $htmlname = 'dest_status', $show_empty = 0) + { - global $langs; - $langs->load("mails"); + global $langs; + $langs->load("mails"); - require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php'; - $mailing = new Mailing($this->db); + require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php'; + $mailing = new Mailing($this->db); - $options = array(); + $options = array(); - if ($show_empty) { - $options[-2] = ''; // Note -1 is used for error - } + if ($show_empty) { + $options[-2] = ''; // Note -1 is used for error + } - $options = $options + $mailing->statut_dest; + $options = $options + $mailing->statut_dest; - return Form::selectarray($htmlname, $options, $selectedid, 0, 0, 0, '', 1); - } + return Form::selectarray($htmlname, $options, $selectedid, 0, 0, 0, '', 1); + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formmargin.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formmargin.class.php @@ -28,26 +28,26 @@ */ class FormMargin { - /** - * @var DoliDB Database handler. - */ - public $db; - - /** + /** + * @var DoliDB Database handler. + */ + public $db; + + /** * @var string Error code (or message) */ public $error = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } @@ -87,7 +87,7 @@ if (empty($line->pa_ht) && isset($line->fk_fournprice) && !$force_price) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; - $product = new ProductFournisseur($this->db); + $product = new ProductFournisseur($db); if ($product->fetch_product_fournisseur_price($line->fk_fournprice)) $line->pa_ht = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100); } @@ -118,7 +118,8 @@ //} //else $marginInfos['margin_on_products'] += $pv - $pa; - } elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service + } + elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '2') { // remise globale considérée comme service $marginInfos['pa_services'] += $pa; $marginInfos['pv_services'] += $pv; $marginInfos['pa_total'] += $pa; @@ -128,11 +129,13 @@ // $marginInfos['margin_on_services'] += -1 * (abs($pv) - $pa); //else $marginInfos['margin_on_services'] += $pv - $pa; - } elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total - $marginInfos['pa_total'] += $pa; - $marginInfos['pv_total'] += $pv; - } - } else { + } + elseif ($conf->global->MARGIN_METHODE_FOR_DISCOUNT == '3') { // remise globale prise en compte uniqt sur total + $marginInfos['pa_total'] += $pa; + $marginInfos['pv_total'] += $pv; + } + } + else { $type = $line->product_type ? $line->product_type : $line->fk_product_type; if ($type == 0) { // product $marginInfos['pa_products'] += $pa; @@ -146,9 +149,10 @@ //} //else //{ - $marginInfos['margin_on_products'] += $pv - $pa; + $marginInfos['margin_on_products'] += $pv - $pa; //} - } elseif ($type == 1) { // service + } + elseif ($type == 1) { // service $marginInfos['pa_services'] += $pa; $marginInfos['pv_services'] += $pv; $marginInfos['pa_total'] += $pa; @@ -195,24 +199,24 @@ { global $langs, $conf, $user; - if (!empty($user->socid)) return; - - if (!$user->rights->margins->liretous) return; + if (!empty($user->socid)) return; + + if (!$user->rights->margins->liretous) return; $marginInfo = $this->getMarginInfosArray($object, $force_price); 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 { print $langs->trans('ShowMarginInfos').' : '; - $hidemargininfos = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW']); // Clean cookie - print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; - print ''.img_picto($langs->trans("Enabled"), 'switch_on').''; - - print ''; - if (!empty($hidemargininfos)) print ''; + if (!empty($hidemargininfos)) print ''; } print '
    '; @@ -224,7 +228,8 @@ print '
    '; if ($conf->global->MARGIN_TYPE == "1") print ''; - else print ''; + else + print ''; print ''; if (!empty($conf->global->DISPLAY_MARGIN_RATES)) print ''; --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formorder.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formorder.class.php @@ -31,42 +31,39 @@ class FormOrder extends Form { - /** - * Return combo list of differents status of a orders - * - * @param string $selected Preselected value - * @param int $short Use short labels - * @param string $hmlname Name of HTML select element - * @return void - */ - public function selectSupplierOrderStatus($selected = '', $short = 0, $hmlname = 'order_status') - { - $options = array(); + /** + * Return combo list of differents status of a orders + * + * @param string $selected Preselected value + * @param int $short Use short labels + * @param string $hmlname Name of HTML select element + * @return void + */ + public function selectSupplierOrderStatus($selected = '', $short = 0, $hmlname = 'order_status') + { + $options = array(); - // 7 is same label than 6. 8 does not exists (billed is another field) - $statustohow = array( - '0' => '0', - '1' => '1', - '2' => '2', - '3' => '3', - '4' => '4', - '5' => '5', - '6' => '6,7', - '9' => '9' - ); + // 7 is same label than 6. 8 does not exists (billed is another field) + $statustohow = array( + '0' => '0', + '1' => '1', + '2' => '2', + '3' => '3', + '4' => '4', + '5' => '5', + '6' => '6,7', + '9' => '9' + ); - $tmpsupplierorder = new CommandeFournisseur($this->db); + $tmpsupplierorder = new CommandeFournisseur($this->db); - foreach ($statustohow as $key => $value) { - $tmpsupplierorder->statut = $key; - $options[$value] = $tmpsupplierorder->getLibStatut($short); - } + foreach ($statustohow as $key => $value) { + $tmpsupplierorder->statut = $key; + $options[$value] = $tmpsupplierorder->getLibStatut($short); + } - if (is_array($selected)) $selectedarray = $selected; - else $selectedarray = explode(',', $selected); - - print Form::multiselectarray($hmlname, $options, $selectedarray, 0); - } + print Form::selectarray($hmlname, $options, $selected, 1); + } /** * Return list of input method (mode used to receive order, like order received by email, fax, online) @@ -81,7 +78,7 @@ { global $langs; - $listofmethods = array(); + $listofmethods = array(); $sql = "SELECT rowid, code, libelle as label"; $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method"; --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formother.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formother.class.php @@ -38,776 +38,769 @@ */ class FormOther { - private $db; - - /** + private $db; + + /** * @var string Error code (or message) */ public $error; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML select list of export models - * - * @param string $selected Id modele pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $type Type des modeles recherches - * @param int $useempty Show an empty value in list - * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) - * @return void - */ - public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null) - { - // phpcs:enable - global $conf, $langs, $user; - - $sql = "SELECT rowid, label, fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; - $sql .= " WHERE type = '".$this->db->escape($type)."'"; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML select list of export models + * + * @param string $selected Id modele pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $type Type des modeles recherches + * @param int $useempty Show an empty value in list + * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) + * @return void + */ + public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null) + { + // phpcs:enable + global $conf, $langs, $user; + + $sql = "SELECT rowid, label, fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; + $sql .= " WHERE type = '".$this->db->escape($type)."'"; if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql .= " ORDER BY label"; - $result = $this->db->query($sql); - if ($result) - { - print '"; - print ajax_combobox($htmlname); - } else { - dol_print_error($this->db); - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of export models - * - * @param string $selected Id modele pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $type Type des modeles recherches - * @param int $useempty Affiche valeur vide dans liste - * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) - * @return void - */ - public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null) - { - // phpcs:enable - global $conf, $langs, $user; - - $sql = "SELECT rowid, label, fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."import_model"; - $sql .= " WHERE type = '".$this->db->escape($type)."'"; - if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql .= " ORDER BY rowid"; - $result = $this->db->query($sql); - if ($result) - { - print '"; - print ajax_combobox($htmlname); - } else { - dol_print_error($this->db); - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of ecotaxes with label - * - * @param string $selected Preselected ecotaxes - * @param string $htmlname Name of combo list - * @return integer - */ - public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id') - { - // phpcs:enable - global $langs; - - $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; - $sql .= " c.label as country"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; - $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; - - dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - print ''; - return 0; - } else { - dol_print_error($this->db); - return 1; - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of revenue stamp for country - * - * @param string $selected Value of preselected revenue stamp - * @param string $htmlname Name of combo list - * @param string $country_code Country Code - * @return string HTML select list - */ - public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '') - { - // phpcs:enable - global $langs; - - $out = ''; - - $sql = "SELECT r.taux, r.revenuestamp_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid"; - $sql .= " AND c.code = '".$this->db->escape($country_code)."'"; - - dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $out .= ''; - return $out; - } else { - dol_print_error($this->db); - return ''; - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select list to select a percent - * - * @param integer $selected pourcentage pre-selectionne - * @param string $htmlname nom de la liste deroulante - * @param int $disabled Disabled or not - * @param int $increment increment value - * @param int $start start value - * @param int $end end value - * @param int $showempty Add also an empty line - * @return string HTML select string - */ - public function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0) - { - // phpcs:enable - $return = ''; - - return $return; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return select list for categories (to use in form search selectors) - * - * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. - * @param integer $selected Preselected value - * @param string $htmlname Name of combo list - * @param int $nocateg Show also an entry "Not categorized" - * @param int $showempty Add also an empty line - * @param string $morecss More CSS - * @return string Html combo list code - * @see select_all_categories() - */ - public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '') - { - // phpcs:enable - global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - - // For backward compatibility - if (is_numeric($type)) - { - dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); - } - - // Load list of "categories" - $static_categs = new Categorie($this->db); - $tab_categs = $static_categs->get_full_arbo($type); - - $moreforfilter = ''; - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox('select_categ_'.$htmlname); - $moreforfilter .= $comboenhancement; - } - - // Print a select with each of them - $moreforfilter .= ''; - - return $moreforfilter; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return select list for categories (to use in form search selectors) - * - * @param string $selected Preselected value - * @param string $htmlname Name of combo list (example: 'search_sale') - * @param User $user Object user - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param int $showempty 1=show also an empty value - * @param string $morecss More CSS - * @param int $norepresentative Show also an entry "Not categorized" - * @return string Html combo list code - */ - public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) - { - // phpcs:enable - global $conf, $langs, $hookmanager; - - $langs->load('users'); - - $out = ''; - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - - $comboenhancement = ajax_combobox($htmlname); - if ($comboenhancement) - { - $out .= $comboenhancement; - } - } - - $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectSalesRep', array(), $this, $action); - - // Select each sales and print them in a select input - $out .= ''; + if ($useempty) + { + print ''; + } + + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + + $label = $obj->label; + if ($obj->fk_user == 0) { + $label .= ' ('.$langs->trans("Everybody").')'; + } + elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { + $tmpuser = new User($this->db); + $tmpuser->fetch($obj->fk_user); + $label .= ' ('.$tmpuser->getFullName($langs).')'; + } + + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + print ajax_combobox($htmlname); + } + else { + dol_print_error($this->db); + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of export models + * + * @param string $selected Id modele pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $type Type des modeles recherches + * @param int $useempty Affiche valeur vide dans liste + * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) + * @return void + */ + public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null) + { + // phpcs:enable + global $conf, $langs, $user; + + $sql = "SELECT rowid, label, fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."import_model"; + $sql .= " WHERE type = '".$this->db->escape($type)."'"; + if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model + $sql .= " ORDER BY rowid"; + $result = $this->db->query($sql); + if ($result) + { + print '"; + print ajax_combobox($htmlname); + } + else { + dol_print_error($this->db); + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of ecotaxes with label + * + * @param string $selected Preselected ecotaxes + * @param string $htmlname Name of combo list + * @return integer + */ + public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id') + { + // phpcs:enable + global $langs; + + $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; + $sql .= " c.label as country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; + $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; + + dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + print ''; + return 0; + } + else + { + dol_print_error($this->db); + return 1; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of revenue stamp for country + * + * @param string $selected Value of preselected revenue stamp + * @param string $htmlname Name of combo list + * @param string $country_code Country Code + * @return string HTML select list + */ + public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '') + { + // phpcs:enable + global $langs; + + $out = ''; + + $sql = "SELECT r.taux, r.revenuestamp_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid"; + $sql .= " AND c.code = '".$country_code."'"; + + dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $out .= ''; + return $out; + } + else + { + dol_print_error($this->db); + return ''; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return a HTML select list to select a percent + * + * @param integer $selected pourcentage pre-selectionne + * @param string $htmlname nom de la liste deroulante + * @param int $disabled Disabled or not + * @param int $increment increment value + * @param int $start start value + * @param int $end end value + * @param int $showempty Add also an empty line + * @return string HTML select string + */ + public function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0) + { + // phpcs:enable + $return = ''; + + return $return; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return select list for categories (to use in form search selectors) + * + * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. + * @param integer $selected Preselected value + * @param string $htmlname Name of combo list + * @param int $nocateg Show also an entry "Not categorized" + * @param int $showempty Add also an empty line + * @param string $morecss More CSS + * @return string Html combo list code + * @see select_all_categories() + */ + public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '') + { + // phpcs:enable + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + + // For backward compatibility + if (is_numeric($type)) + { + dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + } + + // Load list of "categories" + $static_categs = new Categorie($this->db); + $tab_categs = $static_categs->get_full_arbo($type); + + $moreforfilter = ''; + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox('select_categ_'.$htmlname); + $moreforfilter .= $comboenhancement; + } + + // Print a select with each of them + $moreforfilter .= ''; + + return $moreforfilter; + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return select list for categories (to use in form search selectors) + * + * @param string $selected Preselected value + * @param string $htmlname Name of combo list (example: 'search_sale') + * @param User $user Object user + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param int $showempty 1=show also an empty value + * @param string $morecss More CSS + * @param int $norepresentative Show also an entry "Not categorized" + * @return string Html combo list code + */ + public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) + { + // phpcs:enable + global $conf, $langs, $hookmanager; + + $langs->load('users'); + + $out = ''; + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + + $comboenhancement = ajax_combobox($htmlname); + if ($comboenhancement) + { + $out .= $comboenhancement; + } + } + + $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectSalesRep', array(), $this, $action); + + // Select each sales and print them in a select input + $out .= ''; - - return $out; - } - - /** - * Return list of project and tasks - * - * @param int $selectedtask Pre-selected task - * @param int $projectid Project id - * @param string $htmlname Name of html select - * @param int $modeproject 1 to restrict on projects owned by user - * @param int $modetask 1 to restrict on tasks associated to user - * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists - * @param int $useempty 0=Allow empty values - * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id + $out .= ''; + } + $this->db->free($resql_usr); + } + else + { + dol_print_error($this->db); + } + + if ($norepresentative) + { + $langs->load("companies"); + $out .= ''; + } + + $out .= ''; + + return $out; + } + + /** + * Return list of project and tasks + * + * @param int $selectedtask Pre-selected task + * @param int $projectid Project id + * @param string $htmlname Name of html select + * @param int $modeproject 1 to restrict on projects owned by user + * @param int $modetask 1 to restrict on tasks associated to user + * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists + * @param int $useempty 0=Allow empty values + * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id * @param string $filteronprojstatus Filter on project status ('-1'=no filter, '0,1'=Draft+Validated status) - * @param string $morecss More css - * @return void - */ - public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '') - { - global $user, $langs; - - require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - - //print $modeproject.'-'.$modetask; - $task = new Task($this->db); - $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); - if ($tasksarray) - { - print ''; - - print ajax_combobox($htmlname); - } else { - print '
    '.$langs->trans("NoProject").'
    '; - } - } - - /** - * Write lines of a project (all lines of a project if parent = 0) - * - * @param int $inc Cursor counter - * @param int $parent Id of parent task we want to see - * @param array $lines Array of task lines - * @param int $level Level - * @param int $selectedtask Id selected task - * @param int $selectedproject Id selected project - * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id - * @return void - */ - private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0) - { - global $langs, $user, $conf; - - $lastprojectid = 0; - - $numlines = count($lines); - for ($i = 0; $i < $numlines; $i++) { - if ($lines[$i]->fk_parent == $parent) { - //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines - - // Break on a new project - if ($parent == 0) // We are on a task at first level - { - if ($lines[$i]->fk_project != $lastprojectid) // Break found on project - { - if ($i > 0) print ''; - print '\n"; - - $lastprojectid = $lines[$i]->fk_project; - $inc++; - } - } - - $newdisablechildoftaskid = $disablechildoftaskid; - - // Print task - if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 - { - // Check if we must disable entry - $disabled = 0; - if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) - { - $disabled++; - if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too - } - - print '\n"; - $inc++; - } - - $level++; - if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid); - $level--; - } - } - } - - - /** - * Output a HTML thumb of color or a text if not defined. - * - * @param string $color String with hex (FFFFFF) or comma RGB ('255,255,255') - * @param string $textifnotdefined Text to show if color not defined - * @return string HTML code for color thumb - * @see selectColor() - */ - public static function showColor($color, $textifnotdefined = '') - { - $textcolor = 'FFF'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if (colorIsLight($color)) $textcolor = '000'; - - $color = colorArrayToHex(colorStringToArray($color, array()), ''); + * @param string $morecss More css + * @return void + */ + public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '') + { + global $user, $langs; + + require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + + //print $modeproject.'-'.$modetask; + $task = new Task($this->db); + $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); + if ($tasksarray) + { + print ''; + + print ajax_combobox($htmlname); + } + else + { + print '
    '.$langs->trans("NoProject").'
    '; + } + } + + /** + * Write lines of a project (all lines of a project if parent = 0) + * + * @param int $inc Cursor counter + * @param int $parent Id of parent task we want to see + * @param array $lines Array of task lines + * @param int $level Level + * @param int $selectedtask Id selected task + * @param int $selectedproject Id selected project + * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id + * @return void + */ + private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0) + { + global $langs, $user, $conf; + + $lastprojectid = 0; + + $numlines = count($lines); + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_parent == $parent) { + //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines + + // Break on a new project + if ($parent == 0) // We are on a task at first level + { + if ($lines[$i]->fk_project != $lastprojectid) // Break found on project + { + if ($i > 0) print ''; + print '\n"; + + $lastprojectid = $lines[$i]->fk_project; + $inc++; + } + } + + $newdisablechildoftaskid = $disablechildoftaskid; + + // Print task + if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 + { + // Check if we must disable entry + $disabled = 0; + if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) + { + $disabled++; + if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too + } + + print '\n"; + $inc++; + } + + $level++; + if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid); + $level--; + } + } + } + + + /** + * Output a HTML thumb of color or a text if not defined. + * + * @param string $color String with hex (FFFFFF) or comma RGB ('255,255,255') + * @param string $textifnotdefined Text to show if color not defined + * @return string HTML code for color thumb + * @see selectColor() + */ + public static function showColor($color, $textifnotdefined = '') + { + $textcolor = 'FFF'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + if (colorIsLight($color)) $textcolor = '000'; + + $color = colorArrayToHex(colorStringToArray($color, array()), ''); if ($color) print ''; else print $textifnotdefined; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output a HTML code to select a color - * - * @param string $set_color Pre-selected color - * @param string $prefix Name of HTML field - * @param string $form_name Deprecated. Not used. - * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code - * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') - * @return void - * @deprecated Use instead selectColor - * @see selectColor() - */ - public function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '') - { - // phpcs:enable - print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors); - } - - /** - * Output a HTML code to select a color. Field will return an hexa color like '334455'. - * - * @param string $set_color Pre-selected color - * @param string $prefix Name of HTML field - * @param string $form_name Deprecated. Not used. - * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code - * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') - * @param string $morecss Add css style into input field - * @param string $setpropertyonselect Set this property after selecting a color - * @return string - * @see showColor() - */ - public static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '', $setpropertyonselect = '') - { - // Deprecation warning - if ($form_name) { - dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING); - } - - global $langs, $conf; - - $out = ''; - - if (!is_array($arrayofcolors) || count($arrayofcolors) < 1) - { - $langs->load("other"); - if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax)) - { - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; - } - $out .= ''; - } else // In most cases, this is not used. We used instead function with no specific list of colors - { - if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax)) - { - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; - } - $out .= ''; - } - - return $out; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Creation d'un icone de couleur - * - * @param string $color Couleur de l'image - * @param string $module Nom du module - * @param string $name Nom de l'image - * @param int $x Largeur de l'image en pixels - * @param int $y Hauteur de l'image en pixels - * @return void - */ - public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12') - { - // phpcs:enable - global $conf; - - $file = $conf->$module->dir_temp.'/'.$name.'.png'; - - // On cree le repertoire contenant les icones - if (!file_exists($conf->$module->dir_temp)) - { - dol_mkdir($conf->$module->dir_temp); - } - - // On cree l'image en vraies couleurs - $image = imagecreatetruecolor($x, $y); - - $color = substr($color, 1, 6); - - $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge - $vert = hexdec(substr($color, 2, 2)); //conversion du canal vert - $bleu = hexdec(substr($color, 4, 2)); //conversion du canal bleu - - $couleur = imagecolorallocate($image, $rouge, $vert, $bleu); - //print $rouge.$vert.$bleu; - imagefill($image, 0, 0, $couleur); //on remplit l'image - // On cree la couleur et on l'attribue a une variable pour ne pas la perdre - ImagePng($image, $file); //renvoie une image sous format png - ImageDestroy($image); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of week - * - * @param string $selected Preselected value - * @param string $htmlname Nom de la zone select - * @param int $useempty Affiche valeur vide dans liste - * @return string - */ - public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0) - { - // phpcs:enable - global $langs; - - $week = array( - 0=>$langs->trans("Day0"), - 1=>$langs->trans("Day1"), - 2=>$langs->trans("Day2"), - 3=>$langs->trans("Day3"), - 4=>$langs->trans("Day4"), - 5=>$langs->trans("Day5"), - 6=>$langs->trans("Day6") - ); - - $select_week = ''; - return $select_week; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of month - * - * @param string $selected Preselected value - * @param string $htmlname Name of HTML select object - * @param int $useempty Show empty in list - * @param int $longlabel Show long label - * @param string $morecss More Css - * @param bool $addjscombo Add js combo - * @return string - */ - public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'minwidth50 maxwidth75imp valignmiddle', $addjscombo = false) - { - // phpcs:enable - global $langs; - - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - if ($longlabel) $montharray = monthArray($langs, 0); // Get array - else $montharray = monthArray($langs, 1); - - $select_month = ''; - - // Add code for jquery to use multiselect - if ($addjscombo) - { - // Enhance with select2 - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $select_month .= ajax_combobox($htmlname); - } - - return $select_month; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of years - * - * @param string $selected Preselected value (''=current year, -1=none, year otherwise) - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param int $min_year Offset of minimum year into list (by default current year -10) - * @param int $max_year Offset of maximum year into list (by default current year + 5) - * @param int $offset Offset - * @param int $invert Invert - * @param string $option Option - * @param string $morecss More CSS - * @return string - */ - public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') - { - // phpcs:enable - print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss); - } - - /** - * Return HTML combo list of years - * - * @param string $selected Preselected value (''=current year, -1=none, year otherwise) - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param int $min_year Offset of minimum year into list (by default current year -10) - * @param int $max_year Offset of maximum year into list (by default current year + 5) - * @param int $offset Offset - * @param int $invert Invert - * @param string $option Option - * @param string $morecss More css - * @param bool $addjscombo Add js combo - * @return string - */ - public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle width75', $addjscombo = false) - { - $out = ''; - - $currentyear = date("Y") + $offset; - $max_year = $currentyear + $max_year; - $min_year = $currentyear - $min_year; - if (empty($selected) && empty($useempty)) $selected = $currentyear; - - $out .= '\n"; - - // Add code for jquery to use multiselect - if ($addjscombo) - { - // Enhance with select2 - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $out .= ajax_combobox($htmlname); - } - - return $out; - } - - - /** - * Get array with HTML tabs with boxes of a particular area including personalized choices of user. - * Class 'Form' must be known. - * - * @param User $user Object User - * @param String $areacode Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes() + } + $out .= ''; + } + + return $out; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Creation d'un icone de couleur + * + * @param string $color Couleur de l'image + * @param string $module Nom du module + * @param string $name Nom de l'image + * @param int $x Largeur de l'image en pixels + * @param int $y Hauteur de l'image en pixels + * @return void + */ + public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12') + { + // phpcs:enable + global $conf; + + $file = $conf->$module->dir_temp.'/'.$name.'.png'; + + // On cree le repertoire contenant les icones + if (!file_exists($conf->$module->dir_temp)) + { + dol_mkdir($conf->$module->dir_temp); + } + + // On cree l'image en vraies couleurs + $image = imagecreatetruecolor($x, $y); + + $color = substr($color, 1, 6); + + $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge + $vert = hexdec(substr($color, 2, 2)); //conversion du canal vert + $bleu = hexdec(substr($color, 4, 2)); //conversion du canal bleu + + $couleur = imagecolorallocate($image, $rouge, $vert, $bleu); + //print $rouge.$vert.$bleu; + imagefill($image, 0, 0, $couleur); //on remplit l'image + // On cree la couleur et on l'attribue a une variable pour ne pas la perdre + ImagePng($image, $file); //renvoie une image sous format png + ImageDestroy($image); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of week + * + * @param string $selected Preselected value + * @param string $htmlname Nom de la zone select + * @param int $useempty Affiche valeur vide dans liste + * @return string + */ + public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0) + { + // phpcs:enable + global $langs; + + $week = array( + 0=>$langs->trans("Day0"), + 1=>$langs->trans("Day1"), + 2=>$langs->trans("Day2"), + 3=>$langs->trans("Day3"), + 4=>$langs->trans("Day4"), + 5=>$langs->trans("Day5"), + 6=>$langs->trans("Day6") + ); + + $select_week = ''; + return $select_week; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of month + * + * @param string $selected Preselected value + * @param string $htmlname Name of HTML select object + * @param int $useempty Show empty in list + * @param int $longlabel Show long label + * @param string $morecss More Css + * @return string + */ + public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'maxwidth50imp valignmiddle') + { + // phpcs:enable + global $langs; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + + if ($longlabel) $montharray = monthArray($langs, 0); // Get array + else $montharray = monthArray($langs, 1); + + $select_month = ''; + return $select_month; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of years + * + * @param string $selected Preselected value (''=current year, -1=none, year otherwise) + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param int $min_year Offset of minimum year into list (by default current year -10) + * @param int $max_year Offset of maximum year into list (by default current year + 5) + * @param int $offset Offset + * @param int $invert Invert + * @param string $option Option + * @param string $morecss More CSS + * @return string + */ + public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') + { + // phpcs:enable + print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss); + } + + /** + * Return HTML combo list of years + * + * @param string $selected Preselected value (''=current year, -1=none, year otherwise) + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param int $min_year Offset of minimum year into list (by default current year -10) + * @param int $max_year Offset of maximum year into list (by default current year + 5) + * @param int $offset Offset + * @param int $invert Invert + * @param string $option Option + * @param string $morecss More css + * @return string + */ + public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') + { + $out = ''; + + $currentyear = date("Y") + $offset; + $max_year = $currentyear + $max_year; + $min_year = $currentyear - $min_year; + if (empty($selected) && empty($useempty)) $selected = $currentyear; + + $out .= '\n"; + + return $out; + } + + + /** + * Get array with HTML tabs with boxes of a particular area including personalized choices of user. + * Class 'Form' must be known. + * + * @param User $user Object User + * @param String $areacode Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes() * @return array array('selectboxlist'=>, 'boxactivated'=>, 'boxlista'=>, 'boxlistb'=>) - */ - public static function getBoxesArea($user, $areacode) - { - global $conf, $langs, $db; - - include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; - - $confuserzone = 'MAIN_BOXES_'.$areacode; - - // $boxactivated will be array of boxes enabled into global setup - // $boxidactivatedforuser will be array of boxes choosed by user - - $selectboxlist = ''; - $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) - - $boxidactivatedforuser = array(); - foreach ($boxactivated as $box) - { - if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user - } - - // Define selectboxlist - $arrayboxtoactivatelabel = array(); - if (!empty($user->conf->$confuserzone)) - { - $boxorder = ''; - $langs->load("boxes"); // Load label of boxes - foreach ($boxactivated as $box) - { - if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user - $label = $langs->transnoentitiesnoconv($box->boxlabel); - //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; - if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') - { - $label = $label.' '; - } - $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list - } - foreach ($boxidactivatedforuser as $boxid) - { - if (empty($boxorder)) $boxorder .= 'A:'; + */ + public static function getBoxesArea($user, $areacode) + { + global $conf, $langs, $db; + + include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; + + $confuserzone = 'MAIN_BOXES_'.$areacode; + + // $boxactivated will be array of boxes enabled into global setup + // $boxidactivatedforuser will be array of boxes choosed by user + + $selectboxlist = ''; + $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) + + $boxidactivatedforuser = array(); + foreach ($boxactivated as $box) + { + if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user + } + + // Define selectboxlist + $arrayboxtoactivatelabel = array(); + if (!empty($user->conf->$confuserzone)) + { + $boxorder = ''; + $langs->load("boxes"); // Load label of boxes + foreach ($boxactivated as $box) + { + if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user + $label = $langs->transnoentitiesnoconv($box->boxlabel); + //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; + if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') + { + $label = $label.' '; + } + $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list + } + foreach ($boxidactivatedforuser as $boxid) + { + if (empty($boxorder)) $boxorder .= 'A:'; $boxorder .= $boxid.','; - } - - //var_dump($boxidactivatedforuser); - - // Class Form must have been already loaded - $selectboxlist .= ''."\n"; + } + + //var_dump($boxidactivatedforuser); + + // Class Form must have been already loaded + $selectboxlist .= ''."\n"; $selectboxlist .= ''; - $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1); - if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' '; - $selectboxlist .= ''; - if (!empty($conf->use_javascript_ajax)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $selectboxlist .= ajax_combobox("boxcombo"); - } - } - - // Javascript code for dynamic actions - if (!empty($conf->use_javascript_ajax)) - { - $selectboxlist .= ''."\n"; - } - - // Define boxlista and boxlistb - $boxlista = ''; $boxlistb = ''; - $nbboxactivated = count($boxidactivatedforuser); - - if ($nbboxactivated) - { - // Load translation files required by the page - $langs->loadLangs(array("boxes", "projects")); - - $emptybox = new ModeleBoxes($db); - - $boxlista .= "\n\n"; - - // Define $box_max_lines - $box_max_lines = 5; - if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; - - $ii = 0; - foreach ($boxactivated as $key => $box) - { - if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + $selectboxlist .= ''."\n"; + } + + // Define boxlista and boxlistb + $nbboxactivated = count($boxidactivatedforuser); + + if ($nbboxactivated) + { + // Load translation files required by the page + $langs->loadLangs(array("boxes", "projects")); + + $emptybox = new ModeleBoxes($db); + + $boxlista .= "\n\n"; + + // Define $box_max_lines + $box_max_lines = 5; + if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; + + $ii = 0; + foreach ($boxactivated as $key => $box) + { + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 - if (preg_match('/^A/i', $box->box_order)) // column A - { - $ii++; - //print 'box_id '.$boxactivated[$ii]->box_id.' '; - //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; - // Show box - $box->loadBox($box_max_lines); - $boxlista .= $box->showBox(null, null, 1); - } - } - - if ($conf->browser->layout != 'phone') - { - $emptybox->box_id = 'A'; - $emptybox->info_box_head = array(); - $emptybox->info_box_contents = array(); - $boxlista .= $emptybox->showBox(array(), array(), 1); - } - $boxlista .= "\n"; - - $boxlistb .= "\n\n"; - - $ii = 0; - foreach ($boxactivated as $key => $box) - { - if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; - if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 - if (preg_match('/^B/i', $box->box_order)) // colonne B - { - $ii++; - //print 'box_id '.$boxactivated[$ii]->box_id.' '; - //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; - // Show box - $box->loadBox($box_max_lines); - $boxlistb .= $box->showBox(null, null, 1); - } - } - - if ($conf->browser->layout != 'phone') - { - $emptybox->box_id = 'B'; - $emptybox->info_box_head = array(); - $emptybox->info_box_contents = array(); - $boxlistb .= $emptybox->showBox(array(), array(), 1); - } - - $boxlistb .= "\n"; - } - - return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select list of a dictionary - * - * @param string $htmlname Name of select zone - * @param string $dictionarytable Dictionary table - * @param string $keyfield Field for key - * @param string $labelfield Label field - * @param string $selected Selected value - * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @param string $moreattrib More attributes on HTML select tag - * @return void - */ - public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '') - { - // phpcs:enable - global $langs, $conf; - - $langs->load("admin"); - - $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; - $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; - $sql .= " ORDER BY ".$labelfield; - - dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) - { - print '"; - } else { - print $langs->trans("DictionaryEmpty"); - } - } else { - dol_print_error($this->db); - } - } - - /** + if (preg_match('/^A/i', $box->box_order)) // column A + { + $ii++; + //print 'box_id '.$boxactivated[$ii]->box_id.' '; + //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; + // Show box + $box->loadBox($box_max_lines); + $boxlista .= $box->outputBox(); + } + } + + if ($conf->browser->layout != 'phone') + { + $emptybox->box_id = 'A'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlista .= $emptybox->outputBox(array(), array()); + } + $boxlista .= "\n"; + + $boxlistb .= "\n\n"; + + $ii = 0; + foreach ($boxactivated as $key => $box) + { + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 + if (preg_match('/^B/i', $box->box_order)) // colonne B + { + $ii++; + //print 'box_id '.$boxactivated[$ii]->box_id.' '; + //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; + // Show box + $box->loadBox($box_max_lines); + $boxlistb .= $box->outputBox(); + } + } + + if ($conf->browser->layout != 'phone') + { + $emptybox->box_id = 'B'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlistb .= $emptybox->outputBox(array(), array()); + } + + $boxlistb .= "\n"; + } + + return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return a HTML select list of a dictionary + * + * @param string $htmlname Name of select zone + * @param string $dictionarytable Dictionary table + * @param string $keyfield Field for key + * @param string $labelfield Label field + * @param string $selected Selected value + * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @param string $moreattrib More attributes on HTML select tag + * @return void + */ + public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '') + { + // phpcs:enable + global $langs, $conf; + + $langs->load("admin"); + + $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; + $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; + $sql .= " ORDER BY ".$labelfield; + + dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + if ($num) + { + print '"; + } else { + print $langs->trans("DictionaryEmpty"); + } + } + else { + dol_print_error($this->db); + } + } + + /** * Return an html string with a select combo box to choose yes or no * * @param string $htmlname Name of html select field @@ -1336,7 +1317,7 @@ * @param int $useempty 1=Add empty line * @return string See option */ - public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) + public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) { global $langs; @@ -1355,7 +1336,9 @@ { $resultautomanual .= ''."\n"; $resultautomanual .= ''."\n"; - } else { + } + else + { $selected = (($useempty && $value != '0' && $value != 'manual') ? '' : ' selected'); $resultautomanual .= ''."\n"; $resultautomanual .= ''."\n"; @@ -1371,10 +1354,9 @@ * @param mixed $object Object analyzed * @param array $search_groupby Array of preselected fields * @param array $arrayofgroupby Array of groupby to fill - * @param string $morecss More CSS * @return string HTML string component */ - public function selectGroupByField($object, $search_groupby, &$arrayofgroupby, $morecss = 'minwidth200 maxwidth250') + public function selectGroupByField($object, $search_groupby, &$arrayofgroupby) { global $langs, $extrafields, $form; @@ -1396,9 +1378,9 @@ if (preg_match('/^pass/', $key)) continue; if (in_array($val['type'], array('html', 'text'))) continue; if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) { - $arrayofgroupby['t.'.$key.'-year'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.')', 'position' => $val['position'].'-y'); - $arrayofgroupby['t.'.$key.'-month'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.')', 'position' => $val['position'].'-m'); - $arrayofgroupby['t.'.$key.'-day'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.'-'.$DD.')', 'position' => $val['position'].'-d'); + $arrayofgroupby['t.'.$key.'-year'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.')', 'position' => $val['position'].'-y'); + $arrayofgroupby['t.'.$key.'-month'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.')', 'position' => $val['position'].'-m'); + $arrayofgroupby['t.'.$key.'-day'] = array('label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.'-'.$DD.')', 'position' => $val['position'].'-d'); } else { $arrayofgroupby['t.'.$key] = array('label' => $langs->trans($val['label']), 'position' => (int) $val['position']); } @@ -1418,7 +1400,7 @@ foreach ($arrayofgroupby as $key => $val) { $arrayofgroupbylabel[$key] = $val['label']; } - $result = $form->selectarray('search_groupby', $arrayofgroupbylabel, $search_groupby, 1, 0, 0, '', 0, 0, 0, '', $morecss, 1); + $result = $form->selectarray('search_groupby', $arrayofgroupbylabel, $search_groupby, 1, 0, 0, '', 0, 0, 0, '', 'minwidth250', 1); return $result; } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formprojet.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formprojet.class.php @@ -97,7 +97,9 @@ )); $out .= ''; - } else { + } + else + { $out .= $this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, abs($discard_closed), $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss); } if ($discard_closed > 0) @@ -113,7 +115,8 @@ { print $out; return ''; - } else return $out; + } + else return $out; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -170,7 +173,7 @@ if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY)) $sql .= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)"; elseif ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all') // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma. { - $sql .= " AND (p.fk_soc IN (".$socid.", ".((int) $conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY).") OR p.fk_soc IS NULL)"; + $sql .= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)"; } } if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey); @@ -205,7 +208,9 @@ if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$user->rights->societe->lire) { // Do nothing - } else { + } + else + { if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) // We discard closed except if selected { $i++; @@ -227,11 +232,13 @@ { $disabled = 1; $labeltoshow .= ' - '.$langs->trans("Draft"); - } elseif ($obj->fk_statut == 2) + } + elseif ($obj->fk_statut == 2) { if ($discard_closed == 2) $disabled = 1; $labeltoshow .= ' - '.$langs->trans("Closed"); - } elseif (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) && $socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) + } + elseif (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) && $socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) { $disabled = 1; $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany"); @@ -242,11 +249,15 @@ $out .= ''; } - $num = $this->db->num_rows($resql); $i = 0; if ($num) @@ -381,26 +394,16 @@ if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) { // Do nothing - } else { + } + else + { if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) { $i++; continue; } - $labeltoshow = ''; $titletoshow = ''; - - $disabled = 0; - if ($obj->fk_statut == Project::STATUS_DRAFT) - { - $disabled = 1; - } elseif ($obj->fk_statut == Project::STATUS_CLOSED) - { - if ($discard_closed == 2) $disabled = 1; - } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) - { - $disabled = 1; - } + $labeltoshow = ''; if ($showproject == 'all') { @@ -408,51 +411,49 @@ //if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')'; //else $labeltoshow.=' ('.$langs->trans("Private").')'; $labeltoshow .= ' '.dol_trunc($obj->title, $maxlength); - $titletoshow = $labeltoshow; - - if ($obj->name) { - $labeltoshow .= ' ('.$obj->name.')'; - $titletoshow .= ' ('.$obj->name.')'; - } + + if ($obj->name) $labeltoshow .= ' ('.$obj->name.')'; $disabled = 0; - if ($obj->fk_statut == Project::STATUS_DRAFT) { + if ($obj->fk_statut == Project::STATUS_DRAFT) + { $disabled = 1; $labeltoshow .= ' - '.$langs->trans("Draft"); - $titletoshow .= ' - '.$langs->trans("Draft").''; - } elseif ($obj->fk_statut == Project::STATUS_CLOSED) { + } + elseif ($obj->fk_statut == Project::STATUS_CLOSED) + { if ($discard_closed == 2) $disabled = 1; $labeltoshow .= ' - '.$langs->trans("Closed"); - $titletoshow .= ' - '.$langs->trans("Closed").''; - } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) { + } + elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) + { $disabled = 1; $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany"); - $titletoshow .= ' - '.$langs->trans("LinkedToAnotherCompany").''; } $labeltoshow .= ' - '; - $titletoshow .= ' - '; } // Label for task $labeltoshow .= $obj->tref.' '.dol_trunc($obj->tlabel, $maxlength); - $titletoshow .= $obj->tref.' '.dol_trunc($obj->tlabel, $maxlength); if (!empty($selected) && $selected == $obj->rowid) { $out .= ''; @@ -471,7 +472,9 @@ $this->db->free($resql); return $num; - } else { + } + else + { dol_print_error($this->db); return -1; } @@ -595,7 +598,9 @@ $this->db->free($resql); return $sellist; - } else { + } + else + { dol_print_error($this->db); $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); @@ -616,10 +621,9 @@ * @param int $showpercent Show default probability for status * @param string $morecss Add more css * @param int $noadmininfo 0=Add admin info, 1=Disable admin info - * @param int $addcombojs 1=Add a js combo * @return int|string The HTML select list of element or '' if nothing or -1 if KO */ - public function selectOpportunityStatus($htmlname, $preselected = '-1', $showempty = 1, $useshortlabel = 0, $showallnone = 0, $showpercent = 0, $morecss = '', $noadmininfo = 0, $addcombojs = 0) + public function selectOpportunityStatus($htmlname, $preselected = '-1', $showempty = 1, $useshortlabel = 0, $showallnone = 0, $showpercent = 0, $morecss = '', $noadmininfo = 0) { global $conf, $langs, $user; @@ -656,7 +660,9 @@ if ($useshortlabel) { $finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label); - } else { + } + else + { $finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label); if ($showpercent) $finallabel .= ' ('.$obj->percent.'%)'; } @@ -665,10 +671,7 @@ $i++; } $sellist .= ''; - if ($user->admin && !$noadmininfo) $sellist .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - - if ($addcombojs) $sellist .= ajax_combobox($htmlname); } /*else { @@ -679,7 +682,9 @@ $this->db->free($resql); return $sellist; - } else { + } + else + { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); dol_syslog(get_class($this)."::selectOpportunityStatus ".$this->error, LOG_ERR); --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formpropal.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formpropal.class.php @@ -27,115 +27,119 @@ */ class FormPropal { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** - * @var string Error code (or message) - */ - public $error = ''; + /** + * @var string Error code (or message) + */ + public $error = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Return combo list of differents status of a proposal - * Values are id of table c_propalst - * - * @param string $selected Preselected value - * @param int $short Use short labels - * @param int $excludedraft 0=All status, 1=Exclude draft status - * @param int $showempty 1=Add empty line - * @param string $mode 'customer', 'supplier' - * @param string $htmlname Name of select field - * @return void - */ - public function selectProposalStatus($selected = '', $short = 0, $excludedraft = 0, $showempty = 1, $mode = 'customer', $htmlname = 'propal_statut') - { - global $langs; + /** + * Return combo list of differents status of a proposal + * Values are id of table c_propalst + * + * @param string $selected Preselected value + * @param int $short Use short labels + * @param int $excludedraft 0=All status, 1=Exclude draft status + * @param int $showempty 1=Add empty line + * @param string $mode 'customer', 'supplier' + * @param string $htmlname Name of select field + * @return void + */ + public function selectProposalStatus($selected = '', $short = 0, $excludedraft = 0, $showempty = 1, $mode = 'customer', $htmlname = 'propal_statut') + { + global $langs; - $prefix = ''; - $listofstatus = array(); - if ($mode == 'supplier') { - $prefix = 'SupplierProposalStatus'; + $prefix = ''; + $listofstatus = array(); + if ($mode == 'supplier') { + $prefix = 'SupplierProposalStatus'; - $langs->load("supplier_proposal"); - $listofstatus = array( - 0=>array('id'=>0, 'code'=>'PR_DRAFT'), - 1=>array('id'=>1, 'code'=>'PR_OPEN'), - 2=>array('id'=>2, 'code'=>'PR_SIGNED'), - 3=>array('id'=>3, 'code'=>'PR_NOTSIGNED'), - 4=>array('id'=>4, 'code'=>'PR_CLOSED') - ); - } else { - $prefix = "PropalStatus"; + $langs->load("supplier_proposal"); + $listofstatus = array( + 0=>array('id'=>0, 'code'=>'PR_DRAFT'), + 1=>array('id'=>1, 'code'=>'PR_OPEN'), + 2=>array('id'=>2, 'code'=>'PR_SIGNED'), + 3=>array('id'=>3, 'code'=>'PR_NOTSIGNED'), + 4=>array('id'=>4, 'code'=>'PR_CLOSED') + ); + } else { + $prefix = "PropalStatus"; - $sql = "SELECT id, code, label, active FROM ".MAIN_DB_PREFIX."c_propalst"; - $sql .= " WHERE active = 1"; - dol_syslog(get_class($this)."::selectProposalStatus", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $listofstatus[$obj->id] = array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$obj->label); - $i++; - } - } - } else { - dol_print_error($this->db); - } - } + $sql = "SELECT id, code, label, active FROM ".MAIN_DB_PREFIX."c_propalst"; + $sql .= " WHERE active = 1"; + dol_syslog(get_class($this)."::selectProposalStatus", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $listofstatus[$obj->id] = array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$obj->label); + $i++; + } + } + } + else + { + dol_print_error($this->db); + } + } - print ''; + if ($showempty) print ''; - foreach ($listofstatus as $key => $obj) - { - if ($excludedraft) - { - if ($obj['code'] == 'Draft' || $obj['code'] == 'PR_DRAFT') - { - $i++; - continue; - } - } - if ($selected != '' && $selected == $obj['id']) - { - print ''; - $i++; - } - print ''; - - print ajax_combobox($htmlname); - } + print ($langs->trans($prefix.$key.($short ? 'Short' : '')) != $prefix.$key.($short ? 'Short' : '')) ? $langs->trans($prefix.$key.($short ? 'Short' : '')) : ($obj['label'] ? $obj['label'] : $obj['code']); + } + print ''; + $i++; + } + print ''; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formsms.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formsms.class.php @@ -33,99 +33,99 @@ */ class FormSms { - /** - * @var DoliDB Database handler. - */ - public $db; - - public $fromid; - public $fromname; - public $fromsms; - public $fromtype; - public $replytoname; - public $replytomail; - public $toname; - public $tomail; - - public $withsubstit; // Show substitution array - public $withfrom; - public $withto; - public $withtopic; - public $withbody; - - /** - * @var int Id of company - */ - public $withtosocid; - - public $withfromreadonly; - public $withreplytoreadonly; - public $withtoreadonly; - public $withtopicreadonly; - public $withcancel; - - public $substit = array(); - public $param = array(); - - /** - * @var string Error code (or message) - */ - public $error = ''; - - /** - * @var string[] Array of error strings - */ - public $errors = array(); - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - - $this->withfrom = 1; - $this->withto = 1; - $this->withtopic = 1; - $this->withbody = 1; - - $this->withfromreadonly = 1; - $this->withreplytoreadonly = 1; - $this->withtoreadonly = 0; - $this->withtopicreadonly = 0; - $this->withbodyreadonly = 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Show the form to input an sms. - * - * @param string $morecss Class on first column td - * @param int $showform Show form tags and submit button (recommanded is to use with value 0) - * @return void - */ - public function show_form($morecss = 'titlefield', $showform = 1) - { - // phpcs:enable - global $conf, $langs, $user, $form; - - if (!is_object($form)) $form = new Form($this->db); - - // Load translation files required by the page - $langs->loadLangs(array('other', 'mails', 'sms')); - - $soc = new Societe($this->db); - if (!empty($this->withtosocid) && $this->withtosocid > 0) - { - $soc->fetch($this->withtosocid); - } - - print "\n\n"; - - print ' + /** + * @var DoliDB Database handler. + */ + public $db; + + public $fromid; + public $fromname; + public $fromsms; + public $fromtype; + public $replytoname; + public $replytomail; + public $toname; + public $tomail; + + public $withsubstit; // Show substitution array + public $withfrom; + public $withto; + public $withtopic; + public $withbody; + + /** + * @var int Id of company + */ + public $withtosocid; + + public $withfromreadonly; + public $withreplytoreadonly; + public $withtoreadonly; + public $withtopicreadonly; + public $withcancel; + + public $substit = array(); + public $param = array(); + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string[] Array of error strings + */ + public $errors = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + $this->withfrom = 1; + $this->withto = 1; + $this->withtopic = 1; + $this->withbody = 1; + + $this->withfromreadonly = 1; + $this->withreplytoreadonly = 1; + $this->withtoreadonly = 0; + $this->withtopicreadonly = 0; + $this->withbodyreadonly = 0; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Show the form to input an sms. + * + * @param string $morecss Class on first column td + * @param int $showform Show form tags and submit button (recommanded is to use with value 0) + * @return void + */ + public function show_form($morecss = 'titlefield', $showform = 1) + { + // phpcs:enable + global $conf, $langs, $user, $form; + + if (!is_object($form)) $form = new Form($this->db); + + // Load translation files required by the page + $langs->loadLangs(array('other', 'mails', 'sms')); + + $soc = new Societe($this->db); + if (!empty($this->withtosocid) && $this->withtosocid > 0) + { + $soc->fetch($this->withtosocid); + } + + print "\n\n"; + + print ' '; - if ($showform) print "param["returnurl"]."\">\n"; - - print ''; - foreach ($this->param as $key=>$value) - { - print "\n"; - } - print "
    '.$langs->trans("MailFrom").""; $out .= $langs->trans("Name").':'; $out .= '    '; @@ -648,28 +644,35 @@ $soc = new Societe($this->db); $soc->fetch($this->toid); $out .= $soc->getNomUrl(1); - } elseif ($this->totype == 'contact') + } + elseif ($this->totype == 'contact') { $contact = new Contact($this->db); $contact->fetch($this->toid); $out .= $contact->getNomUrl(1); - } else { + } + else + { $out .= $this->toname; } $out .= ' <'.$this->tomail.'>'; if ($this->withtofree) { - $out .= '
    '.$langs->trans("and").' withto) : "").'" />'; - } - } else { + $out .= '
    '.$langs->trans("and").' withto) : "").'" />'; + } + } + else + { // Note withto may be a text like 'AllRecipientSelected' $out .= (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : ""; } - } else { + } + else + { // The free input of email if (!empty($this->withtofree)) { - $out .= 'withto) : "")).'" />'; + $out .= 'withto) : "")).'" />'; } // The select combo if (!empty($this->withto) && is_array($this->withto)) @@ -681,9 +684,7 @@ { $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true); } - - $withtoselected = GETPOST("receiver", 'array'); // Array of selected value - + $withtoselected = GETPOST("receiver", 'none'); // Array of selected value if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') { $withtoselected = array_keys($tmparray); @@ -707,7 +708,7 @@ { $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true); } - $withtoselected = GETPOST("receiveruser", 'array'); // Array of selected value + $withtoselected = GETPOST("receiveruser", 'none'); // Array of selected value if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') { $withtoselected = array_keys($tmparray); @@ -740,8 +741,10 @@ if ($this->withtoccreadonly) { $out .= (!is_array($this->withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : ""; - } else { - $out .= 'withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : '')).'" />'; + } + else + { + $out .= 'withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : '')).'" />'; if (!empty($this->withtocc) && is_array($this->withtocc)) { $out .= " ".$langs->trans("and")."/".$langs->trans("or")." "; @@ -751,7 +754,7 @@ { $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true); } - $withtoccselected = GETPOST("receivercc", 'array'); // Array of selected value + $withtoccselected = GETPOST("receivercc"); // Array of selected value $out .= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500', null, ""); } } @@ -771,7 +774,7 @@ { $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true); } - $withtoselected = GETPOST("receiverccuser", 'array'); // Array of selected value + $withtoselected = GETPOST("receiverccuser", 'none'); // Array of selected value if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') { $withtoselected = array_keys($tmparray); @@ -861,18 +864,8 @@ { foreach ($listofpaths as $key => $val) { - $relativepathtofile = substr($val, (strlen(DOL_DATA_ROOT) - strlen($val))); - if ($conf->entity > 1) { - $relativepathtofile = str_replace($conf->entity.'/', '', $relativepathtofile); - } - // Try to extract data from full path - $formfile_params = array(); - preg_match('#^(/)(\w+)(/)(.+)$#', $relativepathtofile, $formfile_params); - $out .= '
    '; - // Preview of attachment $out .= img_mime($listofnames[$key]).' '.$listofnames[$key]; - $out .= $formfile->showPreview(array(), $formfile_params[2], $formfile_params[4]); if (!$this->withfilereadonly) { $out .= ' '; @@ -880,7 +873,8 @@ } $out .= '
    '; } - } elseif (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox + } + elseif (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox { $out .= $langs->trans("NoAttachedFiles").'
    '; } @@ -891,7 +885,9 @@ $out .= ' '; $out .= ''; } - } else { + } + else + { $out .= $this->withfile; } @@ -901,7 +897,7 @@ // Message if (!empty($this->withbody)) { - $defaultmessage = GETPOST('message', 'restricthtml'); + $defaultmessage = GETPOST('message', 'none'); if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') { if ($arraydefaultmessage && $arraydefaultmessage->content) { @@ -916,7 +912,9 @@ if (empty($this->substit['__REF__'])) { $paymenturl = ''; - } else { + } + else + { // Set the online payment url link into __ONLINE_PAYMENT_URL__ key require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; $langs->loadLangs(array('paypal', 'other')); @@ -935,12 +933,12 @@ $langs->load('other'); $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = str_replace('\n', "\n", $langs->transnoentities("PredefinedMailContentLink", $paymenturl)); $this->substit['__ONLINE_PAYMENT_URL__'] = $paymenturl; - } else { + } + else + { $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ''; $this->substit['__ONLINE_PAYMENT_URL__'] = ''; } - - $this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'] = ''; // Add lines substitution key from each line $lines = ''; @@ -964,26 +962,24 @@ if (strpos($defaultmessage, '__ONLINE_PAYMENT_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) { $atleastonecomponentishtml++; } - if (strpos($defaultmessage, '__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'])) { - $atleastonecomponentishtml++; - } if (dol_textishtml($defaultmessage)) { $atleastonecomponentishtml++; } if ($atleastonecomponentishtml) { - if (!dol_textishtml($this->substit['__USER_SIGNATURE__'])) { + if (! dol_textishtml($this->substit['__USER_SIGNATURE__'])) { $this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']); } - if (!dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) { + if (! dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) { $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = dol_nl2br($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']); } - if (!dol_textishtml($defaultmessage)) { + if (! dol_textishtml($defaultmessage)) { $defaultmessage = dol_nl2br($defaultmessage); } } if (GETPOSTISSET("message") && !$_POST['modelselected']) $defaultmessage = $_POST["message"]; - else { + else + { $defaultmessage = make_substitutions($defaultmessage, $this->substit); // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty) $defaultmessage = preg_replace("/^(
    )+/", "", $defaultmessage); @@ -999,7 +995,9 @@ { $out .= nl2br($defaultmessage); $out .= ''; - } else { + } + else + { if (!isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes'; // Editor wysiwyg @@ -1031,7 +1029,7 @@ if ($this->withcancel) { $out .= '     '; - $out .= ''; + $out .= ''; } $out .= ''."\n"; } @@ -1075,7 +1073,7 @@ if (!empty($this->withtocccreadonly)) { $out .= (!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : ""; } else { - $out .= 'withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : '')).'" />'; + $out .= 'withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : '')).'" />'; if (!empty($this->withtoccc) && is_array($this->withtoccc)) { $out .= " ".$langs->trans("and")."/".$langs->trans("or")." "; // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time @@ -1083,7 +1081,7 @@ foreach ($tmparray as $key => $val) { $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true); } - $withtocccselected = GETPOST("receiverccc", 'array'); // Array of selected value + $withtocccselected = GETPOST("receiverccc"); // Array of selected value $out .= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null, null, "90%"); } } @@ -1142,7 +1140,7 @@ if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt = 1; if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt = 1; if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt = 1; - $out .= $form->selectyesno('deliveryreceipt', (GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt), 1); + $out .= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"]) ? $_POST["deliveryreceipt"] : $defaultvaluefordeliveryreceipt), 1); } $out .= "
    '.$langs->trans('SellingPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('CostPrice').''.$langs->trans('Margin').''.$langs->trans('MarginRate').'
    \n"; - - // Substitution array - if (!empty($this->withsubstit)) // Unset or set ->withsubstit=0 to disable this. - { - print "\n"; - } - - // From - if ($this->withfrom) - { - if ($this->withfromreadonly) - { - print '\n"; - print "\n"; - } else { - print ''; - print "\n"; - } - } - - // To (target) - if ($this->withto || is_array($this->withto)) - { - print '\n"; - } - - // Message - if ($this->withbody) - { - $defaultmessage = ''; - if ($this->param["models"] == 'body') - { - $defaultmessage = $this->withbody; - } - $defaultmessage = make_substitutions($defaultmessage, $this->substit); - if (GETPOSTISSET("message")) $defaultmessage = GETPOST("message", 'restricthtml'); - $defaultmessage = str_replace('\n', "\n", $defaultmessage); - - print ""; - print '"; - print "'; - } - print "\n"; - } - - print ' + if ($showform) print "param["returnurl"]."\">\n"; + + print ''; + foreach ($this->param as $key=>$value) + { + print "\n"; + } + print "
    "; - $help = ""; - foreach ($this->substit as $key => $val) - { - $help .= $key.' -> '.$langs->trans($val).'
    '; - } - print $form->textwithpicto($langs->trans("SmsTestSubstitutionReplacedByGenericValues"), $help); - print "
    '.$langs->trans("SmsFrom"); - print ''; - print ""; - if ($this->fromtype == 'user') - { - $langs->load("users"); - $fuser = new User($this->db); - $fuser->fetch($this->fromid); - print $fuser->getNomUrl(1); - print '   '; - } - if ($this->fromsms) - { - print $this->fromsms; - } else { - if ($this->fromtype) - { - $langs->load("errors"); - print ' <'.$langs->trans("ErrorNoPhoneDefinedForThisUser").'> '; - } - } - print "
    '.$langs->trans("SmsFrom").""; - //print ''; - if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') // For backward compatibility @deprecated - { - dol_include_once('/ovh/class/ovhsms.class.php'); - try { - $sms = new OvhSms($this->db); - if (empty($conf->global->OVHSMS_ACCOUNT)) - { - $resultsender = 'ErrorOVHSMS_ACCOUNT not defined'; - } else { - $resultsender = $sms->SmsSenderList(); - } - } catch (Exception $e) - { - dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); - } - } elseif (!empty($conf->global->MAIN_SMS_SENDMODE)) // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module' - { - $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE); - $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); - dol_include_once('/'.$module.'/class/'.$classfile.'.class.php'); - try { - $classname = ucfirst($classfile); - if (class_exists($classname)) - { - $sms = new $classname($this->db); - $resultsender = $sms->SmsSenderList(); - } else { - $sms = new stdClass(); - $sms->error = 'The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found'; - } - } catch (Exception $e) - { - dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); - exit; - } - } else { - dol_syslog("Warning: The SMS sending method has not been defined into MAIN_SMS_SENDMODE", LOG_WARNING); - $resultsender = array(); - $resultsender[0]->number = $this->fromsms; - } - - if (is_array($resultsender) && count($resultsender) > 0) - { - print ''; - } else { - print ''.$langs->trans("SmsNoPossibleSenderFound"); - if (is_object($sms) && !empty($sms->error)) print ' '.$sms->error; - print ''; - } - print '
    '; - //$moretext=$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"); - $moretext = ''; - print $form->textwithpicto($langs->trans("SmsTo"), $moretext); - print ''; - if ($this->withtoreadonly) - { - print (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : ""; - } else { - print "withto) && $this->withto != '1' ? (isset($_REQUEST["sendto"]) ?GETPOST("sendto") : $this->withto) : "+")."\">"; - if (!empty($this->withtosocid) && $this->withtosocid > 0) - { - $liste = array(); - foreach ($soc->thirdparty_and_contact_phone_array() as $key => $value) - { - $liste[$key] = $value; - } - print " ".$langs->trans("or")." "; - //var_dump($_REQUEST);exit; - print $form->selectarray("receiver", $liste, GETPOST("receiver"), 1); - } - print ' '.$langs->trans("SmsInfoNumero").''; - } - print "
    '.$langs->trans("SmsText").""; - if ($this->withbodyreadonly) - { - print nl2br($defaultmessage); - print ''; - } else { - print ''; - print '
    '.$langs->trans("SmsInfoCharRemain").': '.(160 - dol_strlen($defaultmessage)).'
    \n"; + + // Substitution array + if (!empty($this->withsubstit)) // Unset or set ->withsubstit=0 to disable this. + { + print "\n"; + } + + // From + if ($this->withfrom) + { + if ($this->withfromreadonly) + { + print '\n"; + print "\n"; + } + else + { + print ''; + print "\n"; + } + } + + // To (target) + if ($this->withto || is_array($this->withto)) + { + print '\n"; + } + + // Message + if ($this->withbody) + { + $defaultmessage = ''; + if ($this->param["models"] == 'body') + { + $defaultmessage = $this->withbody; + } + $defaultmessage = make_substitutions($defaultmessage, $this->substit); + if (isset($_POST["message"])) $defaultmessage = $_POST["message"]; + $defaultmessage = str_replace('\n', "\n", $defaultmessage); + + print ""; + print '"; + print "'; + } + print "\n"; + } + + print ' @@ -332,23 +353,23 @@ '; - print "
    "; + $help = ""; + foreach ($this->substit as $key => $val) + { + $help .= $key.' -> '.$langs->trans($val).'
    '; + } + print $form->textwithpicto($langs->trans("SmsTestSubstitutionReplacedByGenericValues"), $help); + print "
    '.$langs->trans("SmsFrom"); + print ''; + print ""; + if ($this->fromtype == 'user') + { + $langs->load("users"); + $fuser = new User($this->db); + $fuser->fetch($this->fromid); + print $fuser->getNomUrl(1); + print '   '; + } + if ($this->fromsms) + { + print $this->fromsms; + } + else + { + if ($this->fromtype) + { + $langs->load("errors"); + print ' <'.$langs->trans("ErrorNoPhoneDefinedForThisUser").'> '; + } + } + print "
    '.$langs->trans("SmsFrom").""; + //print ''; + if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') // For backward compatibility @deprecated + { + dol_include_once('/ovh/class/ovhsms.class.php'); + try + { + $sms = new OvhSms($this->db); + if (empty($conf->global->OVHSMS_ACCOUNT)) + { + $resultsender = 'ErrorOVHSMS_ACCOUNT not defined'; + } + else + { + $resultsender = $sms->SmsSenderList(); + } + } + catch (Exception $e) + { + dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); + } + } + elseif (!empty($conf->global->MAIN_SMS_SENDMODE)) // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module' + { + $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE); + $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); + dol_include_once('/'.$module.'/class/'.$classfile.'.class.php'); + try + { + $classname = ucfirst($classfile); + if (class_exists($classname)) + { + $sms = new $classname($this->db); + $resultsender = $sms->SmsSenderList(); + } + else + { + $sms = new stdClass(); + $sms->error = 'The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found'; + } + } + catch (Exception $e) + { + dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); + exit; + } + } + else + { + dol_syslog("Warning: The SMS sending method has not been defined into MAIN_SMS_SENDMODE", LOG_WARNING); + $resultsender = array(); + $resultsender[0]->number = $this->fromsms; + } + + if (is_array($resultsender) && count($resultsender) > 0) + { + print ''; + } + else + { + print ''.$langs->trans("SmsNoPossibleSenderFound"); + if (is_object($sms) && !empty($sms->error)) print ' '.$sms->error; + print ''; + } + print '
    '; + //$moretext=$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"); + $moretext = ''; + print $form->textwithpicto($langs->trans("SmsTo"), $moretext); + print ''; + if ($this->withtoreadonly) + { + print (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : ""; + } + else + { + print "withto) && $this->withto != '1' ? (isset($_REQUEST["sendto"]) ?GETPOST("sendto") : $this->withto) : "+")."\">"; + if (!empty($this->withtosocid) && $this->withtosocid > 0) + { + $liste = array(); + foreach ($soc->thirdparty_and_contact_phone_array() as $key => $value) + { + $liste[$key] = $value; + } + print " ".$langs->trans("or")." "; + //var_dump($_REQUEST);exit; + print $form->selectarray("receiver", $liste, GETPOST("receiver"), 1); + } + print ' '.$langs->trans("SmsInfoNumero").''; + } + print "
    '.$langs->trans("SmsText").""; + if ($this->withbodyreadonly) + { + print nl2br($defaultmessage); + print ''; + } + else + { + print ''; + print '
    '.$langs->trans("SmsInfoCharRemain").': '.(160 - dol_strlen($defaultmessage)).'
    '.$langs->trans("DelayBeforeSending").':
    \n"; - - - if ($showform) - { - print '
    '; - print ''; - if ($this->withcancel) - { - print '     '; - print ''; - } - print '
    '; - - print "\n"; - } - - print "\n"; - } + print "
    \n"; + + + if ($showform) + { + print '
    '; + print ''; + if ($this->withcancel) + { + print '     '; + print ''; + } + print '
    '; + + print "\n"; + } + + print "\n"; + } } --- /tmp/dsg/dolibarr/htdocs/core/class/github_html.formsocialcontrib.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_html.formsocialcontrib.class.php @@ -28,9 +28,9 @@ class FormSocialContrib { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -39,82 +39,87 @@ /** - * Constructor - * - * @param DoliDB $db Database handler - */ + * Constructor + * + * @param DoliDB $db Database handler + */ public function __construct($db) { - $this->db = $db; + $this->db = $db; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of social contributions. - * Use mysoc->country_id or mysoc->country_code so they must be defined. - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param int $useempty Set to 1 if we want an empty value - * @param int $maxlen Max length of text in combo box - * @param int $help Add or not the admin help picto - * @param string $morecss Add more CSS on select - * @param int $noerrorifempty No print error if list is empty for the country - * @return void - */ - public function select_type_socialcontrib($selected = '', $htmlname = 'actioncode', $useempty = 0, $maxlen = 40, $help = 1, $morecss = 'minwidth300', $noerrorifempty = 0) - { - // phpcs:enable - global $conf, $db, $langs, $user, $mysoc; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of social contributions. + * Use mysoc->country_id or mysoc->country_code so they must be defined. + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in form + * @param int $useempty Set to 1 if we want an empty value + * @param int $maxlen Max length of text in combo box + * @param int $help Add or not the admin help picto + * @param string $morecss Add more CSS on select + * @return void + */ + public function select_type_socialcontrib($selected = '', $htmlname = 'actioncode', $useempty = 0, $maxlen = 40, $help = 1, $morecss = 'minwidth300') + { + // phpcs:enable + global $conf, $db, $langs, $user, $mysoc; - if (empty($mysoc->country_id) && empty($mysoc->country_code)) - { - print $langs->trans("ErrorSetupOfCountryMustBeDone"); - return; - } + if (empty($mysoc->country_id) && empty($mysoc->country_code)) + { + dol_print_error('', 'Call to select_type_socialcontrib with mysoc country not yet defined'); + exit; + } - if (!empty($mysoc->country_id)) - { - $sql = "SELECT c.id, c.libelle as type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; - $sql .= " WHERE c.active = 1"; - $sql .= " AND c.fk_pays = ".$mysoc->country_id; - $sql .= " ORDER BY c.libelle ASC"; - } else { - $sql = "SELECT c.id, c.libelle as type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c, ".MAIN_DB_PREFIX."c_country as co"; - $sql .= " WHERE c.active = 1 AND c.fk_pays = co.rowid"; - $sql .= " AND co.code = '".$this->db->escape($mysoc->country_code)."'"; - $sql .= " ORDER BY c.libelle ASC"; - } + if (!empty($mysoc->country_id)) + { + $sql = "SELECT c.id, c.libelle as type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; + $sql .= " WHERE c.active = 1"; + $sql .= " AND c.fk_pays = ".$mysoc->country_id; + $sql .= " ORDER BY c.libelle ASC"; + } + else + { + $sql = "SELECT c.id, c.libelle as type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c, ".MAIN_DB_PREFIX."c_country as co"; + $sql .= " WHERE c.active = 1 AND c.fk_pays = co.rowid"; + $sql .= " AND co.code = '".$mysoc->country_code."'"; + $sql .= " ORDER BY c.libelle ASC"; + } - dol_syslog("Form::select_type_socialcontrib", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - print ''; + $i = 0; - if ($useempty) print ''; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - print ''; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print '