--- /tmp/dsg/dolibarr/htdocs/core/class/github_19.0.3_CMailFile.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_CMailFile.class.php @@ -9 +9 @@ - * Copyright (C) 2019-2023 Frédéric France + * Copyright (C) 2019 Frédéric France @@ -33,4 +32,0 @@ -use OAuth\Common\Storage\DoliStorage; -use OAuth\Common\Consumer\Credentials; - - @@ -39 +35 @@ - * 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); @@ -48,5 +44,2 @@ - /** - * @var string Subject of email - */ - public $subject; - 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). @@ -56,17 +49,14 @@ - 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 $msg; - 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; @@ -79,23 +69,2 @@ - /** - * @var string[] Array of Error code (or message) - */ - public $errors = array(); - - - /** - * @var SMTPS (if this method is used) - */ - public $smtps; - /** - * @var Swift_Mailer (if the method is used) - */ - public $mailer; - - /** - * @var Swift_SmtpTransport - */ - public $transport; - /** - * @var Swift_Plugins_Loggers_ArrayLogger - */ - public $logger; + public $smtps; // Contains SMTPs object (if this method is used) + public $phpmailer; // Contains PHPMailer object (if this method is used) @@ -108 +77 @@ - public $styleCSS; + public $styleCSS; @@ -110,10 +79,6 @@ - public $bodyCSS; - - /** - * @var string Message-ID of the email to send (generated) - */ - public $msgid; - public $headers; - public $message; - - /** + public $bodyCSS; + + public $msgid; + public $headers; + public $message; + /** @@ -131,4 +95,0 @@ - /** - * @var array filenames cid - */ - public $cid_list = array(); @@ -137,8 +98,7 @@ - public $html; - public $msgishtml; - 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', @@ -151,2 +111,2 @@ - 'tiff' => 'image/tiff', - ); + 'tiff' => 'image/tiff', + ); @@ -165 +125 @@ - * @param string $addr_cc Email cc (Example: 'abc@def.com, ghk@lmn.com') + * @param string $addr_cc Email cc @@ -172,2 +132,2 @@ - * @param string $moreinheader More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'mail' and 'smtps' for the moment) - * @param string $sendcontext 'standard', 'emailing', 'ticket', 'password', ... (used to define which sending mode and parameters to use) + * @param string $moreinheader More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment) + * @param string $sendcontext 'standard', 'emailing', ... (used to define which sending mode and parameters to use) @@ -175,3 +135,2 @@ - * @param string $upload_dir_tmp Temporary directory (used to convert images embedded as img src=data:image) - */ - public function __construct($subject, $to, $from, $msg, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = 0, $errors_to = '', $css = '', $trackid = '', $moreinheader = '', $sendcontext = 'standard', $replyto = '', $upload_dir_tmp = '') + */ + public function __construct($subject, $to, $from, $msg, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = 0, $errors_to = '', $css = '', $trackid = '', $moreinheader = '', $sendcontext = 'standard', $replyto = '') @@ -179,5 +138 @@ - global $conf, $dolibarr_main_data_root, $user; - - dol_syslog("CMailFile::CMailfile: 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: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); - + global $conf, $dolibarr_main_data_root; @@ -192,2 +147,17 @@ - $cid_list = array(); - + // 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; + $this->filename_list = $filename_list; + $this->mimetype_list = $mimetype_list; + $this->mimefilename_list = $mimefilename_list; + $this->addr_cc = $addr_cc; + $this->addr_bcc = $addr_bcc; + $this->deliveryreceipt = $deliveryreceipt; + if (empty($replyto)) $replyto = $from; + $this->reply_to = $replyto; + $this->errors_to = $errors_to; + $this->trackid = $trackid; @@ -195,2 +165,5 @@ - - // Define this->sendmode ('mail', 'smtps', 'swiftmailer', ...) according to $sendcontext ('standard', 'emailing', 'ticket', 'password') + $this->filename_list = $filename_list; + $this->mimetype_list = $mimetype_list; + $this->mimefilename_list = $mimefilename_list; + + // Define this->sendmode @@ -198,10 +171,6 @@ - if (!empty($this->sendcontext)) { - $smtpContextKey = strtoupper($this->sendcontext); - $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey); - if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { - $this->sendmode = $smtpContextSendMode; - } - } - if (empty($this->sendmode)) { - $this->sendmode = (getDolGlobalString('MAIN_MAIL_SENDMODE') ? $conf->global->MAIN_MAIL_SENDMODE : 'mail'); - } + 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'; @@ -213 +182,2 @@ - if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) { + if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { @@ -223 +193 @@ - $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contain special chars) + $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars) @@ -226,3 +196,7 @@ - $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contain special chars) - - if (empty($subject)) { + $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, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); + dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); + + if (empty($subject)) + { @@ -233,3 +207,4 @@ - 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) + 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) @@ -239 +214,2 @@ - if ($msgishtml == -1) { + if ($msgishtml == -1) + { @@ -241,4 +217,4 @@ - if (dol_textishtml($msg)) { - $this->msgishtml = 1; - } - } else { + if (dol_textishtml($msg)) $this->msgishtml = 1; + } + else + { @@ -258,3 +234 @@ - if (getDolGlobalString('MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML')) { - $this->msgishtml = 1; // To force to send everything with content type html. - } + if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml = 1; // To force to send everything with content type html. @@ -263 +237,2 @@ - if ($this->msgishtml) { + if ($this->msgishtml) + { @@ -266,6 +241,2 @@ - $findimg = 0; - if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS')) { // Off by default - // Search into the body for error = 'ErrorInAddAttachementsImageBaseOnMedia'; - return; - } - } - - if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA')) { - // Search into the body for errors)); // Output errors set by findHtmlImagesInSrcData - $this->error = 'ErrorInAddAttachementsImageBaseOnMedia'; - return; - } - $findimg += $resultImageData; - } - - // Set atleastoneimage if there is at least one embedded file (into ->html_images) - if ($findimg > 0) { - foreach ($this->html_images as $i => $val) { - if ($this->html_images[$i]) { + } + + // Define if there is at least one file + if ($findimg) + { + foreach ($this->html_images as $i => $val) + { + if ($this->html_images[$i]) + { @@ -298,13 +253,0 @@ - if ($this->html_images[$i]['type'] == 'cidfromdata') { - if (!in_array($this->html_images[$i]['fullpath'], $filename_list)) { - // If this file path is not already into the $filename_list, we add it. - $posindice = count($filename_list); - $filename_list[$posindice] = $this->html_images[$i]['fullpath']; - $mimetype_list[$posindice] = $this->html_images[$i]['content_type']; - $mimefilename_list[$posindice] = $this->html_images[$i]['name']; - } else { - $posindice = array_search($this->html_images[$i]['fullpath'], $filename_list); - } - // We complete the array of cid_list - $cid_list[$posindice] = $this->html_images[$i]['cid']; - } @@ -316,7 +259,8 @@ - //var_dump($filename_list); - //var_dump($cid_list);exit; - - // Set atleastoneimage if there is at least one file (into $filename_list array) - if (is_array($filename_list)) { - foreach ($filename_list as $i => $val) { - if ($filename_list[$i]) { + + // Define if there is at least one file + if (is_array($filename_list)) + { + foreach ($filename_list as $i => $val) + { + if ($filename_list[$i]) + { @@ -324,73 +268,4 @@ - dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i]." cid_list[$i]=".$cid_list[$i], LOG_DEBUG); - } - } - } - - // Add auto copy to if not already in $to (Note: Adding bcc for specific modules are also done from pages) - // For example MAIN_MAIL_AUTOCOPY_TO can be 'email@example.com, __USER_EMAIL__, ...' - if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')) { - $listofemailstoadd = explode(',', getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')); - foreach ($listofemailstoadd as $key => $val) { - $emailtoadd = $listofemailstoadd[$key]; - if (trim($emailtoadd) == '__USER_EMAIL__') { - if (!empty($user) && !empty($user->email)) { - $emailtoadd = $user->email; - } else { - $emailtoadd = ''; - } - } - if ($emailtoadd && preg_match('/'.preg_quote($emailtoadd, '/').'/i', $to)) { - $emailtoadd = ''; // Email already in the "To" - } - if ($emailtoadd) { - $listofemailstoadd[$key] = $emailtoadd; - } else { - unset($listofemailstoadd[$key]); - } - } - if (!empty($listofemailstoadd)) { - $addr_bcc .= ($addr_bcc ? ', ' : '').join(', ', $listofemailstoadd); - } - } - - // We always use a replyto - if (empty($replyto)) { - $replyto = dol_sanitizeEmail($from); - } - // We can force the from - if (getDolGlobalString('MAIN_MAIL_FORCE_FROM')) { - $from = getDolGlobalString('MAIN_MAIL_FORCE_FROM'); - } - - $this->subject = $subject; - $this->addr_to = dol_sanitizeEmail($to); - $this->addr_from = dol_sanitizeEmail($from); - $this->msg = $msg; - $this->addr_cc = dol_sanitizeEmail($addr_cc); - $this->addr_bcc = dol_sanitizeEmail($addr_bcc); - $this->deliveryreceipt = $deliveryreceipt; - $this->reply_to = dol_sanitizeEmail($replyto); - $this->errors_to = dol_sanitizeEmail($errors_to); - $this->trackid = $trackid; - // Set arrays with attached files info - $this->filename_list = $filename_list; - $this->mimetype_list = $mimetype_list; - $this->mimefilename_list = $mimefilename_list; - $this->cid_list = $cid_list; - - if (getDolGlobalString('MAIN_MAIL_FORCE_SENDTO')) { - $this->addr_to = dol_sanitizeEmail(getDolGlobalString('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); - $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey); - if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey; - } - } - - dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG); + dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG); + } + } + } @@ -400 +275,2 @@ - if ($this->sendmode == 'mail') { + if ($this->sendmode == 'mail') + { @@ -411,3 +287 @@ - if (!empty($moreinheader)) { - $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n - } + if (!empty($moreinheader)) $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n @@ -418,2 +292,4 @@ - if (!empty($this->html)) { - if (!empty($css)) { + if (!empty($this->html)) + { + if (!empty($css)) + { @@ -431,2 +307,3 @@ - if (!empty($this->atleastonefile)) { - $files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list); + if ($this->atleastonefile) + { + $files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list); @@ -445 +322,3 @@ - } elseif ($this->sendmode == 'smtps') { + } + elseif ($this->sendmode == 'smtps') + { @@ -454 +333 @@ - $subjecttouse = $this->subject; + $subjecttouse = $subject; @@ -460,10 +339,118 @@ - $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)); - - if (!empty($moreinheader)) { - $smtps->setMoreInHeader($moreinheader); - } - - if (!empty($this->html)) { + $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); + + if (!empty($this->html)) + { + if (!empty($css)) + { + $this->css = $css; + $this->buildCSS(); + } + $msg = $this->html; + $msg = $this->checkIfHTML($msg); + } + + // Replace . alone on a new line with .. to avoid to have SMTP interpret this as end of message + $msg = preg_replace('/(\r|\n)\.(\r|\n)/ims', '\1..\2', $msg); + + if ($this->msgishtml) $smtps->setBodyContent($msg, 'html'); + else $smtps->setBodyContent($msg, 'plain'); + + if ($this->atleastoneimage) + { + foreach ($this->images_encoded as $img) + { + $smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']); + } + } + + if ($this->atleastonefile) + { + foreach ($filename_list as $i => $val) + { + $content = file_get_contents($filename_list[$i]); + $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i]); + } + } + + $smtps->setCC($addr_cc); + $smtps->setBCC($addr_bcc); + $smtps->setErrorsTo($errors_to); + $smtps->setDeliveryReceipt($deliveryreceipt); + + $host = dol_getprefix('email'); + $this->msgid = time().'.SMTPs-dolibarr-'.$trackid.'@'.$host; + + $this->smtps = $smtps; + } + 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', $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)) { @@ -475,136 +462,7 @@ - $msg = $this->checkIfHTML($msg); // This add a header and a body including custom CSS to the HTML content - } - - // Replace . alone on a new line with .. to avoid to have SMTP interpret this as end of message - $msg = preg_replace('/(\r|\n)\.(\r|\n)/ims', '\1..\2', $msg); - - if ($this->msgishtml) { - $smtps->setBodyContent($msg, 'html'); - } else { - $smtps->setBodyContent($msg, 'plain'); - } - - if ($this->atleastoneimage) { - foreach ($this->images_encoded as $img) { - $smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']); - } - } - - if (!empty($this->atleastonefile)) { - foreach ($filename_list as $i => $val) { - $content = file_get_contents($filename_list[$i]); - $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]); - } - } - - $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))); - } - - $host = dol_getprefix('email'); - $this->msgid = time().'.SMTPs-dolibarr-'.$this->trackid.'@'.$host; - - $this->smtps = $smtps; - } 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); - - // Add 'References:' header - //$headers->addIdHeader('References', $headerID); - - // Give the message a subject - try { - $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 (getDolGlobalString('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 - $adressEmailFrom = array(); - $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) { - $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID); - } else { - $this->message->setFrom($this->getArrayAddress($this->addr_from)); - } - } else { - $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 { - $this->message->setTo($this->getArrayAddress($this->addr_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - if (!empty($this->reply_to)) { - try { - $this->message->SetReplyTo($this->getArrayAddress($this->reply_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - if (!empty($this->errors_to)) { - try { - $headers->addTextHeader('Errors-To', $this->getArrayAddress($this->errors_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - - try { - $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(); - } - $msg = $this->html; - $msg = $this->checkIfHTML($msg); // This add a header and a body including custom CSS to the HTML content - } - - if ($this->atleastoneimage) { - foreach ($this->images_encoded as $img) { + $msg = $this->checkIfHTML($msg); + } + + if ($this->atleastoneimage) + { + foreach ($this->images_encoded as $img) + { @@ -630,2 +488,4 @@ - if (!empty($this->atleastonefile)) { - foreach ($filename_list as $i => $val) { + if ($this->atleastonefile) + { + foreach ($filename_list as $i => $val) + { @@ -634,3 +493,0 @@ - if (!empty($mimefilename_list[$i])) { - $attachment->setFilename($mimefilename_list[$i]); - } @@ -641,23 +498,7 @@ - if (!empty($this->addr_cc)) { - try { - $this->message->setCc($this->getArrayAddress($this->addr_cc)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - if (!empty($this->addr_bcc)) { - try { - $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - //if (!empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to)); - if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) { - try { - $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - } 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 + { @@ -669,0 +511 @@ + @@ -677 +519 @@ - global $conf, $db, $langs, $hookmanager; + global $conf, $db, $langs; @@ -684,5 +526,4 @@ - if (!getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) { - if (!is_object($hookmanager)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($db); - } + if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($db); @@ -691,2 +532 @@ - $parameters = array(); - $action = ''; + $parameters = array(); $action = ''; @@ -694 +534,2 @@ - if ($reshook < 0) { + if ($reshook < 0) + { @@ -700 +541,2 @@ - if ($reshook == 1) { // Hook replace standard code + if ($reshook == 1) // Hook replace standard code + { @@ -705,22 +547,22 @@ - if ($this->sendcontext == 'emailing' && getDolGlobalString('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 (getDolGlobalString('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); - } - - dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); - return false; + 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; @@ -730,3 +572 @@ - if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL')) { - $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10; - } + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10; @@ -734 +574,2 @@ - if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) { + if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) + { @@ -739,3 +580 @@ - if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL')) { - $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10; - } + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10; @@ -743 +582,2 @@ - if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) { + if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) + { @@ -748,3 +588 @@ - if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL')) { - $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10; - } + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10; @@ -752 +590,2 @@ - if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) { + if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) + { @@ -757,4 +596,3 @@ - if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL')) { - $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10; - } - if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) { + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10; + if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) + { @@ -770,2 +607,0 @@ - $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE'; - $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE'; @@ -774,15 +610,15 @@ - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED'; - if (!empty($this->sendcontext)) { - $smtpContextKey = strtoupper($this->sendcontext); - $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey); - 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; - $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey; - $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$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 = ''; @@ -792 +628,2 @@ - if ($this->sendmode == 'mail') { + if ($this->sendmode == 'mail') + { @@ -796 +633 @@ - //dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG); + dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG); @@ -800,4 +637,3 @@ - if (isset($_SERVER["WINDIR"])) { - if (empty($this->addr_from)) { - $this->addr_from = 'robot@example.com'; - } + if (isset($_SERVER["WINDIR"])) + { + if (empty($this->addr_from)) $this->addr_from = 'robot@example.com'; @@ -808,7 +644,3 @@ - //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".getDolGlobalString($keyforsmtpserver)." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG); - if (getDolGlobalString($keyforsmtpserver)) { - ini_set('SMTP', getDolGlobalString($keyforsmtpserver)); - } - if (getDolGlobalString($keyforsmtpport)) { - ini_set('smtp_port', getDolGlobalString($keyforsmtpport)); - } + //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".$conf->global->$keyforsmtpserver." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG); + if (!empty($conf->global->$keyforsmtpserver)) ini_set('SMTP', $conf->global->$keyforsmtpserver); + if (!empty($conf->global->$keyforsmtpport)) ini_set('smtp_port', $conf->global->$keyforsmtpport); @@ -817 +649,2 @@ - if ($res && !$this->subject) { + if ($res && !$this->subject) + { @@ -823 +656,2 @@ - if ($res && !$dest) { + if ($res && !$dest) + { @@ -829 +663,2 @@ - if ($res) { + if ($res) + { @@ -831,4 +666,4 @@ - if (getDolGlobalString('MAIN_MAIL_ALLOW_SENDMAIL_F')) { - // When using the phpmail function, the mail command may force the from to the user of the login, for example: linuxuser@myserver.mydomain.com - // You can try to set this option to have the command use the From. if it does not work, you can also try the MAIN_MAIL_SENDMAIL_FORCE_BA. - // So forcing using the option -f of sendmail is possible if constant MAIN_MAIL_ALLOW_SENDMAIL_F is defined. + if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) + { + // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA + // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie. @@ -837 +672 @@ - $additionnalparam .= ($additionnalparam ? ' ' : '').(getDolGlobalString('MAIN_MAIL_ERRORS_TO') ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : '')); + $additionnalparam .= ($additionnalparam ? ' ' : '').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : '')); @@ -839 +674,2 @@ - if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_BA')) { // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender + { @@ -843,13 +679,3 @@ - if (getDolGlobalString('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); + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params + + dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG); @@ -859,3 +685 @@ - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->dump_mail(); - } + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); @@ -869,7 +693,5 @@ - if (!empty($additionnalparam)) { - $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam); - } else { - $res = mail($dest, $subjecttouse, $this->message, $this->headers); - } - - if (!$res) { + if (!empty($additionnalparam)) $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam); + else $res = mail($dest, $subjecttouse, $this->message, $this->headers); + + if (!$res) + { @@ -878 +700,5 @@ - if (!$linuxlike) { + $linuxlike = 1; + if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; + if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; + if (!$linuxlike) + { @@ -884,5 +710,3 @@ - - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->save_dump_mail_in_err('Mail with topic '.$this->subject); - } - } else { + } + else + { @@ -893 +717,2 @@ - if (isset($_SERVER["WINDIR"])) { + if (isset($_SERVER["WINDIR"])) + { @@ -898,9 +723,8 @@ - if (getDolGlobalString($keyforsmtpserver)) { - ini_restore('SMTP'); - } - if (getDolGlobalString($keyforsmtpport)) { - ini_restore('smtp_port'); - } - } elseif ($this->sendmode == 'smtps') { - if (!is_object($this->smtps)) { - $this->error = "Failed to send mail with smtps lib
Constructor of object CMailFile was not initialized without errors."; + if (!empty($conf->global->$keyforsmtpserver)) ini_restore('SMTP'); + if (!empty($conf->global->$keyforsmtpport)) ini_restore('smtp_port'); + } + elseif ($this->sendmode == 'smtps') + { + if (!is_object($this->smtps)) + { + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Constructor of object CMailFile was not initialized without errors."; @@ -916,6 +740,2 @@ - if (empty($conf->global->$keyforsmtpserver)) { - $conf->global->$keyforsmtpserver = ini_get('SMTP'); - } - if (empty($conf->global->$keyforsmtpport)) { - $conf->global->$keyforsmtpport = ini_get('smtp_port'); - } + if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); + if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport = ini_get('smtp_port'); @@ -924 +744 @@ - $server = getDolGlobalString($keyforsmtpserver); + $server = $conf->global->$keyforsmtpserver; @@ -926,6 +746,2 @@ - if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { - $secure = 'ssl'; - } - if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) { - $secure = 'tls'; - } + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl'; + if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls'; @@ -934 +750 @@ - $port = getDolGlobalInt($keyforsmtpport); + $port = $conf->global->$keyforsmtpport; @@ -939,3 +755,3 @@ - $loginid = ''; - $loginpass = ''; - if (!empty($conf->global->$keyforsmtpid)) { + $loginid = ''; $loginpass = ''; + if (!empty($conf->global->$keyforsmtpid)) + { @@ -945 +761,2 @@ - if (!empty($conf->global->$keyforsmtppw)) { + if (!empty($conf->global->$keyforsmtppw)) + { @@ -950,61 +766,0 @@ - if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") { - require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array - - $supportedoauth2array = getSupportedOauth2Array(); - - $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice); - if (preg_match('/^.*-/', $keyforsupportedoauth2array)) { - $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array); - } else { - $keyforprovider = ''; - } - $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array); - $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME'; - - if (!empty($supportedoauth2array)) { - $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : '')); - } else { - $OAUTH_SERVICENAME = 'Unknown'; - } - - require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; - - $storage = new DoliStorage($db, $conf, $keyforprovider); - try { - $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if (is_object($tokenobj)) { - $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30)); - } - // Token expired so we refresh it - if (is_object($tokenobj) && $expire) { - $credentials = new Credentials( - getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_ID'), - getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_SECRET'), - getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_URLAUTHORIZE') - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $oauthname = explode('-', $OAUTH_SERVICENAME); - // ex service is Google-Emails we need only the first part Google - $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array()); - // We have to save the token because Google give it only once - $refreshtoken = $tokenobj->getRefreshToken(); - $tokenobj = $apiService->refreshAccessToken($tokenobj); - $tokenobj->setRefreshToken($refreshtoken); - $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj); - } - - $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); - if (is_object($tokenobj)) { - $this->smtps->setToken($tokenobj->getAccessToken()); - } else { - $this->error = "Token not found"; - } - } catch (Exception $e) { - // Return an error if token not found - $this->error = $e->getMessage(); - dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - } - } - @@ -1013,2 +769,3 @@ - if ($res && !$from) { - $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Sender address '$from' invalid"; + if ($res && !$from) + { + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Sender address '$from' invalid"; @@ -1019,2 +776,3 @@ - if ($res && !$dest) { - $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Recipient address '$dest' invalid"; + if ($res && !$dest) + { + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Recipient address '$dest' invalid"; @@ -1025,6 +783,3 @@ - if ($res) { - dol_syslog("CMailFile::sendfile: sendMsg, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_DEBUG); - - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->smtps->setDebug(true); - } + if ($res) + { + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true); @@ -1033,27 +788,7 @@ - - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->dump_mail(); - } - - $smtperrorcode = 0; - if (! $result) { - $smtperrorcode = $this->smtps->lastretval; // SMTP error code - dol_syslog("CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING); - - if ($smtperrorcode == '421') { // Try later - // TODO Add a delay and try again - /* - dol_syslog("CMailFile::sendfile: Try later error, so we wait and we retry"); - sleep(2); - - $result = $this->smtps->sendMsg(); - - if (!empty($conf->global->MAIN_MAIL_DEBUG)) { - $this->dump_mail(); - } - */ - } - } - - $result = $this->smtps->getErrors(); // applicative error code (not SMTP error code) - if (empty($this->error) && empty($result)) { + //print $result; + + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + + $result = $this->smtps->getErrors(); + if (empty($this->error) && empty($result)) + { @@ -1062,5 +797,5 @@ - } else { - if (empty($this->error)) { - $this->error = $result; - } - dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - ".$this->error, LOG_ERR); + } + 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); @@ -1068,4 +802,0 @@ - - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->save_dump_mail_in_err('Mail smtp error '.$smtperrorcode.' with topic '.$this->subject); - } @@ -1074,4 +805,6 @@ - } 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'; @@ -1080,6 +813,2 @@ - if (empty($conf->global->$keyforsmtpserver)) { - $conf->global->$keyforsmtpserver = ini_get('SMTP'); - } - if (empty($conf->global->$keyforsmtpport)) { - $conf->global->$keyforsmtpport = ini_get('smtp_port'); - } + if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); + if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport = ini_get('smtp_port'); @@ -1088 +817 @@ - $server = getDolGlobalString($keyforsmtpserver); + $server = $conf->global->$keyforsmtpserver; @@ -1090,79 +819,7 @@ - if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { - $secure = 'ssl'; - } - if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) { - $secure = 'tls'; - } - - $this->transport = new Swift_SmtpTransport($server, getDolGlobalString($keyforsmtpport), $secure); - - if (!empty($conf->global->$keyforsmtpid)) { - $this->transport->setUsername($conf->global->$keyforsmtpid); - } - if (!empty($conf->global->$keyforsmtppw) && getDolGlobalString($keyforsmtpauthtype) != "XOAUTH2") { - $this->transport->setPassword($conf->global->$keyforsmtppw); - } - if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") { - require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; - - $supportedoauth2array = getSupportedOauth2Array(); - - $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice); - if (preg_match('/^.*-/', $keyforsupportedoauth2array)) { - $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array); - } else { - $keyforprovider = ''; - } - $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array); - $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME'; - - $OAUTH_SERVICENAME = 'Unknown'; - if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array) - && array_key_exists('name', $supportedoauth2array[$keyforsupportedoauth2array]) - && !empty($supportedoauth2array[$keyforsupportedoauth2array]['name'])) { - $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array]['name'].(!empty($keyforprovider) ? '-'.$keyforprovider : ''); - } - - require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; - - $storage = new DoliStorage($db, $conf, $keyforprovider); - - try { - $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if (is_object($tokenobj)) { - $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30)); - } - // Token expired so we refresh it - if (is_object($tokenobj) && $expire) { - $credentials = new Credentials( - getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_ID'), - getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_SECRET'), - getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_URLAUTHORIZE') - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $oauthname = explode('-', $OAUTH_SERVICENAME); - // ex service is Google-Emails we need only the first part Google - $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array()); - // We have to save the token because Google give it only once - $refreshtoken = $tokenobj->getRefreshToken(); - $tokenobj = $apiService->refreshAccessToken($tokenobj); - $tokenobj->setRefreshToken($refreshtoken); - $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj); - } - if (is_object($tokenobj)) { - $this->transport->setAuthMode('XOAUTH2'); - $this->transport->setPassword($tokenobj->getAccessToken()); - } else { - $this->errors[] = "Token not found"; - } - } catch (Exception $e) { - // Return an error if token not found - $this->errors[] = $e->getMessage(); - dol_syslog("CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR); - } - } - if (getDolGlobalString($keyforsslseflsigned)) { - $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false))); - } + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl'; + if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls'; + + $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure); + + if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); + if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); @@ -1172,2 +829,2 @@ - $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); - $this->message->setEncoder($contentEncoderBase64); + $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + $this->message->setEncoder($contentEncoderBase64); @@ -1178,10 +835,10 @@ - // DKIM SIGN - if (getDolGlobalString('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 (getDolGlobalString('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)) { @@ -1194,3 +850,0 @@ - - dol_syslog("CMailFile::sendfile: mailer->send, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_DEBUG); - @@ -1198 +851,0 @@ - $failedRecipients = array(); @@ -1200 +853 @@ - $result = $this->mailer->send($this->message, $failedRecipients); + $result = $this->mailer->send($this->message); @@ -1202,5 +855,3 @@ - $this->errors[] = $e->getMessage(); - } - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->dump_mail(); - } + $this->error = $e->getMessage(); + } + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); @@ -1209,4 +860 @@ - if (!empty($this->error) || !empty($this->errors) || !$result) { - if (!empty($failedRecipients)) { - $this->errors[] = 'Transport failed for the following addresses: "' . join('", "', $failedRecipients) . '".'; - } + if (!empty($this->error) || !$result) { @@ -1215,5 +863,3 @@ - - if (getDolGlobalString('MAIN_MAIL_DEBUG')) { - $this->save_dump_mail_in_err('Mail with topic '.$this->subject); - } - } else { + } + else + { @@ -1222 +868,3 @@ - } else { + } + else + { @@ -1229,9 +877 @@ - // Now we delete image files that were created dynamically to manage data inline files - foreach ($this->html_images as $val) { - if (!empty($val['type']) && $val['type'] == 'cidfromdata') { - //dol_delete($val['fullpath']); - } - } - - $parameters = array('sent' => $res); - $action = ''; + $parameters = array(); $action = ''; @@ -1239 +879,2 @@ - if ($reshook < 0) { + if ($reshook < 0) + { @@ -1245 +886,3 @@ - } else { + } + else + { @@ -1250,0 +894 @@ + @@ -1266 +910 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1271 +915 @@ - * @return int|string Return integer <0 if KO, encoded string if OK + * @return int <0 if KO, encoded string if OK @@ -1275 +919 @@ - // phpcs:enable + // phpcs:enable @@ -1278 +922,2 @@ - if (is_readable($newsourcefile)) { + if (is_readable($newsourcefile)) + { @@ -1282,3 +927,5 @@ - } else { - $this->error = "Error in _encode_file() method: Can't read file '".$sourcefile."'"; - dol_syslog("CMailFile::_encode_file: ".$this->error, LOG_ERR); + } + else + { + $this->error = "Error: Can't read file '".$sourcefile."' into _encode_file"; + dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR); @@ -1290 +937 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1300 +947 @@ - // phpcs:enable + // phpcs:enable @@ -1303 +950,2 @@ - if (@is_writeable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir + if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir + { @@ -1305,3 +953,4 @@ - $fp = fopen($outputfile, "w"); // overwrite - - if ($this->sendmode == 'mail') { + $fp = fopen($outputfile, "w"); + + if ($this->sendmode == 'mail') + { @@ -1311 +960,3 @@ - } elseif ($this->sendmode == 'smtps') { + } + elseif ($this->sendmode == 'smtps') + { @@ -1313 +964,3 @@ - } elseif ($this->sendmode == 'swiftmailer') { + } + elseif ($this->sendmode == 'swiftmailer') + { @@ -1318,52 +971,2 @@ - dolChmod($outputfile); - - // Move dolibarr_mail.log into a dolibarr_mail.YYYYMMDD.log - if (getDolGlobalString('MAIN_MAIL_DEBUG_LOG_WITH_DATE')) { - $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".log"; - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_move($outputfile, $destfile, 0, 1, 0, 0); - } - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Save content if mail is in error - * Used for debugging. - * - * @param string $message Add also a message - * @return void - */ - public function save_dump_mail_in_err($message = '') - { - global $dolibarr_main_data_root; - - if (@is_writeable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir - $srcfile = $dolibarr_main_data_root."/dolibarr_mail.log"; - - // Add message to dolibarr_mail.log. We do not use dol_syslog() on purpose, - // to be sure to write into dolibarr_mail.log - if ($message) { - // Test constant SYSLOG_FILE_NO_ERROR (should stay a constant defined with define('SYSLOG_FILE_NO_ERROR',1); - if (defined('SYSLOG_FILE_NO_ERROR')) { - $filefd = @fopen($srcfile, 'a+'); - } else { - $filefd = fopen($srcfile, 'a+'); - } - if ($filefd) { - fwrite($filefd, $message."\n"); - fclose($filefd); - dolChmod($srcfile); - } - } - - // Move dolibarr_mail.log into a dolibarr_mail.err or dolibarr_mail.date.err - if (getDolGlobalString('MAIN_MAIL_DEBUG_ERR_WITH_DATE')) { - $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".err"; - } else { - $destfile = $dolibarr_main_data_root."/dolibarr_mail.err"; - } - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_move($srcfile, $destfile, 0, 1, 0, 0); + if (!empty($conf->global->MAIN_UMASK)) + @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); @@ -1382 +985,2 @@ - if (!preg_match('/^[\s\t]*styleCSS)) { - $out .= $this->styleCSS; - } + if (!empty($this->styleCSS)) $out .= $this->styleCSS; @@ -1388,3 +990 @@ - if (!empty($this->bodyCSS)) { - $out .= $this->bodyCSS; - } + if (!empty($this->bodyCSS)) $out .= $this->bodyCSS; @@ -1394 +994,3 @@ - } else { + } + else + { @@ -1404 +1006 @@ - * @return void + * @return string @@ -1408 +1010,2 @@ - if (!empty($this->css)) { + if (!empty($this->css)) + { @@ -1413 +1016,2 @@ - if ($this->css['bgcolor']) { + if ($this->css['bgcolor']) + { @@ -1417 +1021,2 @@ - if ($this->css['bgimage']) { + if ($this->css['bgimage']) + { @@ -1427 +1032 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1435 +1040 @@ - // phpcs:enable + // phpcs:enable @@ -1444 +1049,2 @@ - if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_BA')) { + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) + { @@ -1449,6 +1055,2 @@ - if (isset($this->reply_to) && $this->reply_to) { - $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2; - } - if (isset($this->errors_to) && $this->errors_to) { - $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2; - } + if (isset($this->reply_to) && $this->reply_to) $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2; + if (isset($this->errors_to) && $this->errors_to) $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2; @@ -1457,6 +1059,2 @@ - if (isset($this->addr_cc) && $this->addr_cc) { - $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2; - } - if (isset($this->addr_bcc) && $this->addr_bcc) { - $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ? - } + if (isset($this->addr_cc) && $this->addr_cc) $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2; + if (isset($this->addr_bcc) && $this->addr_bcc) $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ? @@ -1465,3 +1063 @@ - if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) { - $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2; - } + if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2; @@ -1474 +1070,2 @@ - if ($trackid) { + if ($trackid) + { @@ -1478 +1075 @@ - //$out .= 'References: <'.$this->msgid.">".$this->eol2; + $out .= 'References: <'.$this->msgid.">".$this->eol2; @@ -1480 +1077,3 @@ - } else { + } + else + { @@ -1485,3 +1084 @@ - if (!empty($_SERVER['REMOTE_ADDR'])) { - $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2; - } + if (!empty($_SERVER['REMOTE_ADDR'])) $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2; @@ -1501 +1098 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1511 +1108 @@ - // phpcs:enable + // phpcs:enable @@ -1515 +1112,2 @@ - if (is_array($filename_list)) { + if (is_array($filename_list)) + { @@ -1517,5 +1115,5 @@ - for ($i = 0; $i < $filename_list_size; $i++) { - if ($filename_list[$i]) { - if ($mimefilename_list[$i]) { - $filename_list[$i] = $mimefilename_list[$i]; - } + for ($i = 0; $i < $filename_list_size; $i++) + { + if ($filename_list[$i]) + { + if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i]; @@ -1531 +1129 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1540 +1138 @@ - // phpcs:enable + // phpcs:enable @@ -1547 +1145,2 @@ - if ($this->atleastoneimage) { + if ($this->atleastoneimage) + { @@ -1555 +1154,2 @@ - if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) { + if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { @@ -1560 +1160,2 @@ - if ($this->msgishtml) { + if ($this->msgishtml) + { @@ -1563,3 +1164,2 @@ - // TODO We could replace with [Filename.ext] like Gmail do. - $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); // Remove any HTML tags - $strContentAltText = trim(wordwrap($strContentAltText, 75, !getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA') ? "\r\n" : "\n")); + $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); + $strContentAltText = trim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); @@ -1568 +1168 @@ - $strContent = $this->checkIfHTML($strContent); // This add a header and a body including custom CSS to the HTML content + $strContent = $this->checkIfHTML($strContent); @@ -1574,4 +1174,6 @@ - $strContent = rtrim(wordwrap($strContent, 75, !getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA') ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content. - - if ($this->msgishtml) { - if ($this->atleastoneimage) { + $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content. + + if ($this->msgishtml) + { + if ($this->atleastoneimage) + { @@ -1587 +1189,2 @@ - if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part before html part + if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part + { @@ -1601 +1204,2 @@ - if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part after html part + if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part + { @@ -1604 +1208,3 @@ - } else { + } + else + { @@ -1613 +1219,2 @@ - if ($this->atleastoneimage) { + if ($this->atleastoneimage) + { @@ -1624 +1231 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1631,4 +1238,3 @@ - * @param array $cidlist Array of CID if file must be completed with CID code - * @return string String with files encoded - */ - private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist) + * @return string Chaine fichiers encodes + */ + public function write_files($filename_list, $mimetype_list, $mimefilename_list) @@ -1636 +1242 @@ - // phpcs:enable + // phpcs:enable @@ -1640,3 +1246,5 @@ - for ($i = 0; $i < $filename_list_size; $i++) { - if ($filename_list[$i]) { - dol_syslog("CMailFile::write_files: i=$i ".$filename_list[$i]); + for ($i = 0; $i < $filename_list_size; $i++) + { + if ($filename_list[$i]) + { + dol_syslog("CMailFile::write_files: i=$i"); @@ -1644,4 +1252,3 @@ - if ($encoded !== -1) { - if ($mimefilename_list[$i]) { - $filename_list[$i] = $mimefilename_list[$i]; - } + if ($encoded >= 0) + { + if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i]; @@ -1657,4 +1263,0 @@ - if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) { - $out .= "X-Attachment-Id: ".$cidlist[$i].$this->eol; - $out .= "Content-ID: <".$cidlist[$i].'>'.$this->eol; - } @@ -1665 +1268,3 @@ - } else { + } + else + { @@ -1675 +1280 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1684 +1289 @@ - // phpcs:enable + // phpcs:enable @@ -1687,2 +1292,4 @@ - if (is_array($images_list)) { - foreach ($images_list as $img) { + if (is_array($images_list)) + { + foreach ($images_list as $img) + { @@ -1706 +1313 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1716 +1323 @@ - // phpcs:enable + // phpcs:enable @@ -1722 +1329,2 @@ - if (function_exists('fsockopen')) { + if (function_exists('fsockopen')) + { @@ -1727,2 +1334,0 @@ - $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE'; - $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE'; @@ -1731,16 +1337,8 @@ - $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED'; - - if (!empty($this->sendcontext)) { - $smtpContextKey = strtoupper($this->sendcontext); - $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey); - 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; - $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey; - $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$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'; @@ -1750,3 +1348 @@ - if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { - $host = 'ssl://'.$host; - } + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host = 'ssl://'.$host; @@ -1754,3 +1350,3 @@ - //if (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host; - - dol_syslog("Try socket connection to host=".$host." port=".$port." timeout=".$timeout); + //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host; + + dol_syslog("Try socket connection to host=".$host." port=".$port); @@ -1758,8 +1354,6 @@ - $errno = 0; - $errstr = ''; - 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 - $errstr, // and any text that goes with the error - $timeout // timeout for reading/writing data over the socket + 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 + $errstr, // and any text that goes with the error + $timeout // timeout for reading/writing data over the socket @@ -1768,3 +1362 @@ - if (function_exists('stream_set_timeout')) { - stream_set_timeout($socket, $timeout, 0); - } + if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0); @@ -1775,5 +1367,5 @@ - if ($_retVal = $this->server_parse($socket, "220")) { - $_retVal = $socket; - } - } else { - $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : mb_convert_encoding('Error '.$errno.' - '.$errstr, 'UTF-8', 'ISO-8859-1'); + if ($_retVal = $this->server_parse($socket, "220")) $_retVal = $socket; + } + else + { + $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr); @@ -1785 +1377 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1796 +1388 @@ - // phpcs:enable + // phpcs:enable @@ -1800,2 +1392,4 @@ - while (substr($server_response, 3, 1) != ' ') { - if (!($server_response = fgets($socket, 256))) { + while (substr($server_response, 3, 1) != ' ') + { + if (!($server_response = fgets($socket, 256))) + { @@ -1807 +1401,2 @@ - if (!(substr($server_response, 0, 3) == $response)) { + if (!(substr($server_response, 0, 3) == $response)) + { @@ -1816 +1411 @@ - * Search images into html message and init array this->images_encoded if found + * Seearch images into html message and init array this->images_encoded if found @@ -1818 +1413 @@ - * @param string $images_dir Location of physical images files. For example $dolibarr_main_data_root.'/medias' + * @param string $images_dir Location of physical images files @@ -1821 +1416 @@ - private function findHtmlImages($images_dir) + public function findHtmlImages($images_dir) @@ -1823 +1418 @@ - // Build the array of image extensions + // Build the list of image extensions @@ -1826,3 +1420,0 @@ - // We search (into mail body this->html), if we find some strings like "... file=xxx.img" - // For example when: - // @@ -1832 +1424,2 @@ - if (!empty($matches) && !empty($matches[1])) { + if (!empty($matches)) + { @@ -1834,4 +1427,4 @@ - // We are interested in $matches[1] only (the second set of parenthesis into regex) - foreach ($matches[1] as $full) { - $regs = array(); - if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) { // If xxx is 'file=aaa' + foreach ($matches[1] as $full) + { + if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) // If xxx is 'file=aaa' + { @@ -1840 +1433,2 @@ - if (file_exists($images_dir.'/'.$img)) { + if (file_exists($images_dir.'/'.$img)) + { @@ -1842,0 +1437 @@ + @@ -1844,0 +1440 @@ + @@ -1846,0 +1443 @@ + @@ -1848,3 +1445,3 @@ - $regext = array(); - if (preg_match('/^.+\.(\w{3,4})$/', $img, $regext)) { - $ext = strtolower($regext[1]); + if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg)) + { + $ext = strtolower($reg[1]); @@ -1852,0 +1450 @@ + @@ -1854,4 +1452 @@ - $this->html_images[$i]["cid"] = dol_hash($this->html_images[$i]["fullpath"], 'md5'); // Force md5 hash (does not contain special chars) - // type - $this->html_images[$i]["type"] = 'cidfromurl'; - + $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars) @@ -1864 +1459,2 @@ - if (!empty($this->html_images)) { + if (!empty($this->html_images)) + { @@ -1869 +1465,2 @@ - foreach ($this->html_images as $img) { + foreach ($this->html_images as $img) + { @@ -1873 +1470,2 @@ - if (!in_array($fullpath, $inline)) { + if (!in_array($fullpath, $inline)) + { @@ -1875 +1473,2 @@ - if ($image = file_get_contents($fullpath)) { + if ($image = file_get_contents($fullpath)) + { @@ -1877 +1475,0 @@ - $regs = array(); @@ -1892 +1490,3 @@ - } else { + } + else + { @@ -1897,93 +1497,3 @@ - } else { - return 0; - } - } - - /** - * Seearch images with data:image format into html message. - * If we find some, we create it on disk. - * - * @param string $images_dir Location of where to store physicaly images files. For example $dolibarr_main_data_root.'/medias' - * @return int >0 if OK, <0 if KO - */ - private function findHtmlImagesIsSrcData($images_dir) - { - global $conf; - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - // Build the array of image extensions - $extensions = array_keys($this->image_types); - - if (empty($images_dir)) { - //$images_dir = $conf->admin->dir_output.'/temp/'.uniqid('cmailfile'); - $images_dir = $conf->admin->dir_output.'/temp/cmailfile'; - } - - if ($images_dir && !dol_is_dir($images_dir)) { - dol_mkdir($images_dir, DOL_DATA_ROOT); - } - - // Uncomment this for debug - /* - global $dolibarr_main_data_root; - $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log"; - $fp = fopen($outputfile, "w+"); - fwrite($fp, $this->html); - fclose($fp); - */ - - // We search (into mail body this->html), if we find some strings like "... file=xxx.img" - // For example when: - // - $matches = array(); - preg_match_all('/src="data:image\/('.implode('|', $extensions).');base64,([^"]+)"/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found - - if (!empty($matches) && !empty($matches[1])) { - if (empty($images_dir)) { - // No temp directory provided, so we are not able to support convertion of data:image into physical images. - $this->errors[] = 'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk'; - return -1; - } - - $i = count($this->html_images); - foreach ($matches[1] as $key => $ext) { - // We save the image to send in disk - $filecontent = $matches[2][$key]; - - $cid = 'cid000'.dol_hash($filecontent, 'md5'); // The id must not change if image is same - - $destfiletmp = $images_dir.'/'.$cid.'.'.$ext; - - if (!dol_is_file($destfiletmp)) { // If file does not exist yet (this is the case for the first email sent with a data:image inside) - dol_syslog("write the cid file ".$destfiletmp); - $fhandle = @fopen($destfiletmp, 'w'); - if ($fhandle) { - $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent)); - fclose($fhandle); - dolChmod($destfiletmp); - } else { - $this->errors[] = "Failed to open file '".$destfiletmp."' for write"; - return -2; - } - } - - if (file_exists($destfiletmp)) { - // Image full path - $this->html_images[$i]["fullpath"] = $destfiletmp; - // Image name - $this->html_images[$i]["name"] = basename($destfiletmp); - // Content type - $this->html_images[$i]["content_type"] = $this->image_types[strtolower($ext)]; - // cid - $this->html_images[$i]["cid"] = $cid; - // type - $this->html_images[$i]["type"] = 'cidfromdata'; - - $this->html = str_replace('src="data:image/'.$ext.';base64,'.$filecontent.'"', 'src="cid:'.$this->html_images[$i]["cid"].'"', $this->html); - } - $i++; - } - - return 1; - } else { + } + else + { @@ -2006,2 +1516,2 @@ - * 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() @@ -2019,3 +1529,4 @@ - foreach ($arrayaddress as $val) { - $regs = array(); - if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { + foreach ($arrayaddress as $val) + { + if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) + { @@ -2024 +1535,3 @@ - } else { + } + else + { @@ -2029 +1542,2 @@ - if ($email) { + if ($email) + { @@ -2033 +1547,6 @@ - if ($format == 5) { + if ($format == 5) { + $newemail = $name ? $name : $email; + $newemail = ''.$newemail.''; + } + if ($format == 4) + { @@ -2035,6 +1554,3 @@ - $newemail = ''.$newemail.''; - } - if ($format == 4) { - $newemail = $name ? $name : $email; - } - if ($format == 2) { + } + if ($format == 2) + { @@ -2043 +1559,2 @@ - if ($format == 1 || $format == 3) { + if ($format == 1 || $format == 3) + { @@ -2046,8 +1563,5 @@ - if ($format == 0 || $format == 3) { - if (getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL')) { - $newemail = '<'.$email.'>'; - } elseif (!$name) { - $newemail = '<'.$email.'>'; - } else { - $newemail = ($format == 3 ? '"' : '').($encode ? self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>'; - } + if ($format == 0 || $format == 3) + { + if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail = '<'.$email.'>'; + elseif (!$name) $newemail = '<'.$email.'>'; + else $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>'; @@ -2059,4 +1573,3 @@ - if ($maxnumberofemail && $i >= $maxnumberofemail) { - if (count($arrayaddress) > $maxnumberofemail) { - $ret .= '...'; - } + if ($maxnumberofemail && $i >= $maxnumberofemail) + { + if (count($arrayaddress) > $maxnumberofemail) $ret .= '...'; @@ -2078 +1591 @@ - public static function getArrayAddress($address) + public function getArrayAddress($address) @@ -2087,2 +1600,4 @@ - foreach ($arrayaddress as $val) { - if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { + foreach ($arrayaddress as $val) + { + if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) + { @@ -2091 +1606,3 @@ - } else { + } + else + { @@ -2096 +1613 @@ - $ret[$email] = !getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL') ? $name : null; + $ret[$email] = empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL) ? $name : null; --- /tmp/dsg/dolibarr/htdocs/core/class/github_19.0.3_CSMSFile.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_CSMSFile.class.php @@ -32,3 +32,2 @@ - * Usage: $smsfile = new CSMSFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to); - * $smsfile->socid=...; $smsfile->contact_id=...; $smsfile->member_id=...; $smsfile->fk_project=...; - * $smsfile->sendfile(); + * Usage: $smsfile = new CSMSFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to); + * $smsfile->sendfile(); @@ -38,6 +37 @@ - /** - * @var DoliDB Database handler. - */ - public $db; - - /** + /** @@ -47,10 +40,0 @@ - - /** - * @var string[] Array of Error code (or message) - */ - public $errors = array(); - - /** - * @var string end of line character - */ - public $eol; @@ -67,2 +51 @@ - public $contact_id; - public $member_id; + public $contactid; @@ -71,2 +53,0 @@ - - public $deliveryreceipt; @@ -92,6 +73,2 @@ - if (preg_match('/^win/i', PHP_OS)) { - $this->eol = "\r\n"; - } - if (preg_match('/^mac/i', PHP_OS)) { - $this->eol = "\r"; - } + if (preg_match('/^win/i', PHP_OS)) $this->eol = "\r\n"; + if (preg_match('/^mac/i', PHP_OS)) $this->eol = "\r"; @@ -100,6 +77,7 @@ - if (!getDolGlobalString('MAIN_SMS_SENDMODE')) { - $this->error = 'No SMS Engine defined'; - throw new Exception('No SMS Engine defined'); - } - - dol_syslog("CSMSFile::CSMSFile: MAIN_SMS_SENDMODE=".getDolGlobalString('MAIN_SMS_SENDMODE')." charset=".$conf->file->character_set_client." from=".$from.", to=".$to.", msg length=".strlen($msg), LOG_DEBUG); + if (empty($conf->global->MAIN_SMS_SENDMODE)) + { + $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); @@ -109,8 +87,7 @@ - $this->addr_from = $from; - $this->addr_to = $to; - $this->deferred = $deferred; - $this->priority = $priority; - $this->class = $class; - $this->deliveryreceipt = $deliveryreceipt; - $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; @@ -134,16 +111,32 @@ - 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 (getDolGlobalString('MAIN_SMS_DEBUG')) { - $this->dump_sms(); - } - - if (!getDolGlobalString('MAIN_DISABLE_ALL_SMS')) { - // Action according to the choosed sending method - if (getDolGlobalString('MAIN_SMS_SENDMODE')) { - $sendmode = getDolGlobalString('MAIN_SMS_SENDMODE'); // $conf->global->MAIN_SMS_SENDMODE looks like a value 'module' - $classmoduleofsender = getDolGlobalString('MAIN_MODULE_'.strtoupper($sendmode).'_SMS', $sendmode); // $conf->global->MAIN_MODULE_XXX_SMS looks like a value 'class@module' - if ($classmoduleofsender == 'ovh') { - $classmoduleofsender = 'ovhsms@ovh'; // For backward compatibility + 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 + { + dol_include_once('/ovh/class/ovhsms.class.php'); + $sms = new OvhSms($this->db); + $sms->expe = $this->addr_from; + $sms->dest = $this->addr_to; + $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->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); @@ -151,42 +144,5 @@ - - $tmp = explode('@', $classmoduleofsender); - $classfile = $tmp[0]; - $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); - dol_include_once('/'.$module.'/class/'.strtolower($classfile).'.class.php'); - try { - $classname = ucfirst($classfile); - if (class_exists($classname)) { - $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->deliveryreceipt = $this->deliveryreceipt; - - $sms->socid = $this->socid; - $sms->contact_id = $this->contact_id; - $sms->member_id = $this->member_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 (getDolGlobalString('MAIN_SMS_DEBUG')) { - $this->dump_sms_result($res); - } - } - } else { - $sms = new stdClass(); - $sms->error = 'The SMS manager "'.$classfile.'" defined into SMS setup MAIN_MODULE_'.strtoupper($sendmode).'_SMS is not found'; - } - } catch (Exception $e) { - dol_print_error('', 'Error to get list of senders: '.$e->getMessage()); + 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); @@ -194 +150,44 @@ - } else { + } + 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 + { @@ -200 +199,3 @@ - } else { + } + else + { @@ -211,13 +212,14 @@ - // 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 + // 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 + { @@ -233 +234,0 @@ - fputs($fp, "DeliveryReceipt: ".$this->deliveryreceipt."\n"); @@ -237 +238,2 @@ - dolChmod($outputfile); + if (!empty($conf->global->MAIN_UMASK)) + @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); @@ -241,23 +243,25 @@ - // 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); - dolChmod($outputfile); - } - } + // 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_19.0.3_antivir.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_antivir.class.php @@ -48,3 +48,3 @@ - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; @@ -62 +62 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -69 +69 @@ - * @return int Return integer <0 if KO (-98 if error, -99 if virus), 0 if OK + * @return int <0 if KO (-98 if error, -99 if virus), 0 if OK @@ -73 +73 @@ - // phpcs:enable + // phpcs:enable @@ -78,3 +78,4 @@ - if (preg_match('/\.virus$/i', $file)) { - $this->errors[] = 'File has an extension saying file is a virus'; - return -97; + if (preg_match('/\.virus$/i', $file)) + { + $this->errors[] = 'File has an extension saying file is a virus'; + return -97; @@ -84 +84,0 @@ - //$fullcommand="/usr/bin/clamdscan --fdpass '/tmp/phpuxoAEo'" @@ -86 +86 @@ - //var_dump($fullcommand); + $fullcommand .= ' 2>&1'; // This is to get error output @@ -88 +88,3 @@ - $safemode = ini_get("safe_mode"); + $output = array(); + $return_var = 0; + $safemode = ini_get("safe_mode"); @@ -91,4 +93,2 @@ - // Run CLI command. - include_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php'; - $utils = new Utils($this->db); - $outputfile = $conf->user->dir_temp.'/antivir.tmp'; + // Run CLI command. If run of Windows, you can get return with echo %ERRORLEVEL% + $lastline = exec($fullcommand, $output, $return_var); @@ -96 +96 @@ - $result = $utils->executeCLI($fullcommand, $outputfile); + if (is_null($output)) $output = array(); @@ -98,3 +98 @@ - $return_var = $result['result']; - $output = $result['output']; - $errorstring = $result['error']; + //print "x".$lastline." - ".join(',',$output)." - ".$return_var."y";exit; @@ -102,2 +100,20 @@ - if (is_null($output)) { - $output = array(); + /* + $outputfile=$conf->admin->dir_temp.'/dol_avscan_file.out.'.session_id(); + $handle = fopen($outputfile, 'w'); + if ($handle) + { + $handlein = popen($fullcommand, 'r'); + while (!feof($handlein)) + { + $read = fgets($handlein); + fwrite($handle,$read); + } + pclose($handlein); + + $errormsg = fgets($handle,2048); + $this->output=$errormsg; + + fclose($handle); + + if (! empty($conf->global->MAIN_UMASK)) + @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); @@ -104,0 +121,8 @@ + else + { + $langs->load("errors"); + dol_syslog("Failed to open file ".$outputfile,LOG_ERR); + $this->error="ErrorFailedToWriteInDir"; + $return=-1; + } + */ @@ -106 +130 @@ - dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".$output); + dol_syslog("AntiVir::dol_avscan_file Result return_var=".$return_var." output=".join(',', $output)); @@ -109,2 +133,3 @@ - if ($return_var == $returncodevirus) { // Virus found - $this->errors = array($errorstring, $output); + if ($return_var == $returncodevirus) // Virus found + { + $this->errors = $output; @@ -114,2 +139,3 @@ - if ($return_var > 0) { // If other error - $this->errors = array($errorstring, $output); + if ($return_var > 0) // If other error + { + $this->errors = $output; @@ -151 +177 @@ - if (!preg_match('/%file/', $conf->global->MAIN_ANTIVIRUS_PARAM)) { + if (!preg_match('/%file/', $conf->global->MAIN_ANTIVIRUS_PARAM)) @@ -153 +178,0 @@ - } @@ -155,3 +180 @@ - if (preg_match("/\s/", $command)) { - $command = escapeshellarg($command); // Force use of quotes on command. Using escapeshellcmd fails. - } + if (preg_match("/\s/", $command)) $command = escapeshellarg($command); // Use quotes on command. Using escapeshellcmd fails. @@ -159,3 +182 @@ - $forbidden_chars_to_replace = array("*", "?", "\"", "<", ">", "|", "[", "]", ";", '°', '$'); - $ret = dol_sanitizePathName($command).' '.dol_string_nospecial($param, '_', $forbidden_chars_to_replace); - + $ret = $command.' '.$param; @@ -163 +184 @@ - //print "xx".$ret."xx";exit; + //print "xx".$ret."xx";exit; --- /tmp/dsg/dolibarr/htdocs/core/class/github_19.0.3_canvas.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_canvas.class.php @@ -32,3 +32,3 @@ - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; @@ -48,10 +48,10 @@ - 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 + + + /** @@ -78,11 +78,5 @@ - $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; @@ -105,9 +99,9 @@ - $this->targetmodule = $module; - $this->canvas = $canvas; - $this->card = $card; - $this->dirmodule = $module; - // Correct values if canvas is into an external module - $regs = array(); - if (preg_match('/^([^@]+)@([^@]+)$/i', $canvas, $regs)) { - $this->canvas = $regs[1]; - $this->dirmodule = $regs[2]; + $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]; @@ -116,5 +110,3 @@ - if ($this->dirmodule == 'thirdparty') { - $this->dirmodule = 'societe'; - } - - // Control file + if ($this->dirmodule == 'thirdparty') { $this->dirmodule = 'societe'; } + + // Control file @@ -122,7 +114,9 @@ - if (file_exists($controlclassfile)) { - // Include actions class (controller) - 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); + 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); @@ -133,10 +127,11 @@ - 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 + /** @@ -152,8 +147,6 @@ - // phpcs:enable - if (is_object($this->control) && method_exists($this->control, 'assign_values')) { - $this->control->assign_values($action, $id, $ref); - } - } - - /** - * Return if a template exists to display as canvas (if it exists) + // 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) @@ -162,17 +155,11 @@ - * @return int 0=Canvas template file does not exist, 1=Canvas template file exists - */ - public function displayCanvasExists($action) - { - // template_dir should be '/'.$this->dirmodule.'/canvas/'.$this->canvas.'/tpl/', for example '/mymodule/canvas/product/tpl' - 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 @@ -188 +175 @@ - // phpcs:enable + // phpcs:enable @@ -198 +185 @@ - // https://wiki.dolibarr.org/index.php/Canvas_development + // http://wiki.dolibarr.org/index.php/Canvas_development @@ -207 +194 @@ - return (is_object($this->control)); + return (is_object($this->control)); @@ -212 +199 @@ - * @deprecated Use the doActions of hooks instead of this. + * @deprecated Use the doActions of hooks instead of this. @@ -219 +206 @@ - * @see https://wiki.dolibarr.org/index.php/Canvas_development + * @see http://wiki.dolibarr.org/index.php/Canvas_development @@ -223 +210,2 @@ - if (method_exists($this->control, 'doActions')) { + if (method_exists($this->control, 'doActions')) + { --- /tmp/dsg/dolibarr/htdocs/core/class/github_19.0.3_ccountry.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_ccountry.class.php @@ -25 +25,3 @@ -require_once DOL_DOCUMENT_ROOT.'/core/class/commondict.class.php'; +//require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; @@ -31 +33 @@ -class Ccountry extends CommonDict +class Ccountry // extends CommonObject @@ -32,0 +35,15 @@ + /** + * @var DoliDB Database handler. + */ + public $db; + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string[] Error codes (or messages) + */ + public $errors = array(); + @@ -35,0 +53,6 @@ + /** + * @var int ID + */ + public $id; + + public $code; @@ -36,0 +60,7 @@ + + /** + * @var string Countries label + */ + public $label; + + public $active; @@ -43,20 +73,21 @@ - /** - * 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 Return integer <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { + /** + * 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; @@ -66,12 +97,4 @@ - if (isset($this->code)) { - $this->code = trim($this->code); - } - if (isset($this->code_iso)) { - $this->code_iso = trim($this->code_iso); - } - if (isset($this->label)) { - $this->label = trim($this->label); - } - if (isset($this->active)) { - $this->active = trim($this->active); - } + if (isset($this->code)) $this->code = trim($this->code); + if (isset($this->code_iso)) $this->code_iso = trim($this->code_iso); + if (isset($this->label)) $this->label = trim($this->label); + if (isset($this->active)) $this->active = trim($this->active); @@ -82,2 +105,2 @@ - // Insert request - $sql = "INSERT INTO ".$this->db->prefix()."c_country("; + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country("; @@ -89 +112 @@ - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; @@ -94 +117 @@ - $sql .= " ".(!isset($this->active) ? 'NULL' : "'".$this->db->escape($this->active)."'"); + $sql .= " ".(!isset($this->active) ? 'NULL' : "'".$this->db->escape($this->active)."'").""; @@ -99,16 +122,16 @@ - 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($this->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", 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_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); @@ -118 +141,3 @@ - } else { + } + else + { @@ -120,65 +145,65 @@ - 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 ".$this->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 Return integer <0 if KO, >0 if OK - */ - public function update($user = null, $notrigger = 0) - { + 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 = ".$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; @@ -188,12 +213,4 @@ - if (isset($this->code)) { - $this->code = trim($this->code); - } - if (isset($this->code_iso)) { - $this->code_iso = trim($this->code_iso); - } - if (isset($this->label)) { - $this->label = trim($this->label); - } - if (isset($this->active)) { - $this->active = trim($this->active); - } + if (isset($this->code)) $this->code = trim($this->code); + if (isset($this->code_iso)) $this->code_iso = trim($this->code_iso); + if (isset($this->label)) $this->label = trim($this->label); + if (isset($this->active)) $this->active = trim($this->active); @@ -205,2 +222,2 @@ - // Update request - $sql = "UPDATE ".$this->db->prefix()."c_country SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET"; @@ -210,2 +227,2 @@ - $sql .= " active=".(isset($this->active) ? $this->active : "null"); - $sql .= " WHERE rowid=".((int) $this->id); + $sql .= " active=".(isset($this->active) ? $this->active : "null").""; + $sql .= " WHERE rowid=".$this->id; @@ -216,11 +233,10 @@ - $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); + $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); @@ -230 +246,3 @@ - } else { + } + else + { @@ -234,5 +252,5 @@ - } - - - /** - * Delete object in database + } + + + /** + * Delete object in database @@ -240,3 +258,3 @@ - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int Return integer <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 @@ -245,0 +264 @@ + global $conf, $langs; @@ -248,2 +267,2 @@ - $sql = "DELETE FROM ".$this->db->prefix()."c_country"; - $sql .= " WHERE rowid=".((int) $this->id); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country"; + $sql .= " WHERE rowid=".$this->id; @@ -255,10 +274,9 @@ - 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); + 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); @@ -268 +286,3 @@ - } else { + } + else + { @@ -274,15 +294,15 @@ - /** - * 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_19.0.3_comment.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_comment.class.php @@ -35,7 +35,4 @@ - * @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 = ''; + @@ -50,4 +47,4 @@ - * Date modification record (tms) - * - * @var integer - */ + * Date modification record (tms) + * + * @var integer + */ @@ -57,9 +54,9 @@ - * Date creation record (datec) - * - * @var integer - */ - public $datec; - - /** - * @var int ID - */ + * Date creation record (datec) + * + * @var integer + */ + public $datec; + + /** + * @var int ID + */ @@ -69,2 +66,2 @@ - * @var int ID - */ + * @var int ID + */ @@ -74 +71 @@ - * @var int Entity + * @var int Entity @@ -78,3 +74,0 @@ - /** - * @var string Import key - */ @@ -85,3 +78,0 @@ - /** - * @var Comment Object oldcopy - */ @@ -107 +98 @@ - * @return int Return integer <0 if KO, Id of created object if OK + * @return int <0 if KO, Id of created object if OK @@ -116 +107 @@ - $sql = "INSERT INTO ".$this->db->prefix().$this->table_element." ("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; @@ -131 +122 @@ - $sql .= ", ".((int) $user->id); + $sql .= ", ".$user->id.""; @@ -143,9 +134,8 @@ - if (!$resql) { - $error++; - $this->errors[] = "Error ".$this->db->lasterror(); - } - - if (!$error) { - $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element); - - if (!$notrigger) { + 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) + { @@ -154,3 +144 @@ - if ($result < 0) { - $error++; - } + if ($result < 0) { $error++; } @@ -162,2 +150,4 @@ - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { @@ -169 +159,3 @@ - } else { + } + else + { @@ -180,2 +172,2 @@ - * @param string $ref ref object - * @return int Return integer <0 if KO, 0 if not found, >0 if OK + * @param int $ref ref object + * @return int <0 if KO, 0 if not found, >0 if OK @@ -198,2 +190,2 @@ - $sql .= " FROM ".$this->db->prefix().$this->table_element." as c"; - $sql .= " WHERE c.rowid = ".((int) $id); + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c"; + $sql .= " WHERE c.rowid = ".$id; @@ -203 +195,2 @@ - if ($resql) { + if ($resql) + { @@ -206 +199,2 @@ - if ($num_rows) { + if ($num_rows) + { @@ -223,6 +217,5 @@ - if ($num_rows) { - return 1; - } else { - return 0; - } - } else { + if ($num_rows) return 1; + else return 0; + } + else + { @@ -240 +233 @@ - * @return int Return integer <=0 if KO, >0 if OK + * @return int <=0 if KO, >0 if OK @@ -248,6 +241,2 @@ - 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); @@ -257 +246 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; @@ -265 +254 @@ - $sql .= " WHERE rowid=".((int) $this->id); + $sql .= " WHERE rowid=".$this->id; @@ -271,7 +260,6 @@ - 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) + { @@ -280,3 +268 @@ - if ($result < 0) { - $error++; - } + if ($result < 0) { $error++; } @@ -288,2 +274,4 @@ - if ($error) { - foreach ($this->errors as $errmsg) { + if ($error) + { + foreach ($this->errors as $errmsg) + { @@ -290,0 +279,52 @@ + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } + else + { + $this->db->commit(); + return 1; + } + } + + + /** + * Delete task from 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; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $error = 0; + + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE rowid=".$this->id; + + $resql = $this->db->query($sql); + 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++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach ($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); @@ -303,52 +343 @@ - * Delete task from database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function delete($user, $notrigger = 0) - { - global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - $error = 0; - - $this->db->begin(); - - $sql = "DELETE FROM ".$this->db->prefix().$this->table_element; - $sql .= " WHERE rowid=".((int) $this->id); - - $resql = $this->db->query($sql); - 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++; - } - // End call triggers - } - } - - // 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); - } - $this->db->rollback(); - return -1 * $error; - } else { - $this->db->commit(); - return 1; - } - } - - - /** - * Load comments linked with current task into ->comments + * Load comments linked with current task @@ -358 +347 @@ - * @return int Result + * @return array Comment array @@ -363 +351,0 @@ - @@ -365 +352,0 @@ - @@ -369,3 +356,3 @@ - $sql .= " FROM ".$this->db->prefix().$this->table_element." as c"; - $sql .= " WHERE c.fk_element = ".((int) $fk_element); - $sql .= " AND c.element_type = '".$this->db->escape($element_type)."'"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c"; + $sql .= " WHERE c.fk_element = ".$fk_element; + $sql .= " AND c.element_type = '".$db->escape($element_type)."'"; @@ -376,5 +363,8 @@ - $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)) + { @@ -386 +376 @@ - $this->db->free($resql); + $db->free($resql); --- /tmp/dsg/dolibarr/htdocs/core/class/github_19.0.3_commondocgenerator.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commondocgenerator.class.php @@ -7,2 +7,2 @@ - * Copyright (C) 2016-2023 Charlene Benke - * Copyright (C) 2018-2023 Frédéric France + * Copyright (C) 2016 Charlie Benke + * Copyright (C) 2018 Frédéric France @@ -10 +9,0 @@ - * Copyright (C) 2024 Mélina Joum @@ -35 +34 @@ - * Parent class for documents (PDF, ODT, ...) generators + * Parent class for documents generators @@ -40,10 +38,0 @@ - * @var string Model name - */ - public $name = ''; - - /** - * @var string Version - */ - public $version = ''; - - /** @@ -53,0 +43,5 @@ + /** + * @var string[] Array of error strings + */ + public $errors = array(); + @@ -55,7 +49,2 @@ - * @var string[] Array of error strings - */ - public $errors = array(); - - /** - * @var DoliDB Database handler. - */ + * @var DoliDB Database handler. + */ @@ -64,3 +53,3 @@ - /** - * @var Extrafields object - */ + /** + * @var Extrafields object + */ @@ -68,104 +56,0 @@ - - /** - * @var int If set to 1, save the fullname of generated file with path as the main doc when generating a doc with this template. - */ - public $update_main_doc_field; - - /** - * @var string The name of constant to use to scan ODT files (Exemple: 'COMMANDE_ADDON_PDF_ODT_PATH') - */ - public $scandir; - - /** - * @var string model description (short text) - */ - public $description; - - /** - * @var array - */ - public $format; - - /** - * @var string pdf, odt, etc - */ - public $type; - - public $page_hauteur; - public $page_largeur; - public $marge_gauche; - public $marge_droite; - public $marge_haute; - public $marge_basse; - - public $option_logo; - public $option_tva; - public $option_multilang; - public $option_freetext; - public $option_draft_watermark; - public $watermark; - - public $option_modereg; - public $option_condreg; - public $option_escompte; - public $option_credit_note; - - public $tva; - public $tva_array; - public $localtax1; - public $localtax2; - - /** - * @var int Tab Title Height - */ - public $tabTitleHeight; - - /** - * @var array default title fields style - */ - public $defaultTitlesFieldsStyle; - - /** - * @var array default content fields style - */ - public $defaultContentsFieldsStyle; - - /** - * @var Societe Issuer of document - */ - public $emetteur; - - /** - * @var array Minimum version of PHP required by module. - * e.g.: PHP ≥ 7.1 = array(7, 1) - */ - public $phpmin = array(7, 1); - - /** - * @var array Array of columns - */ - public $cols; - - /** - * @var array Array with result of doc generation. content is array('fullpath'=>$file) - */ - public $result; - - public $posxlabel; - public $posxup; - public $posxref; - public $posxpicture; // For picture - public $posxdesc; // For description - public $posxqty; - public $posxpuht; - public $posxtva; - public $posxtotalht; - public $postotalht; - public $posxunit; - public $posxdiscount; - public $posxworkload; - public $posxtimespent; - public $posxprogress; - public $atleastonephoto; - public $atleastoneratenotnull; - public $atleastonediscount; @@ -177,221 +62,170 @@ - */ - 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 - 'myuser_birth'=>dol_print_date($user->birth, 'day', 'gmt'), - 'myuser_dateemployment'=>dol_print_date($user->dateemployment, 'day', 'tzuser'), - 'myuser_dateemploymentend'=>dol_print_date($user->dateemploymentend, 'day', 'tzuser'), - 'myuser_gender'=>$user->gender, - ); - // 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, - 'mycompany_socialobject'=>$mysoc->socialobject, - '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 - * For example {company_name}, {company_name_alias} - * - * @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 $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_capital_formated'=> price($object->capital, 0, '', 1, -1), - '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); - } + */ + 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); + } @@ -401 +235 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -410,3 +244,3 @@ - public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable + public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable @@ -415 +249,2 @@ - if (empty($object->country) && !empty($object->country_code)) { + if (empty($object->country) && !empty($object->country_code)) + { @@ -418 +253,2 @@ - if (empty($object->state) && !empty($object->state_code)) { + if (empty($object->state) && !empty($object->state_code)) + { @@ -439,0 +276 @@ + $array_key.'_jabberid' => $object->jabberid, // deprecated @@ -451,6 +288,7 @@ - // 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); + } @@ -461 +299,39 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // 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), + '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 (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 @@ -465,41 +340,0 @@ - * @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), - '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 - /** - * Define array with couple substitution key => substitution value - * Note that vars into substitutions array are formatted. - * @@ -508 +343 @@ - * @param string $array_key Name of the key for return array + * @param string $array_key Name of the key for return array @@ -513 +348 @@ - // phpcs:enable + // phpcs:enable @@ -518,2 +353,3 @@ - - if ($object->element == 'facture') { + $remain_to_pay = 0; + if ($object->element == 'facture') + { @@ -521 +357,2 @@ - if ($object->fk_facture_source > 0) { + if ($object->fk_facture_source > 0) + { @@ -528,83 +365,3 @@ - } - - $date = (isset($object->element) && $object->element == 'contrat' && isset($object->date_contrat)) ? $object->date_contrat : (isset($object->date) ? $object->date : null); - - if (get_class($object) == 'CommandeFournisseur') { - /* @var $object CommandeFournisseur*/ - $object->date_validation = $object->date_valid; - $object->date_commande = $object->date; - } - $resarray = array( - $array_key.'_id'=>$object->id, - $array_key.'_ref' => (property_exists($object, 'ref') ? $object->ref : ''), - $array_key.'_label' => (property_exists($object, 'label') ? $object->label : ''), - $array_key.'_ref_ext' => (property_exists($object, 'ref_ext') ? $object->ref_ext : ''), - $array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)), - $array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), - $array_key.'_source_invoice_ref'=>((empty($invoice_source) || empty($invoice_source->ref)) ? '' : $invoice_source->ref), - // Dates - $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_limit_rfc'=>(!empty($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'dayrfc') : ''), - $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') : ''), - $array_key.'_date_approve'=>(!empty($object->date_approve) ? dol_print_date($object->date_approve, 'day') : ''), - $array_key.'_date_delivery_planed'=>(!empty($object->delivery_date) ? dol_print_date($object->delivery_date, 'day') : ''), - $array_key.'_date_close'=>(!empty($object->date_cloture) ? dol_print_date($object->date_cloture, 'dayhour') : ''), - - $array_key.'_payment_mode_code'=>$object->mode_reglement_code, - $array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) != 'PaymentType'.$object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) : $object->mode_reglement), - $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.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs), - $array_key.'_total_vat_locale'=>(!empty($object->total_vat) ? price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)), - $array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs), - $array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs), - $array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs), - - $array_key.'_total_ht'=>price2num($object->total_ht), - $array_key.'_total_vat'=>(!empty($object->total_vat) ? price2num($object->total_vat) : price2num($object->total_tva)), - $array_key.'_total_localtax1'=>price2num($object->total_localtax1), - $array_key.'_total_localtax2'=>price2num($object->total_localtax2), - $array_key.'_total_ttc'=>price2num($object->total_ttc), - - $array_key.'_multicurrency_code' => $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_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), - $array_key.'_multicurrency_total_ttc_locale' => price($object->multicurrency_total_ttc, 0, $outputlangs), - - $array_key.'_note_private'=>$object->note_private, - $array_key.'_note_public'=>$object->note_public, - $array_key.'_note'=>$object->note_public, // For backward compatibility - - // Payments - $array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs), - $array_key.'_already_payed'=>price2num($sumpayed), - $array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs), - $array_key.'_already_deposit'=>price2num($sumdeposit), - $array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs), - $array_key.'_already_creditnote'=>price2num($sumcreditnote), - - $array_key.'_already_payed_all_locale'=>price(price2num($already_payed_all, 'MT'), 0, $outputlangs), - $array_key.'_already_payed_all'=> price2num($already_payed_all, 'MT'), - - // Remain to pay with all known information (except open direct debit requests) - $array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $already_payed_all, 'MT'), 0, $outputlangs), - $array_key.'_remain_to_pay'=>price2num($object->total_ttc - $already_payed_all, 'MT') - ); - - if (in_array($object->element, array('facture', 'invoice', 'supplier_invoice', 'facture_fournisseur'))) { - $bank_account = null; - - if (property_exists($object, 'fk_account') && $object->fk_account > 0) { + $remain_to_pay = $sumpayed - $sumdeposit - $sumcreditnote; + + if ($object->fk_account > 0) { @@ -615,6 +371,0 @@ - - $resarray[$array_key.'_bank_iban'] = (empty($bank_account) ? '' : $bank_account->iban); - $resarray[$array_key.'_bank_bic'] = (empty($bank_account) ? '' : $bank_account->bic); - $resarray[$array_key.'_bank_label'] = (empty($bank_account) ? '' : $bank_account->label); - $resarray[$array_key.'_bank_number'] = (empty($bank_account) ? '' : $bank_account->number); - $resarray[$array_key.'_bank_proprio'] =(empty($bank_account) ? '' : $bank_account->proprio); @@ -623 +374,71 @@ - if (method_exists($object, 'getTotalDiscount') && in_array(get_class($object), array('Propal', 'Proposal', 'Commande', 'Facture', 'SupplierProposal', 'CommandeFournisseur', 'FactureFournisseur'))) { + $date = ($object->element == 'contrat' ? $object->date_contrat : $object->date); + + $resarray = array( + $array_key.'_id'=>$object->id, + $array_key.'_ref'=>$object->ref, + $array_key.'_ref_ext'=>$object->ref_ext, + $array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)), + $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.'_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_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') : ''), + $array_key.'_date_delivery_planed'=>(!empty($object->date_livraison) ?dol_print_date($object->date_livraison, 'day') : ''), + $array_key.'_date_close'=>(!empty($object->date_cloture) ?dol_print_date($object->date_cloture, 'dayhour') : ''), + + $array_key.'_payment_mode_code'=>$object->mode_reglement_code, + $array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) != 'PaymentType'.$object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) : $object->mode_reglement), + $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.'_bank_iban'=>$bank_account->iban, + $array_key.'_bank_bic'=>$bank_account->bic, + + $array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs), + $array_key.'_total_vat_locale'=>(!empty($object->total_vat) ?price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)), + $array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs), + $array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs), + $array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs), + + $array_key.'_total_ht'=>price2num($object->total_ht), + $array_key.'_total_vat'=>(!empty($object->total_vat) ?price2num($object->total_vat) : price2num($object->total_tva)), + $array_key.'_total_localtax1'=>price2num($object->total_localtax1), + $array_key.'_total_localtax2'=>price2num($object->total_localtax2), + $array_key.'_total_ttc'=>price2num($object->total_ttc), + + $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_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), + $array_key.'_multicurrency_total_ttc_locale' => price($object->multicurrency_total_ttc, 0, $outputlangs), + + $array_key.'_note_private'=>$object->note, + $array_key.'_note_public'=>$object->note_public, + $array_key.'_note'=>$object->note_public, // For backward compatibility + + // Payments + $array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs), + $array_key.'_already_payed'=>price2num($sumpayed), + $array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs), + $array_key.'_already_deposit'=>price2num($sumdeposit), + $array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs), + $array_key.'_already_creditnote'=>price2num($sumcreditnote), + + $array_key.'_already_payed_all_locale'=>price(price2num($already_payed_all, 'MT'), 0, $outputlangs), + $array_key.'_already_payed_all'=> price2num($already_payed_all, 'MT'), + + // Remain to pay with all know information (except open direct debit requests) + $array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $remain_to_pay, 'MT'), 0, $outputlangs), + $array_key.'_remain_to_pay'=>price2num($object->total_ttc - $remain_to_pay, 'MT') + ); + + if (method_exists($object, 'getTotalDiscount')) { @@ -632,2 +453,4 @@ - if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0) { - if (!is_object($object->project)) { + if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0) + { + if (!is_object($object->project)) + { @@ -642,6 +464,0 @@ - } else { // empty replacement - $resarray[$array_key.'_project_ref'] =''; - $resarray[$array_key.'_project_title'] = ''; - $resarray[$array_key.'_project_description'] = ''; - $resarray[$array_key.'_project_date_start'] = ''; - $resarray[$array_key.'_project_date_end'] = ''; @@ -651 +468,2 @@ - if (is_array($object->lines) && count($object->lines) > 0) { + if (is_array($object->lines) && count($object->lines) > 0) + { @@ -653,6 +471,4 @@ - // Set substitution keys for different VAT rates - foreach ($object->lines as $line) { - // $line->tva_tx format depends on database field accuracy, 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; - } + foreach ($object->lines as $line) + { + // $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; @@ -661 +477 @@ - // $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) @@ -663,3 +479 @@ - if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) { - $resarray[$array_key.'_total_vat_'.$vatformated] = 0; - } + if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0; @@ -672,2 +486,2 @@ - // Calculate total up and total discount percentage - // Note that this added fields does not match a field into database in Dolibarr (Dolibarr manage discount on lines not as a global property of object) + // @GS: Calculate total up and total discount percentage + // Note that this added fields correspond to nothing in Dolibarr (Dolibarr manage discount on lines not globally) @@ -676 +490 @@ - if (method_exists($object, 'getTotalDiscount') && in_array(get_class($object), array('Propal', 'Proposal', 'Commande', 'Facture', 'SupplierProposal', 'CommandeFournisseur', 'FactureFournisseur'))) { + if (method_exists($object, 'getTotalDiscount')) { @@ -691 +505,2 @@ - if (is_array($object->array_options) && count($object->array_options)) { + if (is_array($object->array_options) && count($object->array_options)) + { @@ -700 +515 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -703 +517,0 @@ - * Note that vars into substitutions array are formatted. @@ -712 +526,3 @@ - // phpcs:enable + // phpcs:enable + global $conf; + @@ -716,8 +532,4 @@ - - '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_desc'=>(empty($line->product_desc) ? '' : $line->product_desc), - + '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, @@ -726,3 +538,3 @@ - '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), @@ -740 +552 @@ - // Dates + // Dates @@ -743,14 +555,14 @@ - '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), @@ -759,5 +571,6 @@ - // Units - if (getDolGlobalInt('PRODUCT_USE_UNITS')) { - $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); - $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); - } + // Units + if ($conf->global->PRODUCT_USE_UNITS) + { + $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); + } @@ -773,9 +586,11 @@ - $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)) { + $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)) + { @@ -784 +599,2 @@ - foreach ($extralabels as $key => $label) { + foreach ($extralabels as $key) + { @@ -788 +604,2 @@ - if ($columns != "") { + if ($columns != "") + { @@ -790,3 +607,4 @@ - $resql = $this->db->query("SELECT ".$columns." FROM ".$this->db->prefix()."product_fournisseur_price_extrafields AS ex INNER JOIN ".$this->db->prefix()."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$this->db->escape($line->ref_supplier)."'"); - - if ($this->db->num_rows($resql) > 0) { + $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) + { @@ -795,2 +613,3 @@ - foreach ($extralabels as $key => $label) { - $resarray['line_product_supplier_'.$key] = $resql->$key; + foreach ($extralabels as $key) + { + $resarray['line_product_supplier_'.$key] = $resql->{$key}; @@ -801 +620 @@ - } + } @@ -804 +623,2 @@ - if (isset($line->fk_product) && $line->fk_product > 0) { + if (isset($line->fk_product) && $line->fk_product > 0) + { @@ -807,15 +627,2 @@ - if (!empty($tmpproduct->array_options) && is_array($tmpproduct->array_options)) { - foreach ($tmpproduct->array_options as $key => $label) { - $resarray["line_product_".$key] = $label; - } - } - } else { - // Set unused placeholders as blank - $extrafields->fetch_name_optionals_label("product"); - $extralabels = $extrafields->attributes["product"]['label']; - - if (!empty($extralabels) && is_array($extralabels)) { - foreach ($extralabels as $key => $label) { - $resarray['line_product_options_'.$key] = ''; - } - } + foreach ($tmpproduct->array_options as $key=>$label) + $resarray["line_product_".$key] = $label; @@ -827,14 +634,13 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * Note that vars into substitutions array are formatted. - * - * @param Expedition $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 - * @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; @@ -845,66 +651,146 @@ - $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 Object $object Dolibarr Object - * @param Translate $outputlangs Language object for output - * @param boolean|int $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 = 1) - { - // phpcs:enable - $array_other = array(); - if (!empty($object)) { - foreach ($object as $key => $value) { - if (in_array($key, array('db', 'fields', 'lines', 'modelpdf', 'model_pdf'))) { // discard some properties - continue; + $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'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key=>$label) + { + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') + { + $object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]); + $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'])); @@ -912,18 +798,3 @@ - if (!empty($value)) { - if (!is_array($value) && !is_object($value)) { - $array_other['object_'.$key] = $value; - } elseif (is_array($value) && $recursive) { - $tmparray = $this->get_substitutionarray_each_var_object($value, $outputlangs, 0); - if (!empty($tmparray) && is_array($tmparray)) { - foreach ($tmparray as $key2 => $value2) { - $array_other['object_'.$key.'_'.preg_replace('/^object_/', '', $key2)] = $value2; - } - } - } elseif (is_object($value) && $recursive) { - $tmparray = $this->get_substitutionarray_each_var_object($value, $outputlangs, 0); - if (!empty($tmparray) && is_array($tmparray)) { - foreach ($tmparray as $key2 => $value2) { - $array_other['object_'.$key.'_'.preg_replace('/^object_/', '', $key2)] = $value2; - } - } - } + 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]]; @@ -931,44 +802,2 @@ - } - } - - //var_dump($array_other); - - return $array_other; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Fill array with couple extrafield key => extrafield value - * Note that vars into substitutions array are formatted. - * - * @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'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) { - $formatedarrayoption = $object->array_options; - - if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') { - $formatedarrayoption['options_'.$key] = price2num($formatedarrayoption['options_'.$key]); - $formatedarrayoption['options_'.$key.'_currency'] = price($formatedarrayoption['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' => $formatedarrayoption['options_'.$key.'_currency'])); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') { - $valueofselectkey = $formatedarrayoption['options_'.$key]; - if (array_key_exists($valueofselectkey, $extrafields->attributes[$object->table_element]['param'][$key]['options'])) { - $formatedarrayoption['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$valueofselectkey]; - } else { - $formatedarrayoption['options_'.$key] = ''; - } - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { - $valArray = explode(',', $formatedarrayoption['options_'.$key]); + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { + $valArray = explode(',', $object->array_options['options_'.$key]); @@ -976 +805 @@ - foreach ($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt => $valopt) { + foreach ($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt=>$valopt) { @@ -981,11 +810,10 @@ - $formatedarrayoption['options_'.$key] = implode(', ', $output); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') { - if (strlen($formatedarrayoption['options_'.$key]) > 0) { - $date = $formatedarrayoption['options_'.$key]; - $formatedarrayoption['options_'.$key] = dol_print_date($date, 'day'); // using company output language - $formatedarrayoption['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format - $formatedarrayoption['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format - } else { - $formatedarrayoption['options_'.$key] = ''; - $formatedarrayoption['options_'.$key.'_locale'] = ''; - $formatedarrayoption['options_'.$key.'_rfc'] = ''; + $object->array_options['options_'.$key] = implode(', ', $output); + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') + { + if (strlen($object->array_options['options_'.$key]) > 0) + { + $date = $object->array_options['options_'.$key]; + $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 @@ -993,12 +821,23 @@ - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $formatedarrayoption['options_'.$key.'_locale'])); - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $formatedarrayoption['options_'.$key.'_rfc'])); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') { - $datetime = $formatedarrayoption['options_'.$key]; - $formatedarrayoption['options_'.$key] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : ''); // using company output language - $formatedarrayoption['options_'.$key.'_locale'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : ''); // using output language format - $formatedarrayoption['options_'.$key.'_rfc'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : ''); // international format - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $formatedarrayoption['options_'.$key.'_locale'])); - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $formatedarrayoption['options_'.$key.'_rfc'])); - } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'link') { - $id = $formatedarrayoption['options_'.$key]; - if ($id != "") { + 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') + { + $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 + $object->array_options['options_'.$key.'_locale'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour', 'tzserver', $outputlangs) : ''); // using output language format + $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') + { + $id = $object->array_options['options_'.$key]; + if ($id != "") + { @@ -1010 +849,2 @@ - if (!empty($classpath)) { + if (!empty($classpath)) + { @@ -1012 +852,2 @@ - if ($classname && class_exists($classname)) { + if ($classname && class_exists($classname)) + { @@ -1016 +857 @@ - $formatedarrayoption['options_'.$key] = $tmpobject->name; + $object->array_options['options_'.$key] = $tmpobject->name; @@ -1022,5 +863 @@ - if (array_key_exists('options_'.$key, $formatedarrayoption)) { - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $formatedarrayoption['options_'.$key])); - } else { - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => '')); - } + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key])); @@ -1046 +883,238 @@ - 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) @@ -1048,447 +1122,178 @@ - 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 void - */ - public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - $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 = (isset($this->cols[$colKey]) ? $this->cols[$colKey] : null); - return (is_array($colDef) ? ((isset($colDef['xStartPos']) ? $colDef['xStartPos'] : 0) + $colDef['content']['padding'][3]) : 0); - } - - /** - * 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 = '', $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 int Return integer <0 if KO, >= if OK - */ - 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 0; - } - $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(isset($colDef['content']['padding'][3]) ? $colDef['content']['padding'][3] : 0, isset($colDef['content']['padding'][0]) ? $colDef['content']['padding'][0] : 0, isset($colDef['content']['padding'][1]) ? $colDef['content']['padding'][1] : 0, isset($colDef['content']['padding'][2]) ? $colDef['content']['padding'][2] : 0); - $pdf->writeHTMLCell($colDef['width'], 2, isset($colDef['xStartPos']) ? $colDef['xStartPos'] : 0, $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - - return 0; - } - - - /** - * 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 void - */ - 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 - * @param Translate $outputlangs The output langs (if value is __(XXX)__ we use it to translate it). - * @return string - */ - public function getExtrafieldContent($object, $extrafieldKey, $outputlangs = null) - { - 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 extra fields if they haven't been loaded already. - 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 = ''; - if (isset($object->array_options[$extrafieldOptionsKey])) { - $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element, $outputlangs); - } - - // 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 string Html string - */ - public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) - { - global $hookmanager; - - if (empty($object->table_element)) { - return ""; - } - - // Load extrafields if not allready done - 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; - } - - // Load language if required - if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) { - $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); - } - - $field = new stdClass(); - $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); - $field->content = $this->getExtrafieldContent($object, $key, $outputlangs); - if (isset($extrafields->attributes[$object->table_element]['langfile'][$key])) { - $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$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; @@ -1497,311 +1302,253 @@ - // 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 boolean true if column on - */ - 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']) && isset($colDef['xStartPos'])) { - $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]); - } - if (isset($colDef['title']['align'])) { - $align = $colDef['title']['align']; - } else { - $align = ''; - } - $pdf->SetXY($colDef['xStartPos'], $tab_top); - $textWidth = $colDef['width']; - $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $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, '', $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 int Return integer <0 if KO, >=0 if OK - */ - public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) - { - if (!empty($hidedetails)) { - return 0; - } - - if (empty($object->table_element)) { - return 0; - } - - // Load extra fields if they haven't been loaded already. - 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]) && array_key_exists('label', $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' => (bool) $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); - } - } - - return 1; - } - - /** - * Define Array Column Field into $this->cols - * This method must be implemented by the module that generate the document with its own columns. - * - * @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 void - */ - public function defineColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - // Default field style for content - $this->defaultContentsFieldsStyle = array( - 'align' => 'R', // R,C,L - 'padding' => array(1, 0.5, 1, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ); - - // Default field style for content - $this->defaultTitlesFieldsStyle = array( - 'align' => 'C', // R,C,L - 'padding' => array(0.5, 0, 0.5, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ); - - // Example - /* - $rank = 0; // do not use negative rank - $this->cols['desc'] = array( - 'rank' => $rank, - 'width' => false, // only for desc - 'status' => true, - 'title' => array( - 'textkey' => 'Designation', // use lang key is usefull in somme case with module - 'align' => 'L', - // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label - // 'label' => ' ', // the final label - 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'content' => array( - 'align' => 'L', - 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - ); - */ - } + // 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_19.0.3_commoninvoice.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commoninvoice.class.php @@ -5 +4,0 @@ - * Copyright (C) 2023 Nick Fragoulis @@ -28 +26,0 @@ -require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; @@ -35,148 +33,30 @@ - use CommonIncoterm; - - /** - * @var string Label used as ref for template invoices - */ - public $title; - - /** - * @var int Type of invoice (See TYPE_XXX constants) - */ - public $type = self::TYPE_STANDARD; - - /** - * @var int Sub type of invoice (A subtype code coming from llx_invoice_subtype table. May be used by some countries like Greece) - */ - public $subtype; - - /** - * @var int Thirdparty ID - * @deprecated - * @see $socid - */ - public $fk_soc; - /** - * @var int Thirdparty ID - */ - public $socid; - - public $paye; - - /** - * Invoice date (date) - * - * @var integer - */ - public $date; - - public $date_lim_reglement; - - public $cond_reglement_id; // Id in llx_c_paiement - public $cond_reglement_code; // Code in llx_c_paiement - public $cond_reglement_label; - public $cond_reglement_doc; // Code in llx_c_paiement - - public $mode_reglement_id; - public $mode_reglement_code; // Code in llx_c_paiement - - /** - * @var string - */ - public $mode_reglement; - - /** - * @var double - */ - public $revenuestamp; - - public $totalpaid; // duplicate with sumpayed - public $totaldeposits; // duplicate with sumdeposit - public $totalcreditnotes; // duplicate with sumcreditnote - - public $sumpayed; - public $sumpayed_multicurrency; - public $sumdeposit; - public $sumdeposit_multicurrency; - public $sumcreditnote; - public $sumcreditnote_multicurrency; - public $remaintopay; - - /** - * @var int - */ - public $stripechargedone; - - /** - * @var int - */ - public $stripechargeerror; - - /** - * Payment description - * @var string - */ - public $description; - - /** - * @var string - * @deprecated - * @see $ref_customer - */ - public $ref_client; - - /** - * @var int Situation cycle reference number - */ - public $situation_cycle_ref; - - /** - * ! Closing after partial payment: discount_vat, badsupplier, abandon - * ! Closing when no payment: replaced, abandoned - * @var string Close code - */ - public $close_code; - - /** - * ! Comment if paid without full payment - * @var string Close note - */ - public $close_note; - - - /** - * ! Populate by Payment module like stripe - * @var string message return by Online Payment module - */ - public $postactionmessages; - - - /** - * 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; @@ -213 +92,0 @@ - @@ -219 +98 @@ - * @return float Remain of amount to pay + * @return double Remain of amount to pay @@ -223,10 +102,10 @@ - $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; @@ -239,3 +118,2 @@ - * @param int $multicurrency Return multicurrency_amount instead of amount. -1=Return both. - * @return float|int|array Amount of payment already done, <0 and set ->error if KO - * @see getSumDepositsUsed(), getSumCreditNotesUsed() + * @param int $multicurrency Return multicurrency_amount instead of amount + * @return int Amount of payment already done, <0 if KO @@ -247 +125,2 @@ - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + { @@ -252,3 +131,3 @@ - $sql = "SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount"; - $sql .= " FROM ".$this->db->prefix().$table; - $sql .= " WHERE ".$field." = ".((int) $this->id); + $sql = 'SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$table; + $sql .= ' WHERE '.$field.' = '.$this->id; @@ -257 +135,0 @@ - @@ -259 +137,2 @@ - if ($resql) { + if ($resql) + { @@ -261 +139,0 @@ - @@ -263,17 +141,5 @@ - - if ($obj) { - if ($multicurrency < 0) { - $this->sumpayed = $obj->amount; - $this->sumpayed_multicurrency = $obj->multicurrency_amount; - return array('alreadypaid'=>(float) $obj->amount, 'alreadypaid_multicurrency'=>(float) $obj->multicurrency_amount); - } elseif ($multicurrency) { - $this->sumpayed_multicurrency = $obj->multicurrency_amount; - return (float) $obj->multicurrency_amount; - } else { - $this->sumpayed = $obj->amount; - return (float) $obj->amount; - } - } else { - return 0; - } - } else { + if ($multicurrency) return $obj->multicurrency_amount; + else return $obj->amount; + } + else + { @@ -286,7 +152,5 @@ - * 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 for sale invoices (not recommended), - * of FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS is on for purchase invoices (not recommended). - * - * @param int $multicurrency Return multicurrency_amount instead of amount - * @return float Return integer <0 and set ->error if KO, Sum of deposits amount otherwise - * @see getSommePaiement(), getSumCreditNotesUsed() + * 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). + * + * @param int $multicurrency Return multicurrency_amount instead of amount + * @return int <0 if KO, Sum of deposits amount otherwise @@ -296,30 +160,26 @@ - /*if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { - // FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS was never supported for purchase invoice, so we can return 0 with no need of SQL for this case. - 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) { - if ($multicurrency) { - $this->sumdeposit_multicurrency = $result; - } else { - $this->sumdeposit = $result; - } - - 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 Return integer <0 and set ->error if KO, Sum of credit notes and deposits amount otherwise - * @see getSommePaiement(), getSumDepositsUsed() + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + { + // 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 int <0 if KO, Sum of credit notes and deposits amount otherwise @@ -329,16 +189,13 @@ - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - - $discountstatic = new DiscountAbsolute($this->db); - $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency); - if ($result >= 0) { - if ($multicurrency) { - $this->sumcreditnote_multicurrency = $result; - } else { - $this->sumcreditnote = $result; - } - - 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; + } @@ -351 +208 @@ - * @return float Return integer <0 if KO, Sum of credit notes and deposits amount otherwise + * @return int <0 if KO, Sum of credit notes and deposits amount otherwise @@ -355,10 +212,13 @@ - 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; + } @@ -376,4 +236,4 @@ - $sql = "SELECT rowid"; - $sql .= " FROM ".$this->db->prefix().$this->table_element; - $sql .= " WHERE fk_facture_source = ".((int) $this->id); - $sql .= " AND type = 2"; + $sql = 'SELECT rowid'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' WHERE fk_facture_source = '.$this->id; + $sql .= ' AND type = 2'; @@ -381 +241,2 @@ - if ($resql) { + if ($resql) + { @@ -384 +245,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -389 +251,3 @@ - } else { + } + else + { @@ -399 +263 @@ - * @return int Return integer <0 si KO, 0 if no invoice replaces it, id of invoice otherwise + * @return int <0 si KO, 0 if no invoice replaces it, id of invoice otherwise @@ -403,7 +267,5 @@ - $sql = "SELECT rowid"; - $sql .= " FROM ".$this->db->prefix().$this->table_element; - $sql .= " WHERE fk_facture_source = ".((int) $this->id); - $sql .= " AND type < 2"; - if ($option == 'validated') { - $sql .= ' AND fk_statut = 1'; - } + $sql = 'SELECT rowid'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' WHERE fk_facture_source = '.$this->id; + $sql .= ' AND type < 2'; + if ($option == 'validated') $sql .= ' AND fk_statut = 1'; @@ -415 +277 @@ - $sql .= " ORDER BY fk_statut DESC"; + $sql .= ' ORDER BY fk_statut DESC'; @@ -418 +280,2 @@ - if ($resql) { + if ($resql) + { @@ -420 +283,2 @@ - if ($obj) { + if ($obj) + { @@ -423 +287,3 @@ - } else { + } + else + { @@ -427 +293,3 @@ - } else { + } + else + { @@ -436 +303,0 @@ - * @param int $multicurrency Return multicurrency_amount instead of amount @@ -439 +306 @@ - public function getListOfPayments($filtertype = '', $multicurrency = 0) + public function getListOfPayments($filtertype = '') @@ -447,2 +313,0 @@ - $field3 = ', p.ref_ext'; - $field4 = ', p.fk_bank'; // Bank line id @@ -450 +315,2 @@ - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + { @@ -455 +320,0 @@ - $field3 = ''; @@ -459,4 +324,5 @@ - $sql = "SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code".$field3 . $field4; - $sql .= " FROM ".$this->db->prefix().$table." as pf, ".$this->db->prefix().$table2." as p, ".$this->db->prefix()."c_paiement as t"; - $sql .= " WHERE pf.".$field." = ".((int) $this->id); - $sql .= " AND pf.".$field2." = p.rowid"; + $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'; + $sql .= ' AND pf.'.$field2.' = p.rowid'; @@ -465,3 +331 @@ - if ($filtertype) { - $sql .= " AND t.code='PRE'"; - } + if ($filtertype) $sql .= " AND t.code='PRE'"; @@ -471 +335,2 @@ - if ($resql) { + if ($resql) + { @@ -474 +339,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -476,8 +342 @@ - $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; - } - if (!empty($field4)) { - $tmp['fk_bank_line'] = $obj->fk_bank; - } - $retarray[] = $tmp; + $retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); @@ -490,4 +349,5 @@ - if ($this->element == 'facture' || $this->element == 'invoice') { - $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 '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture as f'; - $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.((int) $this->id); + if ($this->element == 'facture' || $this->element == 'invoice') + { + $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 as f'; + $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$this->id; @@ -495,5 +355,7 @@ - } 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 '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture_fourn as f'; - $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.((int) $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_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS is set) + } + 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'; + $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$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) @@ -504 +366,2 @@ - if ($resql) { + if ($resql) + { @@ -507 +370,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -511 +375,2 @@ - } else { + } + else { @@ -516 +381,3 @@ - } else { + } + else + { @@ -525 +392,3 @@ - } else { + } + else + { @@ -533 +402 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -545,5 +414,5 @@ - * @return int Return integer <=0 if no, >0 if yes - */ - public function is_erasable() - { - // phpcs:enable + * @return int <=0 if no, >0 if yes + */ + public function is_erasable() + { + // phpcs:enable @@ -555 +424,2 @@ - if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') { // If draft invoice and ref not yet defined + if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined + { @@ -559,3 +429 @@ - if (getDolGlobalString('INVOICE_CAN_NEVER_BE_REMOVED')) { - return 0; - } + if (!empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0; @@ -564 +432,2 @@ - if ($tmppart !== 'PROV') { + if ($tmppart !== 'PROV') + { @@ -566,3 +435 @@ - if ($ventilExportCompta != 0) { - return -1; - } + if ($ventilExportCompta != 0) return -1; @@ -571,4 +438,3 @@ - if ($this->element != 'invoice_supplier') { - if (empty($this->thirdparty)) { - $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag). - } + if ($this->element != 'invoice_supplier') + { + if (empty($this->thirdparty)) $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag). @@ -579,3 +445 @@ - if (!getDolGlobalString('INVOICE_CAN_ALWAYS_BE_REMOVED') && $maxref != '' && $maxref != $this->ref) { - return -2; - } + if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) return -2; @@ -586 +450,2 @@ - if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) { + if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) + { @@ -588,3 +453 @@ - if (!$last) { - return -3; - } + if (!$last) return -3; @@ -596,3 +459 @@ - if (!getDolGlobalString('INVOICE_CAN_ALWAYS_BE_REMOVED') && $this->getSommePaiement() > 0) { - return -4; - } + if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) return -4; @@ -606 +467 @@ - * @return int Return integer <0 if KO, 0=no, 1=yes + * @return int <0 if KO, 0=no, 1=yes @@ -613,5 +474,3 @@ - if ($this->element == 'invoice_supplier') { - $type = 'supplier_invoice'; - } - - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".$this->db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id); + 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='".$type."' AND ab.fk_doc = ".$this->id; @@ -619 +478,2 @@ - if ($resql) { + if ($resql) + { @@ -621 +481,2 @@ - if ($obj) { + if ($obj) + { @@ -624 +485,3 @@ - } else { + } + else + { @@ -629 +492,2 @@ - if ($alreadydispatched) { + if ($alreadydispatched) + { @@ -635,12 +498,0 @@ - /** - * Return next reference of invoice not already used (or last reference) - * - * @param Societe $soc Thirdparty object - * @param string $mode 'next' for next value or 'last' for last value - * @return string free ref or last ref - */ - public function getNextNumRef($soc, $mode = 'next') - { - // TODO Must be implemented into main class - return ''; - } @@ -651,4 +503,3 @@ - * @param int $withbadge 1=Add span for badge css, 2=Add span and show short label - * @return string Label of type of invoice - */ - public function getLibType($withbadge = 0) + * @return string Label of type of invoice + */ + public function getLibType() @@ -657,105 +508,7 @@ - - $labellong = "Unknown"; - if ($this->type == CommonInvoice::TYPE_STANDARD) { - $labellong = "InvoiceStandard"; - $labelshort = "InvoiceStandardShort"; - } elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) { - $labellong = "InvoiceReplacement"; - $labelshort = "InvoiceReplacementShort"; - } elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) { - $labellong = "InvoiceAvoir"; - $labelshort = "CreditNote"; - } elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) { - $labellong = "InvoiceDeposit"; - $labelshort = "Deposit"; - } elseif ($this->type == CommonInvoice::TYPE_PROFORMA) { - $labellong = "InvoiceProForma"; // Not used. - $labelshort = "ProForma"; - } elseif ($this->type == CommonInvoice::TYPE_SITUATION) { - $labellong = "InvoiceSituation"; - $labelshort = "Situation"; - } - - $out = ''; - if ($withbadge) { - $out .= ''; - } - $out .= $langs->trans($withbadge == 2 ? $labelshort : $labellong); - if ($withbadge) { - $out .= ''; - } - return $out; - } - - /** - * Return label of invoice subtype - * - * @param string $table table of invoice - * @return string|int Label of invoice subtype or -1 if error - */ - public function getSubtypeLabel($table = '') - { - $subtypeLabel = ''; - if ($table === 'facture' || $table === 'facture_fourn') { - $sql = "SELECT s.label FROM " . $this->db->prefix() . $table . " AS f"; - $sql .= " INNER JOIN " . $this->db->prefix() . "c_invoice_subtype AS s ON f.subtype = s.rowid"; - $sql .= " WHERE f.ref = '".$this->db->escape($this->ref)."'"; - } elseif ($table === 'facture_rec' || $table === 'facture_fourn_rec') { - $sql = "SELECT s.label FROM " . $this->db->prefix() . $table . " AS f"; - $sql .= " INNER JOIN " . $this->db->prefix() . "c_invoice_subtype AS s ON f.subtype = s.rowid"; - $sql .= " WHERE f.titre = '".$this->db->escape($this->title)."'"; - } else { - return -1; - } - - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $subtypeLabel = $obj->label; - } - } else { - dol_print_error($this->db); - return -1; - } - - return $subtypeLabel; - } - - /** - * Retrieve a list of invoice subtype labels or codes. - * - * @param int $mode 0=Return id+label, 1=Return code+id - * @return array Array of subtypes - */ - public function getArrayOfInvoiceSubtypes($mode = 0) - { - global $mysoc; - - $effs = array(); - - $sql = "SELECT rowid, code, label as label"; - $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype'; - $sql .= " WHERE active = 1 AND fk_country = ".((int) $mysoc->country_id)." AND entity IN(".getEntity('c_invoice_subtype').")"; - $sql .= " ORDER by rowid, code"; - dol_syslog(get_class($this) . '::getArrayOfInvoiceSubtypes', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - $i = 0; - - while ($i < $num) { - $objp = $this->db->fetch_object($resql); - if (!$mode) { - $key = $objp->rowid; - $effs[$key] = $objp->label; - } else { - $key = $objp->code; - $effs[$key] = $objp->rowid; - } - - $i++; - } - $this->db->free($resql); - } - - return $effs; + 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"); @@ -776 +529 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -784 +537 @@ - * @param int $type Type invoice. If -1, we use $this->type + * @param int $type Type invoice @@ -787,4 +540,4 @@ - public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = -1) - { - // phpcs:enable - global $langs, $hookmanager; + public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0) + { + // phpcs:enable + global $langs; @@ -792,4 +544,0 @@ - - if ($type == -1) { - $type = $this->type; - } @@ -800,55 +549,42 @@ - if ($status == 0) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft'); - } elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) { - if ($status == 3) { - $labelStatus = $langs->transnoentitiesnoconv('BillStatusCanceled'); - $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusCanceled'); - } else { - $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'); - } - } - - $parameters = array( - 'status' => $status, - 'mode' => $mode, - 'paye' => $paye, - 'alreadypaid' => $alreadypaid, - 'type' => $type - ); - - $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook - - if ($reshook > 0) { - return $hookmanager->resPrint; - } - - + 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'); + } + } @@ -859 +595 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -865,14 +601,7 @@ - * @return integer Date limit of payment if OK, <0 if KO - */ - 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; - } - if (!$cond_reglement) { - return $this->date; - } + * @return integer Date limite de reglement si ok, <0 si ko + */ + 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; @@ -881,8 +610,7 @@ - $cdr_type = 0; - $cdr_decalage = 0; - - $sqltemp = "SELECT c.type_cdr, c.nbjour, c.decalage"; - $sqltemp .= " FROM ".$this->db->prefix()."c_payment_term as c"; - if (is_numeric($cond_reglement)) { - $sqltemp .= " WHERE c.rowid=".((int) $cond_reglement); - } else { + $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'; + if (is_numeric($cond_reglement)) $sqltemp .= " WHERE c.rowid=".$cond_reglement; + else { @@ -890 +618 @@ - $sqltemp .= " AND c.code = '".$this->db->escape($cond_reglement)."'"; + $sqltemp .= " AND c.code='".$this->db->escape($cond_reglement)."'"; @@ -895,2 +623,4 @@ - if ($resqltemp) { - if ($this->db->num_rows($resqltemp)) { + if ($resqltemp) + { + if ($this->db->num_rows($resqltemp)) + { @@ -902 +632,3 @@ - } else { + } + else + { @@ -911 +643,2 @@ - if ($cdr_type == 0) { + if ($cdr_type == 0) + { @@ -915,2 +648,4 @@ - } elseif ($cdr_type == 1) { - // 1 : application of the "end of the month" rule + } + // 1 : application of the "end of the month" rule + elseif ($cdr_type == 1) + { @@ -921 +656,2 @@ - if ($mois == 12) { + if ($mois == 12) + { @@ -924 +660,3 @@ - } else { + } + else + { @@ -932,3 +670,5 @@ - } elseif ($cdr_type == 2 && !empty($cdr_decalage)) { - // 2 : application of the rule, the N of the current or next month - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + } + // 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'; @@ -943,8 +683,4 @@ - 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; - } + 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; @@ -960,8 +696,7 @@ - * @param User $fuser User asking the direct debit transfer - * @param float $amount Amount we request direct debit for - * @param string $type 'direct-debit' or 'bank-transfer' - * @param string $sourcetype Source ('facture' or 'supplier_invoice') - * @param int $checkduplicateamongall 0=Default (check among open requests only to find if request already exists). 1=Check also among requests completely processed and cancel if at least 1 request exists whatever is its status. - * @return int Return integer <0 if KO, 0 if a request already exists, >0 if OK - */ - public function demande_prelevement($fuser, $amount = 0, $type = 'direct-debit', $sourcetype = 'facture', $checkduplicateamongall = 0) + * @param User $fuser User asking the direct debit transfer + * @param float $amount Amount we request direct debit for + * @param string $type 'direct-debit' or 'bank-transfer' + * @param string $sourcetype Source ('facture' or 'supplier_invoice') + * @return int <0 if KO, >0 if OK + */ + public function demande_prelevement($fuser, $amount = 0, $type = 'direct-debit', $sourcetype = 'facture') @@ -976 +711,2 @@ - if ($this->status > self::STATUS_DRAFT && $this->paye == 0) { + if ($this->statut > self::STATUS_DRAFT && $this->paye == 0) + { @@ -981,2 +717,2 @@ - $sql = "SELECT count(rowid) as nb"; - $sql .= " FROM ".$this->db->prefix()."prelevement_demande"; + $sql = 'SELECT count(*)'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande'; @@ -984 +720 @@ - $sql .= " WHERE fk_facture_fourn = ".((int) $this->id); + $sql .= ' WHERE fk_facture_fourn = '.$this->id; @@ -986,6 +722,4 @@ - $sql .= " WHERE fk_facture = ".((int) $this->id); - } - $sql .= " AND type = 'ban'"; // To exclude record done for some online payments - if (empty($checkduplicateamongall)) { - $sql .= " AND traite = 0"; - } + $sql .= ' WHERE fk_facture = '.$this->id; + } + $sql .= ' AND ext_payment_id IS NULL'; // To exclude record done for some online payments + $sql .= ' AND traite = 0'; @@ -994 +727,0 @@ - @@ -996,3 +729,5 @@ - if ($resql) { - $obj = $this->db->fetch_object($resql); - if ($obj && $obj->nb == 0) { // If no request found yet + if ($resql) + { + $row = $this->db->fetch_row($resql); + if ($row[0] == 0) + { @@ -1001 +736 @@ - $totalpaid = $this->getSommePaiement(); + $totalpaye = $this->getSommePaiement(); @@ -1004 +739 @@ - //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits; + //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits; @@ -1008 +743 @@ - //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT); + //$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT); @@ -1010,6 +745,5 @@ - if (empty($amount)) { - $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT'); - } - - if (is_numeric($amount) && $amount != 0) { - $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande('; + if (empty($amount)) $amount = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + + if (is_numeric($amount) && $amount != 0) + { + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'prelevement_facture_demande('; @@ -1021,12 +755,11 @@ - $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, type, entity)'; - $sql .= " VALUES (".((int) $this->id); - $sql .= ", ".((float) price2num($amount)); - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", ".((int) $fuser->id); - $sql .= ", '".$this->db->escape($bac->code_banque)."'"; - $sql .= ", '".$this->db->escape($bac->code_guichet)."'"; - $sql .= ", '".$this->db->escape($bac->number)."'"; - $sql .= ", '".$this->db->escape($bac->cle_rib)."'"; - $sql .= ", '".$this->db->escape($sourcetype)."'"; - $sql .= ", 'ban'"; - $sql .= ", ".((int) $conf->entity); + $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, entity)'; + $sql .= ' VALUES ('.$this->id; + $sql .= ",'".price2num($amount)."'"; + $sql .= ",'".$this->db->idate($now)."'"; + $sql .= ",".$fuser->id; + $sql .= ",'".$this->db->escape($bac->code_banque)."'"; + $sql .= ",'".$this->db->escape($bac->code_guichet)."'"; + $sql .= ",'".$this->db->escape($bac->number)."'"; + $sql .= ",'".$this->db->escape($bac->cle_rib)."'"; + $sql .= ",'".$this->db->escape($sourcetype)."'"; + $sql .= ",".$conf->entity; @@ -1037 +770,2 @@ - if (!$resql) { + if (!$resql) + { @@ -1042 +776,3 @@ - } else { + } + else + { @@ -1048 +784,2 @@ - if (!$error) { + if (!$error) + { @@ -1050,2 +787,3 @@ - $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) + { @@ -1056,3 +794 @@ - if ($error) { - return -1; - } + if ($error) return -1; @@ -1060 +796,3 @@ - } else { + } + else + { @@ -1062 +800 @@ - dol_syslog(get_class($this).'::demandeprelevement Can t create a request to generate a direct debit, a request already exists.'); + dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours'); @@ -1065 +803,3 @@ - } else { + } + else + { @@ -1067 +807 @@ - dol_syslog(get_class($this).'::demandeprelevement Error -2'); + dol_syslog(get_class($this).'::demandeprelevement Erreur -2'); @@ -1070 +810,3 @@ - } else { + } + else + { @@ -1072,546 +814 @@ - dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->status, $this->paye, $this->mode_reglement_id"); - return -3; - } - } - - - /** - * Create a payment with Stripe card - * Must take amount using Stripe and record an event into llx_actioncomm - * Record bank payment - * Send email to customer ? - * - * @param User $fuser User asking the direct debit transfer - * @param int $id Invoice ID with remain to pay - * @param string $sourcetype Source ('facture' or 'supplier_invoice') - * @return int Return integer <0 if KO, >0 if OK - */ - public function makeStripeCardRequest($fuser, $id, $sourcetype = 'facture') - { - // TODO See in sellyoursaas - return 0; - } - - /** - * Create a direct debit order into prelevement_bons for a given prelevement_request, then - * Send the payment order to the service (for a direct debit order or a credit transfer order) and record an event in llx_actioncomm. - * - * @param User $fuser User asking the direct debit transfer - * @param int $did ID of unitary payment request to pay - * @param string $type 'direct-debit' or 'bank-transfer' - * @param string $sourcetype Source ('facture' or 'supplier_invoice') - * @param string $service 'StripeTest', 'StripeLive', ... - * @param string $forcestripe To force another stripe env: 'cus_account@pk_...:sk_...' - * @return int Return integer <0 if KO, >0 if OK - */ - public function makeStripeSepaRequest($fuser, $did, $type = 'direct-debit', $sourcetype = 'facture', $service = '', $forcestripe = '') - { - global $conf, $user, $langs; - - if ($type != 'bank-transfer' && $type != 'credit-transfer' && !getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT')) { - return 0; - } - if ($type != 'direct-debit' && !getDolGlobalString('STRIPE_SEPA_CREDIT_TRANSFER')) { - return 0; - } - // Set a default value for service if not provided - if (empty($service)) { - $service = 'StripeTest'; - if (getDolGlobalString('STRIPE_LIVE') && !GETPOST('forcesandbox', 'alpha')) { - $service = 'StripeLive'; - } - } - - $error = 0; - - dol_syslog(get_class($this)."::makeStripeSepaRequest start did=".$did." type=".$type." service=".$service." sourcetype=".$sourcetype." forcestripe=".$forcestripe, LOG_DEBUG); - - if ($this->status > self::STATUS_DRAFT && $this->paye == 0) { - // Get the default payment mode for BAN payment of the third party - require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; - $bac = new CompanyBankAccount($this->db); // table societe_rib - $result = $bac->fetch(0, $this->socid, 1, 'ban'); - if ($result <= 0 || empty($bac->id)) { - $this->error = $langs->trans("ThirdpartyHasNoDefaultBanAccount"); - $this->errors[] = $this->error; - dol_syslog(get_class($this)."::makeStripeSepaRequest ".$this->error); - return -1; - } - - // Load the pending payment request to process (with rowid=$did) - $sql = "SELECT rowid, date_demande, amount, fk_facture, fk_facture_fourn, fk_salary, fk_prelevement_bons"; - $sql .= " FROM ".$this->db->prefix()."prelevement_demande"; - $sql .= " WHERE rowid = ".((int) $did); - if ($type != 'bank-transfer' && $type != 'credit-transfer') { - $sql .= " AND fk_facture = ".((int) $this->id); // Add a protection to not pay another invoice than current one - } - if ($type != 'direct-debit') { - if ($sourcetype == 'salary') { - $sql .= " AND fk_salary = ".((int) $this->id); // Add a protection to not pay another salary than current one - } else { - $sql .= " AND fk_facture_fourn = ".((int) $this->id); // Add a protection to not pay another invoice than current one - } - } - $sql .= " AND traite = 0"; // To not process payment request that were already converted into a direct debit or credit transfer order (Note: fk_prelevement_bons is also empty when traite = 0) - - dol_syslog(get_class($this)."::makeStripeSepaRequest load requests to process", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_object($resql); - if (!$obj) { - dol_print_error($this->db, 'CantFindRequestWithId'); - return -2; - } - - // amount to pay - $amount = $obj->amount; - - if (is_numeric($amount) && $amount != 0) { - require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php'; - $companypaymentmode = new CompanyPaymentMode($this->db); // table societe_rib - $companypaymentmode->fetch($bac->id); - - $this->stripechargedone = 0; - $this->stripechargeerror = 0; - - $now = dol_now(); - - $currency = $conf->currency; - - $errorforinvoice = 0; // We reset the $errorforinvoice at each invoice loop - - $this->fetch_thirdparty(); - - dol_syslog("makeStripeSepaRequest Process payment request amount=".$amount." thirdparty_id=" . $this->thirdparty->id . ", thirdparty_name=" . $this->thirdparty->name . " ban id=" . $bac->id, LOG_DEBUG); - - //$alreadypayed = $this->getSommePaiement(); - //$amount_credit_notes_included = $this->getSumCreditNotesUsed(); - //$amounttopay = $this->total_ttc - $alreadypayed - $amount_credit_notes_included; - $amounttopay = $amount; - - // Correct the amount according to unit of currency - // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support - $arrayzerounitcurrency = ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']; - $amountstripe = $amounttopay; - if (!in_array($currency, $arrayzerounitcurrency)) { - $amountstripe = $amountstripe * 100; - } - - $fk_bank_account = getDolGlobalInt('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS'); // Bank account used for SEPA direct debit or credit transfer. Must be the Stripe account in Dolibarr. - if (!($fk_bank_account > 0)) { - $error++; - $errorforinvoice++; - dol_syslog("makeStripeSepaRequest Error no bank account defined for Stripe payments", LOG_ERR); - $this->errors[] = "Error bank account for Stripe payments not defined into Stripe module"; - } - - $this->db->begin(); - - // Create a prelevement_bon - require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; - $bon = new BonPrelevement($this->db); - if (!$error) { - if (empty($obj->fk_prelevement_bons)) { - // This creates a record into llx_prelevement_bons and updates link with llx_prelevement_demande - $nbinvoices = $bon->create(0, 0, 'real', 'ALL', '', 0, $type, $did, $fk_bank_account); - if ($nbinvoices <= 0) { - $error++; - $errorforinvoice++; - dol_syslog("makeStripeSepaRequest Error on BonPrelevement creation", LOG_ERR); - $this->errors[] = "Error on BonPrelevement creation"; - } - /* - if (!$error) { - // Update the direct debit payment request of the processed request to save the id of the prelevement_bon - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_demande SET"; - $sql .= " fk_prelevement_bons = ".((int) $bon->id); - $sql .= " WHERE rowid = ".((int) $did); - - $result = $this->db->query($sql); - if ($result < 0) { - $error++; - $this->errors[] = "Error on updateing fk_prelevement_bons to ".$bon->id; - } - } - */ - } else { - $error++; - $errorforinvoice++; - dol_syslog("makeStripeSepaRequest Error Line already part of a bank payment order", LOG_ERR); - $this->errors[] = "The line is already included into a bank payment order. Delete the bank payment order first."; - } - } - - if (!$error) { - if ($amountstripe > 0) { - try { - global $savstripearrayofkeysbyenv; - global $stripearrayofkeysbyenv; - $servicestatus = 0; - if ($service == 'StripeLive') { - $servicestatus = 1; - } - - //var_dump($companypaymentmode); - dol_syslog("makeStripeSepaRequest We will try to pay with companypaymentmodeid=" . $companypaymentmode->id . " stripe_card_ref=" . $companypaymentmode->stripe_card_ref . " mode=" . $companypaymentmode->status, LOG_DEBUG); - - $thirdparty = new Societe($this->db); - $resultthirdparty = $thirdparty->fetch($this->socid); - - include_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php'; // This include the include of htdocs/stripe/config.php - // So it inits or erases the $stripearrayofkeysbyenv - $stripe = new Stripe($this->db); - - if (empty($savstripearrayofkeysbyenv)) { - $savstripearrayofkeysbyenv = $stripearrayofkeysbyenv; - } - dol_syslog("makeStripeSepaRequest Current Stripe environment is " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key']); - dol_syslog("makeStripeSepaRequest Current Saved Stripe environment is ".$savstripearrayofkeysbyenv[$servicestatus]['publishable_key']); - - $foundalternativestripeaccount = ''; - - // Force stripe to another value (by default this value is empty) - if (! empty($forcestripe)) { - dol_syslog("makeStripeSepaRequest A dedicated stripe account was forced, so we switch to it."); - - $tmparray = explode('@', $forcestripe); - if (! empty($tmparray[1])) { - $tmparray2 = explode(':', $tmparray[1]); - if (! empty($tmparray2[1])) { - $stripearrayofkeysbyenv[$servicestatus]["publishable_key"] = $tmparray2[0]; - $stripearrayofkeysbyenv[$servicestatus]["secret_key"] = $tmparray2[1]; - - $stripearrayofkeys = $stripearrayofkeysbyenv[$servicestatus]; - \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']); - - $foundalternativestripeaccount = $tmparray[0]; // Store the customer id - - dol_syslog("makeStripeSepaRequest We use now customer=".$foundalternativestripeaccount." publishable_key=".$stripearrayofkeys['publishable_key'], LOG_DEBUG); - } - } - - if (! $foundalternativestripeaccount) { - $stripearrayofkeysbyenv = $savstripearrayofkeysbyenv; - - $stripearrayofkeys = $savstripearrayofkeysbyenv[$servicestatus]; - \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']); - dol_syslog("makeStripeSepaRequest We found a bad value for Stripe Account for thirdparty id=".$thirdparty->id.", so we ignore it and keep using the global one, so ".$stripearrayofkeys['publishable_key'], LOG_WARNING); - } - } else { - $stripearrayofkeysbyenv = $savstripearrayofkeysbyenv; - - $stripearrayofkeys = $savstripearrayofkeysbyenv[$servicestatus]; - \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']); - dol_syslog("makeStripeSepaRequest No dedicated Stripe Account requested, so we use global one, so ".$stripearrayofkeys['publishable_key'], LOG_DEBUG); - } - - $stripeacc = $stripe->getStripeAccount($service, $this->socid); // Get Stripe OAuth connect account if it exists (no network access here) - - if ($foundalternativestripeaccount) { - if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage - $customer = \Stripe\Customer::retrieve(array('id'=>"$foundalternativestripeaccount", 'expand[]'=>'sources')); - } else { - $customer = \Stripe\Customer::retrieve(array('id'=>"$foundalternativestripeaccount", 'expand[]'=>'sources'), array("stripe_account" => $stripeacc)); - } - } else { - $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0); - if (empty($customer) && ! empty($stripe->error)) { - $this->errors[] = $stripe->error; - } - /*if (!empty($customer) && empty($customer->sources)) { - $customer = null; - $this->errors[] = '\Stripe\Customer::retrieve did not returned the sources'; - }*/ - } - - // $nbhoursbetweentries = (empty($conf->global->SELLYOURSAAS_NBHOURSBETWEENTRIES) ? 49 : $conf->global->SELLYOURSAAS_NBHOURSBETWEENTRIES); // Must have more that 48 hours + 1 between each try (so 1 try every 3 daily batch) - // $nbdaysbeforeendoftries = (empty($conf->global->SELLYOURSAAS_NBDAYSBEFOREENDOFTRIES) ? 35 : $conf->global->SELLYOURSAAS_NBDAYSBEFOREENDOFTRIES); - $postactionmessages = []; - - if ($resultthirdparty > 0 && !empty($customer)) { - if (!$error) { // Payment was not canceled - $stripecard = null; - if ($companypaymentmode->type == 'ban') { - // Check into societe_rib if a payment mode for Stripe and ban payment exists - // To make a Stripe SEPA payment request, we must have the payment mode source already saved into societe_rib and retreived with ->sepaStripe - // The payment mode source is created when we create the bank account on Stripe with paymentmodes.php?action=create - $stripecard = $stripe->sepaStripe($customer, $companypaymentmode, $stripeacc, $servicestatus, 0); - } else { - $error++; - $this->error = 'The payment mode type is not "ban"'; - } - - if ($stripecard) { // Can be src_... (for sepa) or pm_... (new card mode). Note that card_... (old card mode) should not happen here. - $FULLTAG = 'DID='.$did.'-INV=' . $this->id . '-CUS=' . $thirdparty->id; - $description = 'Stripe payment from makeStripeSepaRequest: ' . $FULLTAG . ' did='.$did.' ref=' . $this->ref; - - $stripefailurecode = ''; - $stripefailuremessage = ''; - $stripefailuredeclinecode = ''; - - // Using new SCA method - dol_syslog("* Create payment on SEPA " . $stripecard->id . ", amounttopay=" . $amounttopay . ", amountstripe=" . $amountstripe . ", FULLTAG=" . $FULLTAG, LOG_DEBUG); - - // Create payment intent and charge payment (confirmnow = true) - $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $this, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1, 1, $did); - - $charge = new stdClass(); - - if ($paymentintent->status === 'succeeded' || $paymentintent->status === 'processing') { - $charge->status = 'ok'; - $charge->id = $paymentintent->id; - $charge->customer = $customer->id; - } elseif ($paymentintent->status === 'requires_action') { - //paymentintent->status may be => 'requires_action' (no error in such a case) - dol_syslog(var_export($paymentintent, true), LOG_DEBUG); - - $charge->status = 'failed'; - $charge->customer = $customer->id; - $charge->failure_code = $stripe->code; - $charge->failure_message = $stripe->error; - $charge->failure_declinecode = $stripe->declinecode; - $stripefailurecode = $stripe->code; - $stripefailuremessage = 'Action required. Contact the support at ';// . $conf->global->SELLYOURSAAS_MAIN_EMAIL; - $stripefailuredeclinecode = $stripe->declinecode; - } else { - dol_syslog(var_export($paymentintent, true), LOG_DEBUG); - - $charge->status = 'failed'; - $charge->customer = $customer->id; - $charge->failure_code = $stripe->code; - $charge->failure_message = $stripe->error; - $charge->failure_declinecode = $stripe->declinecode; - $stripefailurecode = $stripe->code; - $stripefailuremessage = $stripe->error; - $stripefailuredeclinecode = $stripe->declinecode; - } - - //var_dump("stripefailurecode=".$stripefailurecode." stripefailuremessage=".$stripefailuremessage." stripefailuredeclinecode=".$stripefailuredeclinecode); - //exit; - - - // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) - if (empty($charge) || $charge->status == 'failed') { - dol_syslog('Failed to charge payment mode ' . $stripecard->id . ' stripefailurecode=' . $stripefailurecode . ' stripefailuremessage=' . $stripefailuremessage . ' stripefailuredeclinecode=' . $stripefailuredeclinecode, LOG_WARNING); - - // Save a stripe payment was in error - $this->stripechargeerror++; - - $error++; - $errorforinvoice++; - $errmsg = $langs->trans("FailedToChargeCard"); - if (!empty($charge)) { - if ($stripefailuredeclinecode == 'authentication_required') { - $errauthenticationmessage = $langs->trans("ErrSCAAuthentication"); - $errmsg = $errauthenticationmessage; - } elseif (in_array($stripefailuredeclinecode, ['insufficient_funds', 'generic_decline'])) { - $errmsg .= ': ' . $charge->failure_code; - $errmsg .= ($charge->failure_message ? ' - ' : '') . ' ' . $charge->failure_message; - if (empty($stripefailurecode)) { - $stripefailurecode = $charge->failure_code; - } - if (empty($stripefailuremessage)) { - $stripefailuremessage = $charge->failure_message; - } - } else { - $errmsg .= ': failure_code=' . $charge->failure_code; - $errmsg .= ($charge->failure_message ? ' - ' : '') . ' failure_message=' . $charge->failure_message; - if (empty($stripefailurecode)) { - $stripefailurecode = $charge->failure_code; - } - if (empty($stripefailuremessage)) { - $stripefailuremessage = $charge->failure_message; - } - } - } else { - $errmsg .= ': ' . $stripefailurecode . ' - ' . $stripefailuremessage; - $errmsg .= ($stripefailuredeclinecode ? ' - ' . $stripefailuredeclinecode : ''); - } - - $description = 'Stripe payment ERROR from makeStripeSepaRequest: ' . $FULLTAG; - $postactionmessages[] = $errmsg . ' (' . $stripearrayofkeys['publishable_key'] . ')'; - $this->errors[] = $errmsg; - } else { - dol_syslog('Successfuly request '.$type.' '.$stripecard->id); - - $postactionmessages[] = 'Success to request '.$type.' (' . $charge->id . ' with ' . $stripearrayofkeys['publishable_key'] . ')'; - - // Save a stripe payment was done in realy life so later we will be able to force a commit on recorded payments - // even if in batch mode (method doTakePaymentStripe), we will always make all action in one transaction with a forced commit. - $this->stripechargedone++; - - // Default description used for label of event. Will be overwrite by another value later. - $description = 'Stripe payment request OK (' . $charge->id . ') from makeStripeSepaRequest: ' . $FULLTAG; - } - - $object = $this; - - // Track an event - if (empty($charge) || $charge->status == 'failed') { - $actioncode = 'PAYMENT_STRIPE_KO'; - $extraparams = $stripefailurecode; - $extraparams .= (($extraparams && $stripefailuremessage) ? ' - ' : '') . $stripefailuremessage; - $extraparams .= (($extraparams && $stripefailuredeclinecode) ? ' - ' : '') . $stripefailuredeclinecode; - } else { - $actioncode = 'PAYMENT_STRIPE_OK'; - $extraparams = ''; - } - } else { - $error++; - $errorforinvoice++; - dol_syslog("No ban payment method found for this stripe customer " . $customer->id, LOG_WARNING); - $this->errors[] = 'Failed to get direct debit payment method for stripe customer = ' . $customer->id; - - $description = 'Failed to find or use the payment mode - no ban defined for the thirdparty account'; - $stripefailurecode = 'BADPAYMENTMODE'; - $stripefailuremessage = 'Failed to find or use the payment mode - no ban defined for the thirdparty account'; - $postactionmessages[] = $description . ' (' . $stripearrayofkeys['publishable_key'] . ')'; - - $object = $this; - - $actioncode = 'PAYMENT_STRIPE_KO'; - $extraparams = ''; - } - } else { - // If error because payment was canceled for a logical reason, we do nothing (no event added) - $description = ''; - $stripefailurecode = ''; - $stripefailuremessage = ''; - - $object = $this; - - $actioncode = ''; - $extraparams = ''; - } - } else { // Else of the if ($resultthirdparty > 0 && ! empty($customer)) { - if ($resultthirdparty <= 0) { - dol_syslog('SellYourSaasUtils Failed to load customer for thirdparty_id = ' . $thirdparty->id, LOG_WARNING); - $this->errors[] = 'Failed to load Stripe account for thirdparty_id = ' . $thirdparty->id; - } else { // $customer stripe not found - dol_syslog('SellYourSaasUtils Failed to get Stripe customer id for thirdparty_id = ' . $thirdparty->id . " in mode " . $servicestatus . " in Stripe env " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key'], LOG_WARNING); - $this->errors[] = 'Failed to get Stripe account id for thirdparty_id = ' . $thirdparty->id . " in mode " . $servicestatus . " in Stripe env " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key']; - } - $error++; - $errorforinvoice++; - - $description = 'Failed to find or use your payment mode (no payment mode for this customer id)'; - $stripefailurecode = 'BADPAYMENTMODE'; - $stripefailuremessage = 'Failed to find or use your payment mode (no payment mode for this customer id)'; - $postactionmessages = []; - - $object = $this; - - $actioncode = 'PAYMENT_STRIPE_KO'; - $extraparams = ''; - } - - if ($description) { - dol_syslog("* Record event for credit transfer or direct debit request result - " . $description); - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - - // Insert record of payment (success or error) - $actioncomm = new ActionComm($this->db); - - $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) - $actioncomm->code = 'AC_' . $actioncode; - $actioncomm->label = $description; - $actioncomm->note_private = join(",\n", $postactionmessages); - $actioncomm->fk_project = $this->fk_project; - $actioncomm->datep = $now; - $actioncomm->datef = $now; - $actioncomm->percentage = -1; // Not applicable - $actioncomm->socid = $thirdparty->id; - $actioncomm->contactid = 0; - $actioncomm->authorid = $user->id; // User saving action - $actioncomm->userownerid = $user->id; // Owner of action - // Fields when action is a real email (content is already into note) - /*$actioncomm->email_msgid = $object->email_msgid; - $actioncomm->email_from = $object->email_from; - $actioncomm->email_sender= $object->email_sender; - $actioncomm->email_to = $object->email_to; - $actioncomm->email_tocc = $object->email_tocc; - $actioncomm->email_tobcc = $object->email_tobcc; - $actioncomm->email_subject = $object->email_subject; - $actioncomm->errors_to = $object->errors_to;*/ - $actioncomm->fk_element = $this->id; - $actioncomm->elementtype = $this->element; - $actioncomm->extraparams = dol_trunc($extraparams, 250); - - $actioncomm->create($user); - } - - $this->description = $description; - $this->postactionmessages = $postactionmessages; - } catch (Exception $e) { - $error++; - $errorforinvoice++; - dol_syslog('Error ' . $e->getMessage(), LOG_ERR); - $this->errors[] = 'Error ' . $e->getMessage(); - } - } else { // If remain to pay is null - $error++; - $errorforinvoice++; - dol_syslog("Remain to pay is null for the invoice " . $this->id . " " . $this->ref . ". Why is the invoice not classified 'Paid' ?", LOG_WARNING); - $this->errors[] = "Remain to pay is null for the invoice " . $this->id . " " . $this->ref . ". Why is the invoice not classified 'Paid' ?"; - } - } - - // Set status of the order to "Transferred" with method 'api' - if (!$error && !$errorforinvoice) { - $result = $bon->set_infotrans($user, $now, 3); - if ($result < 0) { - $error++; - $errorforinvoice++; - dol_syslog("Error on BonPrelevement creation", LOG_ERR); - $this->errors[] = "Error on BonPrelevement creation"; - } - } - - if (!$error && !$errorforinvoice) { - // Update the direct debit payment request of the processed invoice to save the id of the prelevement_bon - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_demande SET"; - $sql .= " ext_payment_id = '".$this->db->escape($paymentintent->id)."',"; - $sql .= " ext_payment_site = '".$this->db->escape($service)."'"; - $sql .= " WHERE rowid = ".((int) $did); - - dol_syslog(get_class($this)."::makeStripeSepaRequest update to save stripe paymentintent ids", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this).'::makeStripeSepaRequest Erreur'); - $error++; - } - } - - if (!$error && !$errorforinvoice) { - $this->db->commit(); - } else { - $this->db->rollback(); - } - } else { - $this->error = 'WithdrawRequestErrorNilAmount'; - dol_syslog(get_class($this).'::makeStripeSepaRequest WithdrawRequestErrorNilAmount'); - $error++; - } - - /* - if (!$error) { - // Force payment mode of the 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) { - $result = $this->setPaymentMethods($payment_mode_id); - } - }*/ - - if ($error) { - return -1; - } - return 1; - } else { - $this->error = $this->db->error(); - dol_syslog(get_class($this).'::makeStripeSepaRequest Erreur -2'); - return -2; - } - } else { - $this->error = "Status of invoice does not allow this"; - dol_syslog(get_class($this)."::makeStripeSepaRequest ".$this->error." ".$this->status." ,".$this->paye.", ".$this->mode_reglement_id, LOG_WARNING); + dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id"); @@ -1628 +825 @@ - * @return int Return integer <0 if OK, >0 if KO + * @return int <0 if OK, >0 if KO @@ -1633,2 +830,2 @@ - $sql = 'DELETE FROM '.$this->db->prefix().'prelevement_demande'; - $sql .= ' WHERE rowid = '.((int) $did); + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande'; + $sql .= ' WHERE rowid = '.$did; @@ -1636 +833,2 @@ - if ($this->db->query($sql)) { + if ($this->db->query($sql)) + { @@ -1638 +836,3 @@ - } else { + } + else + { @@ -1643,175 +842,0 @@ - } - - - /** - * Build string for ZATCA QR Code (Arabi Saudia) - * - * @return string String for ZATCA QR Code - */ - public function buildZATCAQRString() - { - global $conf, $mysoc; - - $tmplang = new Translate('', $conf); - $tmplang->setDefaultLang('en_US'); - $tmplang->load("main"); - - $datestring = dol_print_date($this->date, 'dayhourrfc'); - //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2); - //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2); - $pricewithtaxstring = price2num($this->total_ttc, 2, 1); - $pricetaxstring = price2num($this->total_tva, 2, 1); - - /* - $name = implode(unpack("H*", $this->thirdparty->name)); - $vatnumber = implode(unpack("H*", $this->thirdparty->tva_intra)); - $date = implode(unpack("H*", $datestring)); - $pricewithtax = implode(unpack("H*", price2num($pricewithtaxstring, 2))); - $pricetax = implode(unpack("H*", $pricetaxstring)); - - //var_dump(strlen($this->thirdparty->name)); - //var_dump(str_pad(dechex('9'), 2, '0', STR_PAD_LEFT)); - //var_dump($this->thirdparty->name); - //var_dump(implode(unpack("H*", $this->thirdparty->name))); - //var_dump(price($this->total_tva, 0, $tmplang, 0, -1, 2)); - - $s = '01'.str_pad(dechex(strlen($this->thirdparty->name)), 2, '0', STR_PAD_LEFT).$name; - $s .= '02'.str_pad(dechex(strlen($this->thirdparty->tva_intra)), 2, '0', STR_PAD_LEFT).$vatnumber; - $s .= '03'.str_pad(dechex(strlen($datestring)), 2, '0', STR_PAD_LEFT).$date; - $s .= '04'.str_pad(dechex(strlen($pricewithtaxstring)), 2, '0', STR_PAD_LEFT).$pricewithtax; - $s .= '05'.str_pad(dechex(strlen($pricetaxstring)), 2, '0', STR_PAD_LEFT).$pricetax; - $s .= ''; // Hash of xml invoice - $s .= ''; // ecda signature - $s .= ''; // ecda public key - $s .= ''; // ecda signature of public key stamp - */ - - // Using TLV format - $s = pack('C1', 1).pack('C1', strlen($mysoc->name)).$mysoc->name; - $s .= pack('C1', 2).pack('C1', strlen($mysoc->tva_intra)).$mysoc->tva_intra; - $s .= pack('C1', 3).pack('C1', strlen($datestring)).$datestring; - $s .= pack('C1', 4).pack('C1', strlen($pricewithtaxstring)).$pricewithtaxstring; - $s .= pack('C1', 5).pack('C1', strlen($pricetaxstring)).$pricetaxstring; - $s .= ''; // Hash of xml invoice - $s .= ''; // ecda signature - $s .= ''; // ecda public key - $s .= ''; // ecda signature of public key stamp - - $s = base64_encode($s); - - return $s; - } - - - /** - * Build string for QR-Bill (Switzerland) - * - * @return string String for Switzerland QR Code if QR-Bill - */ - public function buildSwitzerlandQRString() - { - global $conf, $mysoc; - - $tmplang = new Translate('', $conf); - $tmplang->setDefaultLang('en_US'); - $tmplang->load("main"); - - $pricewithtaxstring = price2num($this->total_ttc, 2, 1); - $pricetaxstring = price2num($this->total_tva, 2, 1); - - $complementaryinfo = ''; - /* - Example: //S1/10/10201409/11/190512/20/1400.000-53/30/106017086/31/180508/32/7.7/40/2:10;0:30 - /10/ Numéro de facture – 10201409 - /11/ Date de facture – 12.05.2019 - /20/ Référence client – 1400.000-53 - /30/ Numéro IDE pour la TVA – CHE-106.017.086 TVA - /31/ Date de la prestation pour la comptabilisation de la TVA – 08.05.2018 - /32/ Taux de TVA sur le montant total de la facture – 7.7% - /40/ Conditions – 2% d’escompte à 10 jours, paiement net à 30 jours - */ - $datestring = dol_print_date($this->date, '%y%m%d'); - //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2); - //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2); - $complementaryinfo = '//S1/10/'.str_replace('/', '', $this->ref).'/11/'.$datestring; - if ($this->ref_client) { - $complementaryinfo .= '/20/'.$this->ref_client; - } - if ($this->thirdparty->tva_intra) { - $complementaryinfo .= '/30/'.$this->thirdparty->tva_intra; - } - - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $bankaccount = new Account($this->db); - - // Header - $s = ''; - $s .= "SPC\n"; - $s .= "0200\n"; - $s .= "1\n"; - // Info Seller ("Compte / Payable à") - if ($this->fk_account > 0) { - // Bank BAN if country is LI or CH. TODO Add a test to check than IBAN start with CH or LI - $bankaccount->fetch($this->fk_account); - $s .= $bankaccount->iban."\n"; - } else { - $s .= "\n"; - } - if ($bankaccount->id > 0 && getDolGlobalString('PDF_SWISS_QRCODE_USE_OWNER_OF_ACCOUNT_AS_CREDITOR')) { - // If a bank account is prodived and we ask to use it as creditor, we use the bank address - // TODO In a future, we may always use this address, and if name/address/zip/town/country differs from $mysoc, we can use the address of $mysoc into the final seller field ? - $s .= "S\n"; - $s .= dol_trunc($bankaccount->proprio, 70, 'right', 'UTF-8', 1)."\n"; - $addresslinearray = explode("\n", $bankaccount->owner_address); - $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 1 - $s .= dol_trunc(empty($addresslinearray[2]) ? '' : $addresslinearray[2], 70, 'right', 'UTF-8', 1)."\n"; // address line 2 - /*$s .= dol_trunc($mysoc->zip, 16, 'right', 'UTF-8', 1)."\n"; - $s .= dol_trunc($mysoc->town, 35, 'right', 'UTF-8', 1)."\n"; - $s .= dol_trunc($mysoc->country_code, 2, 'right', 'UTF-8', 1)."\n";*/ - } else { - $s .= "S\n"; - $s .= dol_trunc($mysoc->name, 70, 'right', 'UTF-8', 1)."\n"; - $addresslinearray = explode("\n", $mysoc->address); - $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 1 - $s .= dol_trunc(empty($addresslinearray[2]) ? '' : $addresslinearray[2], 70, 'right', 'UTF-8', 1)."\n"; // address line 2 - $s .= dol_trunc($mysoc->zip, 16, 'right', 'UTF-8', 1)."\n"; - $s .= dol_trunc($mysoc->town, 35, 'right', 'UTF-8', 1)."\n"; - $s .= dol_trunc($mysoc->country_code, 2, 'right', 'UTF-8', 1)."\n"; - } - // Final seller (Ultimate seller) ("Créancier final" = "En faveur de") - $s .= "\n"; - $s .= "\n"; - $s .= "\n"; - $s .= "\n"; - $s .= "\n"; - $s .= "\n"; - $s .= "\n"; - // Amount of payment (to do?) - $s .= price($pricewithtaxstring, 0, 'none', 0, 0, 2)."\n"; - $s .= ($this->multicurrency_code ? $this->multicurrency_code : $conf->currency)."\n"; - // Buyer - $s .= "S\n"; - $s .= dol_trunc($this->thirdparty->name, 70, 'right', 'UTF-8', 1)."\n"; - $addresslinearray = explode("\n", $this->thirdparty->address); - $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 1 - $s .= dol_trunc(empty($addresslinearray[2]) ? '' : $addresslinearray[2], 70, 'right', 'UTF-8', 1)."\n"; // address line 2 - $s .= dol_trunc($this->thirdparty->zip, 16, 'right', 'UTF-8', 1)."\n"; - $s .= dol_trunc($this->thirdparty->town, 35, 'right', 'UTF-8', 1)."\n"; - $s .= dol_trunc($this->thirdparty->country_code, 2, 'right', 'UTF-8', 1)."\n"; - // ID of payment - $s .= "NON\n"; // NON or QRR - $s .= "\n"; // QR Code reference if previous field is QRR - // Free text - if ($complementaryinfo) { - $s .= $complementaryinfo."\n"; - } else { - $s .= "\n"; - } - $s .= "EPD\n"; - // More text, complementary info - if ($complementaryinfo) { - $s .= $complementaryinfo."\n"; - } - $s .= "\n"; - //var_dump($s);exit; - return $s; @@ -1831,15 +856,10 @@ - * 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; @@ -1854,37 +873,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; - - /** - * Unit price before taxes - * @var float - * @deprecated - */ - public $price; - - /** @@ -1921,12 +903,0 @@ - * Local tax 1 type - * @var string - */ - public $localtax1_type; - - /** - * Local tax 2 type - * @var string - */ - public $localtax2_type; - - /** @@ -1939,7 +909,0 @@ - * Fixed discount - * @var float - * @deprecated - */ - public $remise; - - /** @@ -1975,10 +938,0 @@ - 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 - - public $buy_price_ht; - public $buyprice; // For backward compatibility - public $pa_ht; // For backward compatibility - - public $marge_tx; - public $marque_tx; - @@ -1987 +941 @@ - * Bit 0: 0 for common VAT - 1 if VAT french NPR + * Bit 0: 0 si TVA normal - 1 si TVA NPR @@ -1993,6 +947,9 @@ - public $special_code = 0; - - public $fk_user_author; - public $fk_user_modif; - - public $fk_accounting_account; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } --- /tmp/dsg/dolibarr/htdocs/core/class/github_19.0.3_commonobject.class.php +++ /tmp/dsg/dolibarr/htdocs/core/class/client_commonobject.class.php @@ -4 +4 @@ - * Copyright (C) 2010-2020 Juanjo Menent + * Copyright (C) 2010-2015 Juanjo Menent @@ -6 +6 @@ - * Copyright (C) 2011-2022 Philippe Grand + * Copyright (C) 2011-2019 Philippe Grand @@ -10 +10 @@ - * Copyright (C) 2015-2022 Alexandre Spangaro + * Copyright (C) 2015 Alexandre Spangaro @@ -14,2 +14,2 @@ - * Copyright (C) 2017 Rui Strecht - * Copyright (C) 2018-2023 Frédéric France + * Copyright (C) 2017 Rui Strecht + * Copyright (C) 2018-2019 Frédéric France @@ -17,3 +16,0 @@ - * Copyright (C) 2023 Gauthier VERDOL - * Copyright (C) 2021 Grégory Blémand - * Copyright (C) 2023 Lenin Rivas @@ -47,7 +43,0 @@ - const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc. - - /** - * @var string ID of module. - */ - public $module; - @@ -60 +50 @@ - * @var int The object identifier + * @var int The object identifier @@ -63,5 +52,0 @@ - - /** - * @var int The environment ID when using a multicompany module - */ - public $entity; @@ -76,5 +60,0 @@ - * @var string Error string that is hidden but can be used to store complementatry technical code. - */ - public $errorhidden; - - /** @@ -86,6 +66 @@ - * @var array To store error results of ->validateField() - */ - private $validateFieldsErrors = array(); - - /** - * @var string ID to identify managed object + * @var string ID to identify managed object @@ -96,12 +71 @@ - * @var string Fieldname with ID of parent key if this field has a parent - */ - public $fk_element; - - /** - * @var string Name to use for 'features' parameter to check module permissions user->rights->feature with restrictedArea(). - * Undefined means same value than $element. Can be use to force a check on another element for example for class of line, we mention here the parent element. - */ - public $element_for_permission; - - /** - * @var string Name of table without prefix where object is stored + * @var string Name of table without prefix where object is stored @@ -112 +76 @@ - * @var string Name of subtable line + * @var string Name of subtable line @@ -117,5 +80,0 @@ - * @var int 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table - */ - public $ismultientitymanaged; - - /** @@ -132,5 +90,0 @@ - * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. - */ - public $fields = array(); - - /** @@ -142,10 +95,0 @@ - * @var array To store result of ->liste_contact() - */ - public $contacts_ids; - - /** - * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object - */ - public $linked_objects; - - /** @@ -162,6 +106 @@ - * @var boolean[] Array of boolean with object id as key and value as true if linkedObjects full loaded for object id. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction. - */ - private $linkedObjectsFullLoaded = array(); - - /** - * @var CommonObject To store a cloned copy of object before to edit it and keep track of old properties + * @var Object To store a cloned copy of object before to edit it and keep track of old properties @@ -172,5 +110,0 @@ - * @var string To store old value of a modified ref - */ - public $oldref; - - /** @@ -181,4 +114,0 @@ - /** - * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user - */ - public $restrictiononfksoc = 0; @@ -194,4 +123,0 @@ - // Properties set and used by Agenda trigger - public $actionmsg; - public $actionmsg2; - @@ -204 +130 @@ - * @var Project The related project object + * @var Project The related project @@ -210 +136 @@ - * @var int The related project ID + * @var int The related project ID @@ -216 +141,0 @@ - * @var Project The related project object @@ -223,7 +148 @@ - * @deprecated - * @see $fk_project - */ - public $fk_projet; - - /** - * @var Contact A related contact object + * @var Contact a related contact @@ -235 +154 @@ - * @var int The related contact ID + * @var int The related contact ID @@ -241 +160 @@ - * @var Societe A related thirdparty object + * @var Societe A related thirdparty @@ -247 +166 @@ - * @var User A related user + * @var User A related user @@ -253 +172 @@ - * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type + * @var string The type of originating object ('commande', 'facture', ...) @@ -259 +178 @@ - * @var int The id of originating object + * @var int The id of originating object @@ -265,16 +184 @@ - * @var Object Origin object. This is set by fetch_origin() from this->origin and this->origin_id. - */ - public $origin_object; - - // TODO Remove this. Has been replaced with ->origin_object. - // This is set by fetch_origin() from this->origin and this->origin_id - /** @deprecated */ - public $expedition; - /** @deprecated */ - public $livraison; - /** @deprecated */ - public $commandeFournisseur; - - - /** - * @var string The object's reference + * @var string The object's reference @@ -285 +189,11 @@ - * @var string An external reference for the object + * @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 @@ -290,17 +204 @@ - * @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. Prefer use of status. - * @deprecated + * @var int The object's status @@ -310,7 +207,0 @@ - - /** - * @var int The object's status - * @see setStatut() - */ - public $status; - @@ -331 +222 @@ - * @var string The ISO country code on 2 chars. + * @var string @@ -334,3 +225,3 @@ - public $country_code; - - /** + public $country_code; + + /** @@ -350,11 +241,5 @@ - * @see getFullAddress(), $state - */ - public $state_code; - - /** - * @var int - * @see getFullAddress(), $region_code, $region - */ - public $region_id; - - /** + * @see getFullAddress(), state + */ + public $state_code; + + /** @@ -362,3 +247,3 @@ - * @see getFullAddress(), $region_id, $region - */ - public $region_code; + * @see getFullAddress(), region + */ + public $region; @@ -368,4 +253,3 @@ - * @see getFullAddress(), $region_id, $region_code - */ - public $region; - + * @see getFullAddress(), region + */ + public $region_code; @@ -398 +282 @@ - * @var int Payment method ID (cheque, cash, ...) + * @var int Payment method ID (cheque, cash, ...) @@ -404 +288 @@ - * @var int Payment terms ID + * @var int Payment terms ID @@ -410,12 +294 @@ - * @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 + * @var int Payment terms ID @@ -428 +301 @@ - * @var int Delivery address ID + * @var int Delivery address ID @@ -435 +308 @@ - * @var int Shipping method ID + * @var int Shipping method ID @@ -439,47 +311,0 @@ - - /** - * @var string Shipping method label - * @see setShippingMethod() - */ - public $shipping_method; - - // Multicurrency - /** - * @var int ID - */ - public $fk_multicurrency; - - /** - * @var string Multicurrency code - */ - public $multicurrency_code; - - /** - * @var float Multicurrency rate - */ - public $multicurrency_tx; - - /** - * @var float Multicurrency total without tax - */ - public $multicurrency_total_ht; - - /** - * @var float Multicurrency total vat - */ - public $multicurrency_total_tva; - - /** - * @var float Multicurrency total with tax - */ - public $multicurrency_total_ttc; - - /** - * @var float Multicurrency total localta1 - */ - public $multicurrency_total_localtax1; // not in database - - /** - * @var float Multicurrency total localtax2 - */ - public $multicurrency_total_localtax2; // not in database @@ -491,7 +316,0 @@ - public $model_pdf; - - /** - * @var string - * @deprecated - * @see $model_pdf - */ @@ -507,8 +326 @@ - * @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 + * @var int Bank account ID @@ -520 +332 @@ - * @var string Public note + * @var string Public note @@ -526 +338 @@ - * @var string Private note + * @var string Private note @@ -538 +350 @@ - * @var float Total amount before taxes + * @var float Total amount before taxes @@ -544 +356 @@ - * @var float Total VAT amount + * @var float Total VAT amount @@ -550 +362 @@ - * @var float Total local tax 1 amount + * @var float Total local tax 1 amount @@ -556 +368 @@ - * @var float Total local tax 2 amount + * @var float Total local tax 2 amount @@ -562 +374 @@ - * @var float Total amount with taxes + * @var float Total amount with taxes @@ -579 +391,19 @@ - * @var string The name + * @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 @@ -583,3 +413,3 @@ - /** - * @var string The lastname - */ + /** + * @var string The lastname + */ @@ -588,3 +418,3 @@ - /** - * @var string The firstname - */ + /** + * @var string The firstname + */ @@ -593,3 +423,3 @@ - /** - * @var string The civility code, not an integer - */ + /** + * @var string The civility code, not an integer + */ @@ -600,2 +430,2 @@ - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ @@ -614,62 +443,0 @@ - /** - * @var integer|string $date_modification; - * @deprecated Use date_modification - */ - public $date_update; - - /** - * @var integer|string $date_cloture; - */ - public $date_cloture; // Date closing (tms field) - - /** - * @var User User author/creation - * @deprecated Store only id in user_creation_id - */ - public $user_author; - - /** - * @var User User author/creation - * @deprecated - */ - public $user_creation; - - /** - * @var int User id author/creation - */ - public $user_creation_id; - - /** - * @var User User of validation - * @deprecated - */ - public $user_valid; - - /** - * @var User User of validation - * @deprecated - */ - public $user_validation; - - /** - * @var int User id of validation - */ - public $user_validation_id; - - /** - * @var int User id closing object - */ - public $user_closing_id; - - /** - * @var User User last modifier - * @deprecated - */ - public $user_modification; - - /** - * @var int User id last modifier - */ - public $user_modification_id; - - @@ -679,62 +447 @@ - * @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 from getSommePaiement() (used to show correct status) - * @deprecated Duplicate of $totalpaid - */ - public $alreadypaid; - /** - * @var float Amount already paid from getSommePaiement() (used to show correct status) - */ - public $totalpaid; - - /** - * @var array Array with label of status - */ - public $labelStatus = array(); - - /** - * @var array Array with short label of status - */ - public $labelStatusShort = array(); - - /** - * @var array Array to store list of tpl - */ - public $tpl; - - - /** - * @var int show photo on popup - */ - public $showphoto_on_popup; - - /** - * @var array nb used in load_stateboard - */ - public $nb = array(); - - /** - * @var int used for the return of show_photos() - */ - public $nbphoto; - - /** - * @var string output - */ - public $output; - - /** - * @var array extra parameters - */ - public $extraparams = array(); - - /** - * @var array List of child tables. To test if we can delete object. + * @var array List of child tables. To test if we can delete object. @@ -746,2 +453,2 @@ - * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will - * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object. + * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will + * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object @@ -751,25 +457,0 @@ - /** - * @var Product Populate by fetch_product() - */ - public $product; - - /** - * @var int Populate by setPaymentTerms() - */ - public $cond_reglement_supplier_id; - - /** - * @var string Populate by setPaymentTerms() - */ - public $deposit_percent; - - - /** - * @var string Populate by setRetainedWarrantyPaymentTerms() - */ - public $retained_warranty_fk_cond_reglement; - - /** - * @var int Populate by setWarehouse() - */ - public $warehouse_id; @@ -778,2 +459,0 @@ - - @@ -788 +468 @@ - * @return int Return integer <0 if KO, 0 if OK but not found, >0 if OK and exists + * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists @@ -795 +475 @@ - $sql .= " FROM ".$db->prefix().$element; + $sql .= " FROM ".MAIN_DB_PREFIX.$element; @@ -798,7 +478,4 @@ - if ($id > 0) { - $sql .= " AND rowid = ".((int) $id); - } elseif ($ref) { - $sql .= " AND ref = '".$db->escape($ref)."'"; - } elseif ($ref_ext) { - $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'"; - } else { + if ($id > 0) $sql .= " AND rowid = ".$db->escape($id); + elseif ($ref) $sql .= " AND ref = '".$db->escape($ref)."'"; + elseif ($ref_ext) $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'"; + else { @@ -809,3 +486 @@ - if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority - $sql .= " AND entity = ".((int) $conf->entity); - } + if ($ref || $ref_ext) $sql .= " AND entity = ".$conf->entity; @@ -815 +490,2 @@ - if ($resql) { + if ($resql) + { @@ -817,5 +493,2 @@ - if ($num > 0) { - return 1; - } else { - return 0; - } + if ($num > 0) return 1; + else return 0; @@ -825,106 +497,0 @@ - - /** - * setErrorsFromObject - * - * @param CommonObject $object commonobject - * @return void - */ - public function setErrorsFromObject($object) - { - if (!empty($object->error)) { - $this->error = $object->error; - } - if (!empty($object->errors)) { - $this->errors = array_merge($this->errors, $object->errors); - } - } - - /** - * Return array of datas to show into a tooltip. This method must be implemented in each object class. - * - * @since v18 - * @param array $params params to construct tooltip data - * @return array - */ - public function getTooltipContentArray($params) - { - return []; - } - - /** - * getTooltipContent - * - * @param array $params params - * @since v18 - * @return string - */ - public function getTooltipContent($params) - { - global $action, $extrafields, $langs, $hookmanager; - - // If there is too much extrafields, we do not include them into tooltip - $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3); - - $datas = $this->getTooltipContentArray($params); - $count = 0; - - // Add extrafields - if (!empty($extrafields->attributes[$this->table_element]['label'])) { - $datas['opendivextra'] = '
'; - foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) { - if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') { - continue; - } - if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) { - $datas['more_extrafields'] = '
...'; - break; - } - $enabled = 1; - if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) { - $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2'); - } - if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) { - $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2'); - } - $perms = 1; - if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) { - $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2'); - } - if (empty($enabled)) { - continue; // 0 = Never visible field - } - if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) { - continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation - } - if (empty($perms)) { - continue; // 0 = Not visible - } - if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) { - $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); - } - $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]); - if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') { - $datas[$key]= '
'. $labelextra . ''; - } else { - $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]); - $datas[$key]= '
'. $labelextra . ': ' . $extrafields->showOutputField($key, $value, '', $this->table_element); - $count++; - } - } - $datas['closedivextra'] = '
'; - } - - $hookmanager->initHooks(array($this->element . 'dao')); - $parameters = array( - 'tooltipcontentarray' => &$datas, - 'params' => $params, - ); - // Note that $action and $object may have been modified by some hooks - $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action); - - //var_dump($datas); - $label = implode($datas); - - return $label; - } - @@ -951,9 +518,10 @@ - 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'] : ''); @@ -970,9 +538,60 @@ - 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'] : ''); + } + + /** + * Return full name (civility+' '+name+' '+lastname) + * + * @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 + * @param int $maxlen Maximum length + * @return string String with full name + */ + public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0) + { + //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
\n"; + $lastname = $this->lastname; + $firstname = $this->firstname; + if (empty($lastname)) $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : ''))))); + + $ret = ''; + if ($option && $this->civility_code) + { + if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' '; + else $ret .= $this->civility_code.' '; + } + + $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder); + + return dol_trunc($ret, $maxlen); + } + + /** + * Return clicable link of object (with eventually picto) + * + * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link) + * @return string HTML Code for Kanban thumb. + */ + public function getKanbanView($option = '') + { + $return = '
'; + $return .= '
'; + $return .= ''; + $return .= ''; // Can be image + $return .= ''; + $return .= '
'; + $return .= ''.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).''; + $return .= '
'; + $return .= '
'; + $return .= '
'; + + return $return; @@ -992 +611,2 @@ - if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) { + if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) + { @@ -999,3 +619,4 @@ - 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); @@ -1006 +627 @@ - } + } @@ -1010,0 +632,165 @@ + + /** + * Return full address for banner + * + * @param string $htmlkey HTML id to make banner content unique + * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) + * @return string Full address string + */ + public function getBannerAddress($htmlkey, $object) + { + global $conf, $langs, $form, $extralanguages; + + $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS + + $contactid = 0; + $thirdpartyid = 0; + $elementforaltlanguage = $this->element; + if ($this->element == 'societe') + { + $thirdpartyid = $this->id; + } + if ($this->element == 'contact') + { + $contactid = $this->id; + $thirdpartyid = $object->fk_soc; + } + if ($this->element == 'user') + { + $contactid = $this->contact_id; + $thirdpartyid = $object->fk_soc; + } + + $out = ''; + + $outdone = 0; + $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); + if ($coords) + { + if (!empty($conf->use_javascript_ajax)) + { + // Add picto with tooltip on map + $namecoords = ''; + if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) + { + $namecoords .= $object->name.'
'; + } + $namecoords .= $this->getFullName($langs, 1).'
'.$coords; + // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile + $out .= ''; + $out .= img_picto($langs->trans("Address"), 'map-marker-alt'); + $out .= ' '; + } + $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++; + $outdone++; + + // List of extra languages + $arrayoflangcode = array(); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE; + + if (is_array($arrayoflangcode) && count($arrayoflangcode)) { + if (!is_object($extralanguages)) { + include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php'; + $extralanguages = new ExtraLanguages($this->db); + } + $extralanguages->fetch_name_extralanguages($elementforaltlanguage); + + if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) + { + $out .= "\n"; + $this->fetchValuesForExtraLanguages(); + if (!is_object($form)) $form = new Form($this->db); + $htmltext = ''; + // If there is extra languages + foreach ($arrayoflangcode as $extralangcode) { + $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"'); + $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode); + $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); + } + $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft'); + } + } + } + + 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; + } + $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++; + } + if (!empty($this->phone_pro)) { + $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++; + } + if (!empty($this->phone_perso)) { + $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++; + } + if (!empty($this->user_mobile)) { + $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++; + } + if (!empty($this->office_fax)) { + $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)) + { + $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); + $outdone++; + } + + if (!empty($conf->socialnetworks->enabled)) + { + $outsocialnetwork = ''; + + if (is_array($this->socialnetworks) && count($this->socialnetworks) > 0) { + foreach ($this->socialnetworks as $key => $value) { + $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key); + $outdone++; + } + } 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'); + $outdone++; + if ($this->twitter) $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter'); + $outdone++; + if ($this->facebook) $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook'); + $outdone++; + if ($this->linkedin) $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin'); + $outdone++; + } + + if ($outsocialnetwork) { + $out .= '
'.$outsocialnetwork.'
'; + } + } + + if ($out) return ''."\n".$out.''."\n"; + else return ''; + } @@ -1024 +810,2 @@ - if (empty($this->last_main_doc)) { + if (empty($this->last_main_doc)) + { @@ -1031 +818,2 @@ - if ($result < 0) { + if ($result < 0) + { @@ -1037 +825,2 @@ - if (empty($ecmfile->id)) { + if (empty($ecmfile->id)) + { @@ -1039 +828,2 @@ - if ($initsharekey) { + if ($initsharekey) + { @@ -1041,2 +831 @@ - - // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull + // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first @@ -1050 +839 @@ - $ecmfile->keywords = ''; // keyword content + $ecmfile->keyword = ''; // keyword content @@ -1059,4 +848,5 @@ - } else { - return ''; - } - } elseif (empty($ecmfile->share)) { + } + else return ''; + } + elseif (empty($ecmfile->share)) + { @@ -1064 +854,2 @@ - if ($initsharekey) { + if ($initsharekey) + { @@ -1068,3 +859,2 @@ - } else { - return ''; - } + } + else return ''; @@ -1083,2 +873,2 @@ - //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required. - //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required. + //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required. + //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required. @@ -1086,8 +876,5 @@ - if (!empty($ecmfile->share)) { - $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share - } - if ($forcedownload) { - $paramlink .= ($paramlink ? '&' : '').'attachment=1'; - } - - if ($relativelink) { + if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share + if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1'; + + if ($relativelink) + { @@ -1095 +882,3 @@ - } else { + } + else + { @@ -1104 +893 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1108,5 +897,5 @@ - * @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 Return integer <0 if KO, 0 if already added or code not valid, >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 @@ -1116 +905 @@ - // phpcs:enable + // phpcs:enable @@ -1123 +912,2 @@ - if ($fk_socpeople <= 0) { + if ($fk_socpeople <= 0) + { @@ -1129 +919,2 @@ - if (!$type_contact) { + if (!$type_contact) + { @@ -1137 +928,2 @@ - if (is_numeric($type_contact)) { + if (is_numeric($type_contact)) + { @@ -1139 +931,3 @@ - } else { + } + else + { @@ -1142 +936 @@ - $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; @@ -1148 +942,2 @@ - if ($resql) { + if ($resql) + { @@ -1150,7 +945,7 @@ - if ($obj) { - $id_type_contact = $obj->rowid; - } - } - } - - if ($id_type_contact == 0) { + if ($obj) $id_type_contact = $obj->rowid; + } + } + + if ($id_type_contact == 0) + { + $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT'; @@ -1158 +953 @@ - return 0; + return -3; @@ -1179 +974 @@ - $sql = "INSERT INTO ".$this->db->prefix()."element_contact"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; @@ -1181 +976 @@ - $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , "; + $sql .= " VALUES (".$this->id.", ".$fk_socpeople." , "; @@ -1183 +978 @@ - $sql .= ", 4, ".((int) $id_type_contact); + $sql .= ", 4, ".$id_type_contact; @@ -1187,2 +982,4 @@ - if ($resql) { - if (!$notrigger) { + if ($resql) + { + if (!$notrigger) + { @@ -1190 +987,2 @@ - if ($result < 0) { + if ($result < 0) + { @@ -1198,2 +996,5 @@ - } else { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + } + else + { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { @@ -1201,0 +1003 @@ + echo 'err rollback'; @@ -1203,2 +1005,4 @@ - } else { - $this->error = $this->db->lasterror(); + } + else + { + $this->error = $this->db->error(); @@ -1209,6 +1013,4 @@ - } else { - return 0; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + } else return 0; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1224 +1026 @@ - // phpcs:enable + // phpcs:enable @@ -1226,2 +1028,5 @@ - foreach ($contacts as $contact) { - if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) { + foreach ($contacts as $contact) + { + if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) + { + $this->error = $this->db->lasterror(); @@ -1234 +1039 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1242 +1047 @@ - * @return int Return integer <0 if KO, >= 0 if OK + * @return int <0 if KO, >= 0 if OK @@ -1246 +1051 @@ - // phpcs:enable + // phpcs:enable @@ -1248 +1053 @@ - $sql = "UPDATE ".$this->db->prefix()."element_contact set"; + $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; @@ -1250,7 +1055,3 @@ - if ($type_contact_id) { - $sql .= ", fk_c_type_contact = ".((int) $type_contact_id); - } - if ($fk_socpeople) { - $sql .= ", fk_socpeople = ".((int) $fk_socpeople); - } - $sql .= " where rowid = ".((int) $rowid); + if ($type_contact_id) $sql .= ", fk_c_type_contact = '".$type_contact_id."'"; + if ($fk_socpeople) $sql .= ", fk_socpeople = '".$fk_socpeople."'"; + $sql .= " where rowid = ".$rowid; @@ -1258 +1059,2 @@ - if ($resql) { + if ($resql) + { @@ -1260 +1062,3 @@ - } else { + } + else + { @@ -1266 +1070 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1276 +1080 @@ - // phpcs:enable + // phpcs:enable @@ -1279 +1082,0 @@ - $error = 0; @@ -1283,24 +1086,12 @@ - if (!$error && empty($notrigger)) { - // Call trigger - $this->context['contact_id'] = ((int) $rowid); - $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); - if ($result < 0) { - $error++; - } - // End call triggers - } - - if (!$error) { - dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql .= " WHERE rowid = ".((int) $rowid); - - $result = $this->db->query($sql); - if (!$result) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } - - if (!$error) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; + $sql .= " WHERE rowid =".$rowid; + + dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); + if ($this->db->query($sql)) + { + if (!$notrigger) + { + $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); + if ($result < 0) { $this->db->rollback(); return -1; } + } + @@ -1309 +1100,3 @@ - } else { + } + else + { @@ -1316,3 +1109,3 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Delete all links between an object $this and all its contacts in llx_element_contact + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Delete all links between an object $this and all its contacts @@ -1322 +1115 @@ - * @return int Return integer <0 if KO, 0=Nothing done, >0 if OK + * @return int >0 if OK, <0 if KO @@ -1326,2 +1119 @@ - // phpcs:enable - $listId = ''; + // phpcs:enable @@ -1331,16 +1123,10 @@ - if (!empty($typeContact)) { - foreach ($typeContact as $key => $value) { - array_push($temp, $key); - } - $listId = implode(",", $temp); - } - - // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for - // any type or record instead of only the ones of the current object. So we do nothing in such a case. - if (empty($listId)) { - return 0; - } - - $sql = "DELETE FROM ".$this->db->prefix()."element_contact"; - $sql .= " WHERE element_id = ".((int) $this->id); - $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")"; + foreach ($typeContact as $key => $value) + { + array_push($temp, $key); + } + $listId = implode(",", $temp); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; + $sql .= " WHERE element_id = ".$this->id; + if ($listId) + $sql .= " AND fk_c_type_contact IN (".$listId.")"; @@ -1349 +1135,2 @@ - if ($this->db->query($sql)) { + if ($this->db->query($sql)) + { @@ -1351 +1138,3 @@ - } else { + } + else + { @@ -1357 +1146 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1361,11 +1150,9 @@ - * @param int $statusoflink Status of links to get (-1=all). Not used. - * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user) - * @param int $list 0:Returned array contains all properties, 1:Return array contains just id - * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) - * @param int $status Status of user or company - * @param array $arrayoftcids Array with ID of type of contacts. If we provide this, we can make a ec.fk_c_type_contact in ($arrayoftcids) to avoid link on tc table. TODO Not implemented. - * @return array|int Array of contacts, -1 if error - */ - public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array()) - { - // phpcs:enable + * @param int $status Status of links to get (-1=all) + * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user) + * @param int $list 0:Return array contains all properties, 1:Return array contains just id + * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) + * @return array|int Array of contacts, -1 if error + */ + public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '') + { + // phpcs:enable @@ -1377,6 +1164,2 @@ - if ($source == 'internal') { - $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; - } - if ($source == 'external' || $source == 'thirdparty') { - $sql .= ", t.fk_soc as socid, t.statut as statuscontact"; - } + if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; + if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact"; @@ -1384,31 +1167,13 @@ - $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label"; - $sql .= " FROM ".$this->db->prefix()."c_type_contact tc,"; - $sql .= " ".$this->db->prefix()."element_contact ec"; - if ($source == 'internal') { // internal contact (user) - $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid"; - } - if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople) - $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid"; - } - $sql .= " WHERE ec.element_id = ".((int) $this->id); - $sql .= " AND ec.fk_c_type_contact = tc.rowid"; - $sql .= " AND tc.element = '".$this->db->escape($this->element)."'"; - if ($code) { - $sql .= " AND tc.code = '".$this->db->escape($code)."'"; - } - if ($source == 'internal') { - $sql .= " AND tc.source = 'internal'"; - if ($status >= 0) { - $sql .= " AND t.statut = ".((int) $status); - } - } - if ($source == 'external' || $source == 'thirdparty') { - $sql .= " AND tc.source = 'external'"; - if ($status >= 0) { - $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople - } - } - $sql .= " AND tc.active = 1"; - if ($statusoflink >= 0) { - $sql .= " AND ec.statut = ".((int) $statusoflink); - } + $sql .= ", tc.source, tc.element, tc.code, tc.libelle"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; + $sql .= ", ".MAIN_DB_PREFIX."element_contact ec"; + if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; + if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; + $sql .= " WHERE ec.element_id =".$this->id; + $sql .= " AND ec.fk_c_type_contact=tc.rowid"; + $sql .= " AND tc.element='".$this->db->escape($this->element)."'"; + if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'"; + if ($source == 'internal') $sql .= " AND tc.source = 'internal'"; + if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'"; + $sql .= " AND tc.active=1"; + if ($status >= 0) $sql .= " AND ec.statut = ".$status; @@ -1419 +1184,2 @@ - if ($resql) { + if ($resql) + { @@ -1422 +1188,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -1425 +1192,2 @@ - if (!$list) { + if (!$list) + { @@ -1427,21 +1195,8 @@ - $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label); - $tab[$i] = array( - 'parentId' => $this->id, - 'source' => $obj->source, - 'socid' => $obj->socid, - 'id' => $obj->id, - 'nom' => $obj->lastname, // For backward compatibility - 'civility' => $obj->civility, - 'lastname' => $obj->lastname, - 'firstname' => $obj->firstname, - 'email'=>$obj->email, - 'login'=> (empty($obj->login) ? '' : $obj->login), - 'photo' => (empty($obj->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 { + $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); + $tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id, + '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 + { @@ -1455 +1210,3 @@ - } else { + } + else + { @@ -1467 +1224 @@ - * @return int Return integer <0 if KO, >=0 if OK + * @return int <0 if KO, >=0 if OK @@ -1472,3 +1229,5 @@ - $sql .= " tc.code, tc.libelle as type_label"; - $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)"; - $sql .= " WHERE ec.rowid =".((int) $rowid); + $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; @@ -1480 +1239,2 @@ - if ($resql) { + if ($resql) + { @@ -1486 +1246,3 @@ - } else { + } + else + { @@ -1493 +1255 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1506 +1268 @@ - // phpcs:enable + // phpcs:enable @@ -1509,6 +1271,2 @@ - if (empty($order)) { - $order = 'position'; - } - if ($order == 'position') { - $order .= ',code'; - } + if (empty($order)) $order = 'position'; + if ($order == 'position') $order .= ',code'; @@ -1517,2 +1275,2 @@ - $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position"; - $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc"; + $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; @@ -1520,9 +1278,3 @@ - if ($activeonly == 1) { - $sql .= " AND tc.active=1"; // only the active types - } - if (!empty($source) && $source != 'all') { - $sql .= " AND tc.source='".$this->db->escape($source)."'"; - } - if (!empty($code)) { - $sql .= " AND tc.code='".$this->db->escape($code)."'"; - } + if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types + if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'"; + if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'"; @@ -1533 +1285,2 @@ - if ($resql) { + if ($resql) + { @@ -1536 +1289,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -1540,6 +1294,3 @@ - $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label); - if (empty($option)) { - $tab[$obj->rowid] = $libelle_type; - } else { - $tab[$obj->code] = $libelle_type; - } + $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); + if (empty($option)) $tab[$obj->rowid] = $libelle_type; + else $tab[$obj->code] = $libelle_type; @@ -1549 +1300,3 @@ - } else { + } + else + { @@ -1555,0 +1309 @@ + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1568,0 +1323 @@ + // phpcs:enable @@ -1571,2 +1325,0 @@ - $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda')); - @@ -1575,2 +1328,2 @@ - $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element"; - $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc"; + $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; @@ -1586 +1339 @@ - if ($activeonly == 1) { + if ($activeonly == 1) @@ -1588,3 +1341,2 @@ - } - - if (!empty($source) && $source != 'all') { + + if (!empty($source) && $source != 'all') @@ -1592,3 +1344,2 @@ - } - - if (!empty($code)) { + + if (!empty($code)) @@ -1596 +1346,0 @@ - } @@ -1609,2 +1358,0 @@ - $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal")); - @@ -1624 +1372 @@ - if (!empty($conf->{$modulename}->enabled)) { + if ($conf->{$modulename}->enabled) { @@ -1626,4 +1374,3 @@ - $tmpelement = $obj->element; - $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code; - $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label); - if (empty($option)) { + $transkey = "TypeContact_".$obj->element."_".$source."_".$obj->code; + $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); + if (empty($option)) @@ -1631,3 +1378 @@ - } else { - $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; - } + else $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; @@ -1638 +1383,3 @@ - } else { + } + else + { @@ -1674,9 +1421,5 @@ - $sql .= " FROM ".$this->db->prefix()."element_contact as ec,"; - if ($source == 'internal') { - $sql .= " ".$this->db->prefix()."user as c,"; - } - if ($source == 'external') { - $sql .= " ".$this->db->prefix()."socpeople as c,"; - } - $sql .= " ".$this->db->prefix()."c_type_contact as tc"; - $sql .= " WHERE ec.element_id = ".((int) $id); + $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; + if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,"; + if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,"; + $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= " WHERE ec.element_id = ".$id; @@ -1684,6 +1427,2 @@ - if ($source == 'internal') { - $sql .= " AND c.entity IN (".getEntity('user').")"; - } - if ($source == 'external') { - $sql .= " AND c.entity IN (".getEntity('societe').")"; - } + if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")"; + if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")"; @@ -1691,5 +1430,3 @@ - $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."'"; @@ -1697,3 +1434 @@ - if ($status) { - $sql .= " AND ec.statut = ".((int) $status); - } + if ($status) $sql .= " AND ec.statut = ".$status; @@ -1703,2 +1438,4 @@ - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { @@ -1708 +1445,3 @@ - } else { + } + else + { @@ -1716,6 +1455,6 @@ - // 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. - * @return int Return integer <0 if KO, >0 if OK + // 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 @@ -1725,8 +1464,4 @@ - // phpcs:enable - if (empty($contactid)) { - $contactid = $this->contact_id; - } - - if (empty($contactid)) { - return 0; - } + // phpcs:enable + if (empty($contactid)) $contactid = $this->contactid; + + if (empty($contactid)) return 0; @@ -1741 +1476 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1746 +1481 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -1750,2 +1485,4 @@ - // phpcs:enable - if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) { + // phpcs:enable + global $conf; + + if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) @@ -1753 +1489,0 @@ - } @@ -1757,2 +1493,2 @@ - $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0); - if ($force_thirdparty_id) { + $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); + if ($force_thirdparty_id) @@ -1760 +1495,0 @@ - } @@ -1765,3 +1499,0 @@ - if ($result<0) { - $this->errors=array_merge($this->errors, $thirdparty->errors); - } @@ -1771 +1503 @@ - if (getDolGlobalString('PRODUIT_MULTIPRICES') && empty($this->thirdparty->price_level)) { + if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) { @@ -1776 +1508 @@ - } else { + } else @@ -1778 +1509,0 @@ - } @@ -1786,2 +1517,2 @@ - * @param string $ref Wildcard - * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO + * @param string $ref Wildcard + * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO @@ -1795,3 +1526 @@ - $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element; - $sql .= " WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."'"; // no escapeforlike here - $sql .= " LIMIT 1"; + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1'; @@ -1807,11 +1536,4 @@ - if (method_exists($this, 'fetch')) { - return $this->fetch($result->rowid); - } else { - $this->error = 'Fetch method not implemented on '.get_class($this); - dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR); - array_push($this->errors, $this->error); - return -1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + return $this->fetch($result->rowid); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1823 +1545 @@ - * @return int Return integer <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) + * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) @@ -1827 +1549 @@ - // phpcs:enable + // phpcs:enable @@ -1833,12 +1555,11 @@ - if (empty($idtype) && $idtype != '0') { // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined - if ($this->element == 'product' && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) { - $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; - } elseif ($this->element == 'societe') { - $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; - } else { - dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); - } - } - - if ($idtype > 0) { - if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) { // If data not already loaded + if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined + { + if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + elseif ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; + else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); + } + + if ($idtype > 0) + { + if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded + { @@ -1846,2 +1567,2 @@ - $sql .= " FROM ".$this->db->prefix()."c_barcode_type"; - $sql .= " WHERE rowid = ".((int) $idtype); + $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; + $sql .= " WHERE rowid = ".$idtype; @@ -1850 +1571,2 @@ - if ($resql) { + if ($resql) + { @@ -1857 +1579,3 @@ - } else { + } + else + { @@ -1866 +1590 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1870,13 +1594 @@ - * @return int Return integer <0 if KO, >=0 if OK - */ - public function fetch_project() - { - // phpcs:enable - return $this->fetch_projet(); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load the project with id $this->fk_project into this->project - * - * @return int Return integer <0 if KO, >=0 if OK + * @return int <0 if KO, >=0 if OK @@ -1886 +1598 @@ - // phpcs:enable + // phpcs:enable @@ -1889,6 +1601,2 @@ - if (empty($this->fk_project) && !empty($this->fk_projet)) { - $this->fk_project = $this->fk_projet; // For backward compatibility - } - if (empty($this->fk_project)) { - return 0; - } + if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility + if (empty($this->fk_project)) return 0; @@ -1904 +1612 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1908 +1616 @@ - * @return int Return integer <0 if KO, >=0 if OK + * @return int <0 if KO, >=0 if OK @@ -1912 +1620 @@ - // phpcs:enable + // phpcs:enable @@ -1915,3 +1623 @@ - if (empty($this->fk_product)) { - return 0; - } + if (empty($this->fk_product)) return 0; @@ -1926 +1632 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1931 +1637 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -1935 +1641 @@ - // phpcs:enable + // phpcs:enable @@ -1942,5 +1648,3 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Read linked origin object. - * Set ->origin_object - * Set also ->expedition or ->livraison or ->commandFournisseur (deprecated) + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Read linked origin object @@ -1952,10 +1656,4 @@ - // phpcs:enable - if ($this->origin == 'shipping') { - $this->origin = 'expedition'; - } - if ($this->origin == 'delivery') { - $this->origin = 'livraison'; - } - if ($this->origin == 'order_supplier' || $this->origin == 'supplier_order') { - $this->origin = 'commandeFournisseur'; - } + // phpcs:enable + if ($this->origin == 'shipping') $this->origin = 'expedition'; + if ($this->origin == 'delivery') $this->origin = 'livraison'; + if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur'; @@ -1966,16 +1664,13 @@ - $this->origin_object = new $classname($this->db); - $this->origin_object->fetch($this->origin_id); - - // TODO Remove this line - $this->$origin = $this->origin_object; - } - - /** - * 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 Return integer <0 if KO, >0 if OK - */ + $this->$origin = new $classname($this->db); + $this->$origin->fetch($this->origin_id); + } + + /** + * 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 + */ @@ -1988,2 +1683,2 @@ - $sql = "SELECT rowid FROM ".$this->db->prefix().$table; - $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'"; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; + $sql .= " WHERE ".$field." = '".$key."'"; @@ -1993 +1688 @@ - $sql .= " AND entity = ".((int) $conf->entity); + $sql .= " AND entity = ".$conf->entity; @@ -1998,2 +1693,3 @@ - if ($resql) { - $obj = $this->db->fetch_object($resql); + if ($resql) + { + $row = $this->db->fetch_row($resql); @@ -2001,9 +1697,2 @@ - if ($obj) { - if (method_exists($this, 'fetch')) { - return $this->fetch($obj->rowid); - } else { - $this->error = 'fetch() method not implemented on '.get_class($this); - dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR); - array_push($this->errors, $this->error); - return -1; - } + if ($row[0] > 0) { + $result = $this->fetch($row[0]); @@ -2022 +1711 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -2028,2 +1717,2 @@ - $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table; - $sql .= " WHERE rowid = ".((int) $id); + $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; + $sql .= " WHERE rowid = ".$id; @@ -2033 +1722,2 @@ - if ($resql) { + if ($resql) + { @@ -2049 +1739 @@ - * @param string $format Data format ('text', 'int', 'date'). 'text' is used if not defined + * @param string $format Data format ('text', 'date'). 'text' is used if not defined @@ -2054 +1744 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -2059,14 +1749,10 @@ - global $user; - - if (empty($table)) { - $table = $this->table_element; - } - if (empty($id)) { - $id = $this->id; - } - if (empty($format)) { - $format = 'text'; - } - if (empty($id_field)) { - $id_field = 'rowid'; - } + global $user, $langs, $conf; + + if (empty($table)) $table = $this->table_element; + if (empty($id)) $id = $this->id; + if (empty($format)) $format = 'text'; + if (empty($id_field)) $id_field = 'rowid'; + + $error = 0; + + $this->db->begin(); @@ -2075,61 +1761,18 @@ - if ($table == 'product' && $field == 'note_private') { - $field = 'note'; - } - - if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) { - $fk_user_field = 'fk_user_mod'; - } - if (in_array($table, array('prelevement_bons'))) { // TODO Add a field fk_user_modif into llx_prelevement_bons - $fk_user_field = ''; - } - - if ($trigkey) { - $oldvalue = null; - - $sql = "SELECT " . $field; - $sql .= " FROM " . MAIN_DB_PREFIX . $table; - $sql .= " WHERE " . $id_field . " = " . ((int) $id); - - $resql = $this->db->query($sql); - if ($resql) { - if ($obj = $this->db->fetch_object($resql)) { - if ($format == 'date') { - $oldvalue = $this->db->jdate($obj->$field); - } else { - $oldvalue = $obj->$field; - } - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - - $error = 0; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $this->db->begin(); - - $sql = "UPDATE ".$this->db->prefix().$table." SET "; - - if ($format == 'text') { - $sql .= $field." = '".$this->db->escape($value)."'"; - } elseif ($format == 'int') { - $sql .= $field." = ".((int) $value); - } elseif ($format == 'date') { - $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); - } elseif ($format == 'dategmt') { - $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null"); - } - - if ($fk_user_field) { - if (!empty($fuser) && is_object($fuser)) { - $sql .= ", ".$fk_user_field." = ".((int) $fuser->id); - } elseif (empty($fuser) || $fuser != 'none') { - $sql .= ", ".$fk_user_field." = ".((int) $user->id); - } - } - - $sql .= " WHERE ".$id_field." = ".((int) $id); - + if ($table == 'product' && $field == 'note_private') $field = 'note'; + if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod'; + + $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; + + if ($format == 'text') $sql .= $field." = '".$this->db->escape($value)."'"; + elseif ($format == 'int') $sql .= $field." = ".$this->db->escape($value); + elseif ($format == 'date') $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); + + if ($fk_user_field) + { + if (!empty($fuser) && is_object($fuser)) $sql .= ", ".$fk_user_field." = ".$fuser->id; + elseif (empty($fuser) || $fuser != 'none') $sql .= ", ".$fk_user_field." = ".$user->id; + } + + $sql .= " WHERE ".$id_field." = ".$id; + + dol_syslog(__METHOD__."", LOG_DEBUG); @@ -2137,2 +1780,4 @@ - if ($resql) { - if ($trigkey) { + if ($resql) + { + if ($trigkey) + { @@ -2140 +1785,2 @@ - if (method_exists($this, 'fetch')) { + if (empty($this->fields) && method_exists($this, 'fetch')) + { @@ -2142 +1788,3 @@ - } else { + } + else + { @@ -2145,17 +1793,7 @@ - $this->oldcopy = clone $this; - if (property_exists($this->oldcopy, $field)) { - $this->oldcopy->$field = $oldvalue; - } - - if ($result >= 0) { - $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors - } - if ($result < 0) { - $error++; - } - } - - if (!$error) { - if (property_exists($this, $field)) { - $this->$field = $value; - } + if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors + if ($result < 0) $error++; + } + + if (!$error) + { + if (property_exists($this, $field)) $this->$field = $value; @@ -2164 +1802,3 @@ - } else { + } + else + { @@ -2168,6 +1808,4 @@ - } 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(); @@ -2179 +1817 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -2183,2 +1821 @@ - * @param string $filter Optional SQL filter. Example: "(t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here. - * Use SQL and not Universal Search Filter. @TODO Replace this with an USF string after changing all ->next_prev_filter + * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" @@ -2187 +1824 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -2191 +1828 @@ - // phpcs:enable + // phpcs:enable @@ -2194 +1831,2 @@ - if (!$this->table_element) { + if (!$this->table_element) + { @@ -2198,8 +1836 @@ - if ($fieldid == 'none') { - return 1; - } - - // For backward compatibility - if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') { - $fieldid = 'titre'; - } + if ($fieldid == 'none') return 1; @@ -2209,3 +1840 @@ - if ($user->socid > 0) { - $socid = $user->socid; - } + if ($user->socid > 0) $socid = $user->socid; @@ -2216,4 +1845,2 @@ - if ($this->element == 'societe') { - $aliastablesociete = 'te'; // te as table_element - } - $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc; + if ($this->element == 'societe') $aliastablesociete = 'te'; // te as table_element + @@ -2221 +1848,4 @@ - $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te"; + $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"; + } @@ -2224,24 +1854,11 @@ - $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity - } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid - } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid - } - if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc"; - } - if ($fieldid == 'rowid') { - $sql .= " WHERE te.".$fieldid." < ".((int) $this->id); - } else { - $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - } - if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND sc.fk_user = ".((int) $user->id); - } - if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)'; - } - if (!empty($filter)) { - if (!preg_match('/^\s*AND/i', $filter)) { - $sql .= " AND "; - } + $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 == 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($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)) + { + if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility @@ -2252,4 +1869,3 @@ - $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 ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid - } + $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 @@ -2257 +1873 @@ - if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) { + if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { @@ -2261 +1877,2 @@ - $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))"; + $sql .= " AND ug.fk_user = te.rowid"; + $sql .= " AND ug.entity IN (".getEntity($this->element).")"; @@ -2271,10 +1888,4 @@ - if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') { - $sql .= ' AND te.fk_soc = '.((int) $socid); - } - if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') { - $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)'; - } - if ($restrictiononfksoc && $socid && $this->element == 'societe') { - $sql .= ' AND te.rowid = '.((int) $socid); - } - //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
"; + 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; + //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
"; @@ -2283 +1894,2 @@ - if (!$result) { + if (!$result) + { @@ -2289,0 +1902 @@ + @@ -2291,27 +1904,14 @@ - $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { - $tmparray = explode('@', $this->ismultientitymanaged); - $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity - } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid - } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid - } - if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc"; - } - if ($fieldid == 'rowid') { - $sql .= " WHERE te.".$fieldid." > ".((int) $this->id); - } else { - $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - } - if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND sc.fk_user = ".((int) $user->id); - } - if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)'; - } - if (!empty($filter)) { - if (!preg_match('/^\s*AND/i', $filter)) { - $sql .= " AND "; // For backward compatibility - } + $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) && $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($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)) + { + if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility @@ -2320,6 +1920,2 @@ - 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 ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('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 @@ -2327 +1923 @@ - if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) { + if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { @@ -2331 +1927,2 @@ - $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))"; + $sql .= " AND ug.fk_user = te.rowid"; + $sql .= " AND ug.entity IN (".getEntity($this->element).")"; @@ -2337,14 +1934,4 @@ - if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') { - $tmparray = explode('@', $this->ismultientitymanaged); - $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')'; - } - if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') { - $sql .= ' AND te.fk_soc = '.((int) $socid); - } - if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') { - $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)'; - } - if ($restrictiononfksoc && $socid && $this->element == 'societe') { - $sql .= ' AND te.rowid = '.((int) $socid); - } - //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
"; + 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; + //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
"; @@ -2354 +1941,2 @@ - if (!$result) { + if (!$result) + { @@ -2378,6 +1966,4 @@ - while ($i < $num) { - if ($source == 'thirdparty') { - $contactAlreadySelected[$i] = $tab[$i]['socid']; - } else { - $contactAlreadySelected[$i] = $tab[$i]['id']; - } + while ($i < $num) + { + if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; + else $contactAlreadySelected[$i] = $tab[$i]['id']; @@ -2394,9 +1980,6 @@ - * @param int $notrigger Disable the trigger - * @return int Return integer <0 if KO, >0 if OK - */ - public function setProject($projectid, $notrigger = 0) - { - global $user; - $error = 0; - - if (!$this->table_element) { + * @return int <0 if KO, >0 if OK + */ + public function setProject($projectid) + { + if (!$this->table_element) + { @@ -2407,25 +1990,19 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; - if (!empty($this->fields['fk_project'])) { // Common case - if ($projectid) { - $sql .= " SET fk_project = ".((int) $projectid); - } else { - $sql .= " SET fk_project = NULL"; - } - $sql .= ' WHERE rowid = '.((int) $this->id); - } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm - if ($projectid) { - $sql .= " SET fk_project = ".((int) $projectid); - } else { - $sql .= " SET fk_project = NULL"; - } - $sql .= ' WHERE id = '.((int) $this->id); - } else { // Special case for old architecture objects - if ($projectid) { - $sql .= ' SET fk_projet = '.((int) $projectid); - } else { - $sql .= ' SET fk_projet = NULL'; - } - $sql .= " WHERE rowid = ".((int) $this->id); - } - - $this->db->begin(); + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + if (!empty($this->fields['fk_project'])) // Common case + { + 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 + { + 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 + { + if ($projectid) $sql .= ' SET fk_projet = '.$projectid; + else $sql .= ' SET fk_projet = NULL'; + $sql .= ' WHERE rowid = '.$this->id; + } @@ -2434,3 +2011,7 @@ - if ($this->db->query($sql)) { - $this->fk_project = ((int) $projectid); - } else { + if ($this->db->query($sql)) + { + $this->fk_project = $projectid; + return 1; + } + else + { @@ -2438,16 +2018,0 @@ - $error++; - } - - // Triggers - if (!$error && !$notrigger) { - // Call triggers - $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user); - if ($result < 0) { - $error++; - } //Do also here what you must do to rollback action if trigger fail - // End call triggers - } - - // Commit or rollback - if ($error) { - $this->db->rollback(); @@ -2455,3 +2019,0 @@ - } else { - $this->db->commit(); - return 1; @@ -2469,5 +2030,0 @@ - global $user; - - $error = 0; - $notrigger = 0; - @@ -2475,2 +2032,2 @@ - - if ($this->statut >= 0 || $this->element == 'societe') { + if ($this->statut >= 0 || $this->element == 'societe') + { @@ -2479,18 +2036,9 @@ - if ($this->element == 'societe') { - $fieldname = 'mode_reglement'; - } - if (get_class($this) == 'Fournisseur') { - $fieldname = 'mode_reglement_supplier'; - } - if (get_class($this) == 'Tva') { - $fieldname = 'fk_typepayment'; - } - if (get_class($this) == 'Salary') { - $fieldname = 'fk_typepayment'; - } - - $sql = "UPDATE ".$this->db->prefix().$this->table_element; - $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL'); - $sql .= ' WHERE rowid='.((int) $this->id); - - if ($this->db->query($sql)) { + if ($this->element == 'societe') $fieldname = 'mode_reglement'; + if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_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)) + { @@ -2499,16 +2047 @@ - if (get_class($this) == 'Fournisseur') { - $this->mode_reglement_supplier_id = $id; - } - // Triggers - if (!$error && !$notrigger) { - // Call triggers - if (get_class($this) == 'Commande') { - $result = $this->call_trigger('ORDER_MODIFY', $user); - } else { - $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user); - } - if ($result < 0) { - $error++; - } - // End call triggers - } + if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; @@ -2516,2 +2049,4 @@ - } else { - dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); @@ -2521 +2056,3 @@ - } else { + } + else + { @@ -2537 +2074,2 @@ - if ($this->statut >= 0 || $this->element == 'societe') { + if ($this->statut >= 0 || $this->element == 'societe') + { @@ -2540,5 +2078,6 @@ - $sql = 'UPDATE '.$this->db->prefix().$this->table_element; - $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'"; - $sql .= ' WHERE rowid='.((int) $this->id); - - if ($this->db->query($sql)) { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { @@ -2548,3 +2087 @@ - if ($rate) { - $this->setMulticurrencyRate($rate, 2); - } + if ($rate) $this->setMulticurrencyRate($rate, 2); @@ -2553,2 +2090,4 @@ - } else { - dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); @@ -2558 +2097,3 @@ - } else { + } + else + { @@ -2575 +2116,2 @@ - if ($this->statut >= 0 || $this->element == 'societe') { + if ($this->statut >= 0 || $this->element == 'societe') + { @@ -2578,5 +2120,6 @@ - $sql = 'UPDATE '.$this->db->prefix().$this->table_element; - $sql .= " SET ".$fieldname." = ".((float) $rate); - $sql .= ' WHERE rowid='.((int) $this->id); - - if ($this->db->query($sql)) { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$rate; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { @@ -2586,2 +2129,4 @@ - if (!empty($this->lines)) { - foreach ($this->lines as &$line) { + if (!empty($this->lines)) + { + foreach ($this->lines as &$line) + { @@ -2600,2 +2144,0 @@ - /** @var Propal $this */ - /** @var PropaleLigne $line */ @@ -2603,22 +2146,4 @@ - $line->id, - $line->subprice, - $line->qty, - $line->remise_percent, - $line->tva_tx, - $line->localtax1_tx, - $line->localtax2_tx, - ($line->description ? $line->description : $line->desc), - 'HT', - $line->info_bits, - $line->special_code, - $line->fk_parent_line, - $line->skip_update_total, - $line->fk_fournprice, - $line->pa_ht, - $line->label, - $line->product_type, - $line->date_start, - $line->date_end, - $line->array_options, - $line->fk_unit, - $line->multicurrency_subprice + $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, + ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, + $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, + $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice @@ -2628,2 +2152,0 @@ - /** @var Commande $this */ - /** @var OrderLine $line */ @@ -2631,22 +2154,4 @@ - $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->date_start, - $line->date_end, - $line->product_type, - $line->fk_parent_line, - $line->skip_update_total, - $line->fk_fournprice, - $line->pa_ht, - $line->label, - $line->special_code, - $line->array_options, - $line->fk_unit, - $line->multicurrency_subprice + $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->date_start, $line->date_end, + $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, + $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice @@ -2656,2 +2160,0 @@ - /** @var Facture $this */ - /** @var FactureLigne $line */ @@ -2659,23 +2162,4 @@ - $line->id, - ($line->description ? $line->description : $line->desc), - $line->subprice, - $line->qty, - $line->remise_percent, - $line->date_start, - $line->date_end, - $line->tva_tx, - $line->localtax1_tx, - $line->localtax2_tx, - 'HT', - $line->info_bits, - $line->product_type, - $line->fk_parent_line, - $line->skip_update_total, - $line->fk_fournprice, - $line->pa_ht, - $line->label, - $line->special_code, - $line->array_options, - $line->situation_percent, - $line->fk_unit, - $line->multicurrency_subprice + $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, + $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, + $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice @@ -2685,2 +2168,0 @@ - /** @var SupplierProposal $this */ - /** @var SupplierProposalLine $line */ @@ -2688,20 +2170,4 @@ - $line->id, - $line->subprice, - $line->qty, - $line->remise_percent, - $line->tva_tx, - $line->localtax1_tx, - $line->localtax2_tx, - ($line->description ? $line->description : $line->desc), - 'HT', - $line->info_bits, - $line->special_code, - $line->fk_parent_line, - $line->skip_update_total, - $line->fk_fournprice, - $line->pa_ht, - $line->label, - $line->product_type, - $line->array_options, - $line->ref_fourn, - $line->multicurrency_subprice + $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, + ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, + $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options, + $line->ref_fourn, $line->multicurrency_subprice @@ -2711,2 +2176,0 @@ - /** @var CommandeFournisseur $this */ - /** @var CommandeFournisseurLigne $line */ @@ -2714,18 +2178,3 @@ - $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->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 @@ -2735,2 +2183,0 @@ - /** @var FactureFournisseur $this */ - /** @var SupplierInvoiceLine $line */ @@ -2738,19 +2185,3 @@ - $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->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 @@ -2767,2 +2198,4 @@ - } else { - dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); @@ -2772 +2205,3 @@ - } else { + } + else + { @@ -2782,8 +2217,8 @@ - * @param int $id Id of new payment terms - * @param string $deposit_percent % of deposit if needed by payment terms - * @return int >0 if OK, <0 if KO - */ - public function setPaymentTerms($id, $deposit_percent = null) - { - dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')'); - if ($this->statut >= 0 || $this->element == 'societe') { + * @param int $id Id of new payment terms + * @return int >0 if OK, <0 if KO + */ + public function setPaymentTerms($id) + { + dol_syslog(get_class($this).'::setPaymentTerms('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { @@ -2792,23 +2227,9 @@ - if ($this->element == 'societe') { - $fieldname = 'cond_reglement'; - } - if (get_class($this) == 'Fournisseur') { - $fieldname = 'cond_reglement_supplier'; - } - - if (empty($deposit_percent) || $deposit_percent < 0) { - $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id); - } - - if ($deposit_percent > 100) { - $deposit_percent = 100; - } - - $sql = 'UPDATE '.$this->db->prefix().$this->table_element; - $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL'); - if (in_array($this->table_element, array('propal', 'commande', 'societe'))) { - $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'"); - } - $sql .= ' WHERE rowid='.((int) $this->id); - - if ($this->db->query($sql)) { + if ($this->element == 'societe') $fieldname = 'cond_reglement'; + if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_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)) + { @@ -2817,3 +2238 @@ - if (get_class($this) == 'Fournisseur') { - $this->cond_reglement_supplier_id = $id; - } + if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; @@ -2821 +2239,0 @@ - $this->deposit_percent = $deposit_percent; @@ -2823,2 +2241,4 @@ - } else { - dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error()); + } + else + { + dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); @@ -2828 +2248,3 @@ - } else { + } + else + { @@ -2835,40 +2256,0 @@ - /** - * Change the transport mode methods - * - * @param int $id Id of transport mode - * @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 '.$this->db->prefix().$this->table_element; - $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL'); - $sql .= ' WHERE rowid='.((int) $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; - } - } @@ -2884,21 +2266,27 @@ - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') { - $fieldname = 'retained_warranty_fk_cond_reglement'; - - $sql = 'UPDATE '.$this->db->prefix().$this->table_element; - $sql .= " SET ".$fieldname." = ".((int) $id); - $sql .= ' WHERE rowid='.((int) $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; + } @@ -2912 +2300 @@ - * @return int Return integer <0 si ko, >0 si ok + * @return int <0 si ko, >0 si ok @@ -2917,8 +2305,7 @@ - if ($this->element == 'delivery' || $this->element == 'shipping') { - $fieldname = 'fk_address'; - } - - $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id); - $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0"; - - if ($this->db->query($sql)) { + if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + + if ($this->db->query($sql)) + { @@ -2927 +2314,3 @@ - } else { + } + else + { @@ -2929 +2318 @@ - dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error); + dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); @@ -2948,3 +2337 @@ - if (empty($userused)) { - $userused = $user; - } + if (empty($userused)) $userused = $user; @@ -2961,3 +2348 @@ - if ($shipping_method_id < 0) { - $shipping_method_id = 'NULL'; - } + if ($shipping_method_id < 0) $shipping_method_id = 'NULL'; @@ -2966,3 +2351,3 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; - $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id); - $sql .= " WHERE rowid=".((int) $this->id); + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_shipping_method = ".$shipping_method_id; + $sql .= " WHERE rowid=".$this->id; @@ -2975 +2360,2 @@ - if (!$notrigger) { + if (!$notrigger) + { @@ -2979,3 +2365 @@ - if ($result < 0) { - $error++; - } + if ($result < 0) $error++; @@ -2985 +2369,2 @@ - if ($error) { + if ($error) + { @@ -2989 +2374 @@ - $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id; + $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id; @@ -3008,3 +2393 @@ - if ($warehouse_id < 0) { - $warehouse_id = 'NULL'; - } + if ($warehouse_id < 0) $warehouse_id = 'NULL'; @@ -3013,3 +2396,3 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; - $sql .= " SET fk_warehouse = ".((int) $warehouse_id); - $sql .= " WHERE rowid=".((int) $this->id); + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_warehouse = ".$warehouse_id; + $sql .= " WHERE rowid=".$this->id; @@ -3018 +2401 @@ - $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id; + $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id; @@ -3033 +2416 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -3037 +2420,2 @@ - if (!$this->table_element) { + if (!$this->table_element) + { @@ -3044 +2428 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; @@ -3046 +2430,3 @@ - $sql .= " WHERE rowid = ".((int) $this->id); + $sql .= " WHERE rowid = ".$this->id; + // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; + // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; @@ -3050,2 +2436,3 @@ - if ($resql) { - $this->model_pdf = $modelpdf; + if ($resql) + { + $this->modelpdf = $modelpdf; @@ -3053 +2440,3 @@ - } else { + } + else + { @@ -3072,3 +2461 @@ - if (empty($userused)) { - $userused = $user; - } + if (empty($userused)) $userused = $user; @@ -3084,3 +2471 @@ - if ($fk_account < 0) { - $fk_account = 'NULL'; - } + if ($fk_account < 0) $fk_account = 'NULL'; @@ -3089,3 +2474,3 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; - $sql .= " SET fk_account = ".((int) $fk_account); - $sql .= " WHERE rowid=".((int) $this->id); + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_account = ".$fk_account; + $sql .= " WHERE rowid=".$this->id; @@ -3094 +2479,2 @@ - if (!$resql) { + if (!$resql) + { @@ -3098,2 +2484,5 @@ - } else { - if (!$notrigger) { + } + else + { + if (!$notrigger) + { @@ -3101,10 +2490,3 @@ - $this->context['bankaccountupdate'] = 1; - $triggerName = strtoupper(get_class($this)).'_MODIFY'; - // Special cases - if ($triggerName == 'FACTUREREC_MODIFY') { - $triggerName = 'BILLREC_MODIFY'; - } - $result = $this->call_trigger($triggerName, $userused); - if ($result < 0) { - $error++; - } + $this->context = array('bankaccountupdate'=>1); + $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused); + if ($result < 0) $error++; @@ -3114 +2496,2 @@ - if ($error) { + if ($error) + { @@ -3117,2 +2500,4 @@ - } else { - $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account; + } + else + { + $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account; @@ -3127 +2512 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3135 +2520 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -3139,2 +2524,3 @@ - // phpcs:enable - if (!$this->table_element_line) { + // phpcs:enable + if (!$this->table_element_line) + { @@ -3144 +2530,2 @@ - if (!$this->fk_element) { + if (!$this->fk_element) + { @@ -3149,5 +2535,0 @@ - $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' - if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - @@ -3156,8 +2538,4 @@ - $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - if (!$renum) { - $sql .= " AND " . $fieldposition . " = 0"; - } - if ($renum) { - $sql .= " AND " . $fieldposition . " <> 0"; - } + $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.'='.$this->id; + if (!$renum) $sql .= ' AND rang = 0'; + if ($renum) $sql .= ' AND rang <> 0'; @@ -3167 +2545,2 @@ - if ($resql) { + if ($resql) + { @@ -3170,5 +2549,6 @@ - } 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. + } + 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. @@ -3178,6 +2558,4 @@ - $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - if ($fk_parent_line) { - $sql .= ' AND fk_parent_line IS NULL'; - } - $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder; + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + if ($fk_parent_line) $sql .= ' AND fk_parent_line IS NULL'; + $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder; @@ -3187 +2565,2 @@ - if ($resql) { + if ($resql) + { @@ -3190 +2569,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -3194,2 +2574,4 @@ - if (!empty($childrens)) { - foreach ($childrens as $child) { + if (!empty($childrens)) + { + foreach ($childrens as $child) + { @@ -3203,2 +2585,4 @@ - if (!empty($rows)) { - foreach ($rows as $key => $row) { + if (!empty($rows)) + { + foreach ($rows as $key => $row) + { @@ -3208 +2592,3 @@ - } else { + } + else + { @@ -3218,11 +2604,5 @@ - * @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) - { - $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' - if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - + * @param int $id Id of parent line + * @return array Array with list of children lines id + */ + public function getChildrenOfLine($id) + { @@ -3231,6 +2611,6 @@ - $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= ' AND fk_parent_line = '.((int) $id); - $sql .= " ORDER BY " . $fieldposition . " ASC"; - - dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG); + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND fk_parent_line = '.$id; + $sql .= ' ORDER BY rang ASC'; + + dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG); @@ -3238,10 +2618,12 @@ - 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)); - } - } - } - } + if ($resql) + { + $i = 0; + $num = $this->db->num_rows($resql); + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + $rows[$i] = $row[0]; + $i++; + } + } + @@ -3251 +2633 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3261 +2643 @@ - // phpcs:enable + // phpcs:enable @@ -3271 +2653 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3281 +2663 @@ - // phpcs:enable + // phpcs:enable @@ -3296,46 +2677,0 @@ - * - * @param int $rowid Id of line - * @param int $rang Position - * @return int Return integer <0 if KO, >0 if OK - */ - public function updateRangOfLine($rowid, $rang) - { - global $hookmanager; - $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' - if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - - $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang); - $sql .= ' WHERE rowid = '.((int) $rowid); - - dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG); - if (!$this->db->query($sql)) { - dol_print_error($this->db); - return -1; - } else { - $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition); - $action=''; - $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action); - return 1; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update position of line with ajax (rang) - * - * @param array $rows Array of rows - * @return void - */ - public function line_ajaxorder($rows) - { - // phpcs:enable - $num = count($rows); - for ($i = 0; $i < $num; $i++) { - $this->updateRangOfLine($rows[$i], ($i + 1)); - } - } - - /** - * Update position of line up (rang) @@ -3346,0 +2683,39 @@ + public function updateRangOfLine($rowid, $rang) + { + $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' + if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; + $sql .= ' WHERE rowid = '.$rowid; + + dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG); + if (!$this->db->query($sql)) + { + dol_print_error($this->db); + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update position of line with ajax (rang) + * + * @param array $rows Array of rows + * @return void + */ + public function line_ajaxorder($rows) + { + // phpcs:enable + $num = count($rows); + for ($i = 0; $i < $num; $i++) + { + $this->updateRangOfLine($rows[$i], ($i + 1)); + } + } + + /** + * Update position of line up (rang) + * + * @param int $rowid Id of line + * @param int $rang Position + * @return void + */ @@ -3349 +2724,2 @@ - if ($rang > 1) { + if ($rang > 1) + { @@ -3351,11 +2727,11 @@ - if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - - $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang); - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1)); - if ($this->db->query($sql)) { - $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1)); - $sql .= ' WHERE rowid = '.((int) $rowid); - if (!$this->db->query($sql)) { + if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND rang = '.($rang - 1); + if ($this->db->query($sql)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang - 1); + $sql .= ' WHERE rowid = '.$rowid; + if (!$this->db->query($sql)) + { @@ -3364 +2740,3 @@ - } else { + } + else + { @@ -3380 +2758,2 @@ - if ($rang < $max) { + if ($rang < $max) + { @@ -3382,11 +2761,11 @@ - if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - - $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang); - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1)); - if ($this->db->query($sql)) { - $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1)); - $sql .= ' WHERE rowid = '.((int) $rowid); - if (!$this->db->query($sql)) { + if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND rang = '.($rang + 1); + if ($this->db->query($sql)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang + 1); + $sql .= ' WHERE rowid = '.$rowid; + if (!$this->db->query($sql)) + { @@ -3395 +2774,3 @@ - } else { + } + else + { @@ -3409,7 +2790,2 @@ - $fieldposition = 'rang'; - if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - - $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE rowid = ".((int) $rowid); + $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE rowid ='.$rowid; @@ -3419 +2795,2 @@ - if ($resql) { + if ($resql) + { @@ -3423,2 +2799,0 @@ - - return 0; @@ -3435,8 +2810,3 @@ - $fieldposition = 'rang'; - if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { - $fieldposition = 'position'; - } - - $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= " AND " . $fieldposition . " = ".((int) $rang); + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND rang = '.$rang; @@ -3444 +2814,2 @@ - if ($resql) { + if ($resql) + { @@ -3448,5 +2819,3 @@ - - return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3461,5 +2830,3 @@ - // phpcs:enable - $positionfield = 'rang'; - if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) { - $positionfield = 'position'; - } + // phpcs:enable + $positionfield = 'rang'; + if ($this->table_element == 'bom') $positionfield = 'position'; @@ -3468,4 +2835,5 @@ - if ($fk_parent_line) { - $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= " AND fk_parent_line = ".((int) $fk_parent_line); + if ($fk_parent_line) + { + $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND fk_parent_line = '.$fk_parent_line; @@ -3475 +2843,2 @@ - if ($resql) { + if ($resql) + { @@ -3477 +2846,2 @@ - if (!empty($row[0])) { + if (!empty($row[0])) + { @@ -3479 +2849,3 @@ - } else { + } + else + { @@ -3483,4 +2855,6 @@ - } else { - // If not, search the last rang of element - $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); + } + // If not, search the last rang of element + else + { + $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; @@ -3490 +2864,2 @@ - if ($resql) { + if ($resql) + { @@ -3495,5 +2870,3 @@ - - return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3504 +2877 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -3508,2 +2881,3 @@ - // phpcs:enable - if (!$this->table_element) { + // phpcs:enable + if (!$this->table_element) + { @@ -3514 +2888 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; @@ -3516 +2890 @@ - $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id); + $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id; @@ -3519 +2893,2 @@ - if ($this->db->query($sql)) { + if ($this->db->query($sql)) + { @@ -3522 +2897,3 @@ - } else { + } + else + { @@ -3528 +2905 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3534,6 +2911,5 @@ - * @param int $notrigger 1=Does not execute triggers, 0=execute triggers - * @return int Return integer <0 if KO, >0 if OK - */ - public function update_note($note, $suffix = '', $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function update_note($note, $suffix = '') + { + // phpcs:enable @@ -3542 +2918,2 @@ - if (!$this->table_element) { + if (!$this->table_element) + { @@ -3547 +2924,2 @@ - if (!in_array($suffix, array('', '_public', '_private'))) { + if (!in_array($suffix, array('', '_public', '_private'))) + { @@ -3552,3 +2929,0 @@ - - $newsuffix = $suffix; - @@ -3556,14 +2931,7 @@ - if ($this->table_element == 'product' && $newsuffix == '_private') { - $newsuffix = ''; - } - if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) { - $fieldusermod = "fk_user_mod"; - } elseif ($this->table_element == 'ecm_files') { - $fieldusermod = "fk_user_m"; - } else { - $fieldusermod = "fk_user_modif"; - } - $sql = "UPDATE ".$this->db->prefix().$this->table_element; - $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL"); - $sql .= ", ".$fieldusermod." = ".((int) $user->id); - $sql .= " WHERE rowid = ".((int) $this->id); + //var_dump($this->table_element);exit; + if ($this->table_element == 'product') $suffix = ''; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $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; @@ -3572,6 +2940,6 @@ - if ($this->db->query($sql)) { - if ($suffix == '_public') { - $this->note_public = $note; - } elseif ($suffix == '_private') { - $this->note_private = $note; - } else { + if ($this->db->query($sql)) + { + if ($suffix == '_public') $this->note_public = $note; + elseif ($suffix == '_private') $this->note_private = $note; + else + { @@ -3581,28 +2948,0 @@ - if (empty($notrigger)) { - switch ($this->element) { - case 'societe': - $trigger_name = 'COMPANY_MODIFY'; - break; - case 'commande': - $trigger_name = 'ORDER_MODIFY'; - break; - case 'facture': - $trigger_name = 'BILL_MODIFY'; - break; - case 'invoice_supplier': - $trigger_name = 'BILL_SUPPLIER_MODIFY'; - break; - case 'facturerec': - $trigger_name = 'BILLREC_MODIFIY'; - break; - case 'expensereport': - $trigger_name = 'EXPENSE_REPORT_MODIFY'; - break; - default: - $trigger_name = strtoupper($this->element) . '_MODIFY'; - } - $ret = $this->call_trigger($trigger_name, $user); - if ($ret < 0) { - return -1; - } - } @@ -3610 +2950,3 @@ - } else { + } + else + { @@ -3616 +2958 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3621 +2963 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -3627 +2969 @@ - // phpcs:enable + // phpcs:enable @@ -3631 +2973 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3637,4 +2979,4 @@ - * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode Total of rounding, '1'=Force mode Rounding of total - * @param int $nodatabaseupdate 1=Do not update database total fields of the main object. Update only properties in memory. Can be used to save SQL when this method is called several times, so we can do it only once at end. - * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object (used to analyze lines to check corrupted data). - * @return int Return integer <0 if KO, >0 if OK + * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total + * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object. + * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object. + * @return int <0 if KO, >0 if OK @@ -3644 +2986 @@ - // phpcs:enable + // phpcs:enable @@ -3647,7 +2989,7 @@ - $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 @@ -3657 +2999 @@ - if ($this->element == 'propal') { + if ($this->element == 'propal') @@ -3659 +3001 @@ - } elseif ($this->element == 'commande' || $this->element == 'order') { + elseif ($this->element == 'commande' || $this->element == 'order') @@ -3661 +3003 @@ - } elseif ($this->element == 'facture' || $this->element == 'invoice') { + elseif ($this->element == 'facture' || $this->element == 'invoice') @@ -3663 +3005 @@ - } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') { + elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') @@ -3665 +3007 @@ - } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') { + elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') @@ -3667 +3009 @@ - } elseif ($this->element == 'supplier_proposal') { + elseif ($this->element == 'supplier_proposal') @@ -3669 +3010,0 @@ - } @@ -3672,2 +3013,2 @@ - if (getDolGlobalString($MODULE)) { - $modsactivated = explode(',', getDolGlobalString($MODULE)); + if (!empty($conf->global->$MODULE)) { + $modsactivated = explode(',', $conf->global->$MODULE); @@ -3675 +3016 @@ - if (isModEnabled($mod)) { + if ($conf->$mod->enabled) @@ -3677 +3017,0 @@ - } @@ -3683,0 +3024,2 @@ + if ($roundingadjust == '-1') $roundingadjust = 'auto'; // For backward compatibility + @@ -3685,5 +3027,2 @@ - if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) { - $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND'); - } elseif ($forcedroundingmode == 'auto') { - $forcedroundingmode = '0'; - } + if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; + elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0'; @@ -3695 +3034 @@ - // Define constants to find lines to sum (field name int the table_element_line not into table_element) + // Define constants to find lines to sum @@ -3700 +3039,2 @@ - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + { @@ -3704,4 +3044,2 @@ - if ($this->element == 'invoice_supplier_rec') { - $fieldup = 'pu_ht'; - } - if ($this->element == 'expensereport') { + if ($this->element == 'expensereport') + { @@ -3711 +3049 @@ - $sql = "SELECT rowid, qty, ".$fieldup." as up, remise_percent, total_ht, ".$fieldtva." as total_tva, total_ttc, ".$fieldlocaltax1." as total_localtax1, ".$fieldlocaltax2." as total_localtax2,"; + $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; @@ -3713,3 +3051 @@ - if ($this->table_element_line == 'facturedet') { - $sql .= ', situation_percent'; - } + if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent'; @@ -3717,3 +3053,4 @@ - $sql .= " FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - if ($exclspec) { + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + if ($exclspec) + { @@ -3721,6 +3058,2 @@ - if ($this->table_element_line == 'contratdet') { - $product_field = ''; // contratdet table has no product_type field - } - if ($product_field) { - $sql .= " AND ".$product_field." <> 9"; - } + if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field + if ($product_field) $sql .= ' AND '.$product_field.' <> 9'; @@ -3731 +3063,0 @@ - @@ -3733 +3065,2 @@ - if ($resql) { + if ($resql) + { @@ -3746,2 +3078,0 @@ - $this->db->begin(); - @@ -3750 +3081,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -3757 +3089,2 @@ - if (empty($reshook) && $forcedroundingmode == '0') { // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' + if (empty($reshook) && $forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' + { @@ -3762 +3095 @@ - $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT. + $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT. @@ -3764 +3097 @@ - //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc); + //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc); @@ -3767,4 +3100,4 @@ - if ($diff_on_current_total) { - // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2 - $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid); - dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=".$obj->total_ht." vat=".$obj->total_tva." tax1=".$obj->total_localtax1." tax2=".$obj->total_localtax2." ttc=".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING); + if ($diff_when_using_price_ht && $diff_on_current_total) + { + $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; + dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING); @@ -3772,14 +3105 @@ - if (!$resqlfix) { - dol_print_error($this->db, 'Failed to update line'); - } - $obj->total_tva = $tmpcal[1]; - $obj->total_ttc = $tmpcal[2]; - } elseif ($diff_when_using_price_ht && $roundingadjust == '0') { - // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and - // we ask to force the use of rounding on line (like done on calculation) so we force update of line - $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid); - dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix = $this->db->query($sqlfix); - if (!$resqlfix) { - dol_print_error($this->db, 'Failed to update line'); - } + if (!$resqlfix) dol_print_error($this->db, 'Failed to update line'); @@ -3800,9 +3120,3 @@ - if (!isset($total_ht_by_vats[$obj->vatrate])) { - $total_ht_by_vats[$obj->vatrate] = 0; - } - if (!isset($total_tva_by_vats[$obj->vatrate])) { - $total_tva_by_vats[$obj->vatrate] = 0; - } - if (!isset($total_ttc_by_vats[$obj->vatrate])) { - $total_ttc_by_vats[$obj->vatrate] = 0; - } + if (!isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate] = 0; + if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0; + if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0; @@ -3813 +3127,2 @@ - if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on foreign currency + if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency + { @@ -3817,4 +3132,4 @@ - if ($diff) { - if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) { - // If error is more than 10 times the accurancy of rounding. This should not happen. - $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your lines may be corrupted. Try to edit each line manually to fix this before restarting.'; + if ($diff) + { + if (abs($diff) > 0.1) { + $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.'; @@ -3822,3 +3137,2 @@ - $this->error = $errmsg; - $error++; - break; + dol_print_error('', $errmsg); + exit; @@ -3826 +3140 @@ - $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid); + $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; @@ -3828,11 +3142,6 @@ - - $resqlfix = $this->db->query($sqlfix); - - if (!$resqlfix) { - dol_print_error($this->db, 'Failed to update line'); - } - - $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1); - $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1); - $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1); - $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1); + $resqlfix = $this->db->query($sqlfix); + if (!$resqlfix) dol_print_error($this->db, 'Failed to update line'); + $this->total_tva -= $diff; + $this->total_ttc -= $diff; + $total_tva_by_vats[$obj->vatrate] -= $diff; + $total_ttc_by_vats[$obj->vatrate] -= $diff; @@ -3850,24 +3159,15 @@ - if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - if ($this->type != Facture::TYPE_CREDIT_NOTE) { // @phpstan-ignore-line - $prev_sits = $this->get_prev_sits(); - - foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch. - $this->total_ht -= $sit->total_ht; - $this->total_tva -= $sit->total_tva; - $this->total_localtax1 -= $sit->total_localtax1; - $this->total_localtax2 -= $sit->total_localtax2; - $this->total_ttc -= $sit->total_ttc; - $this->multicurrency_total_ht -= $sit->multicurrency_total_ht; - $this->multicurrency_total_tva -= $sit->multicurrency_total_tva; - $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc; - } - } - } - - // Clean total - $this->total_ht = (float) price2num($this->total_ht); - $this->total_tva = (float) price2num($this->total_tva); - $this->total_localtax1 = (float) price2num($this->total_localtax1); - $this->total_localtax2 = (float) price2num($this->total_localtax2); - $this->total_ttc = (float) price2num($this->total_ttc); + 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(); + + foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch. + $this->total_ht -= $sit->total_ht; + $this->total_tva -= $sit->total_tva; + $this->total_localtax1 -= $sit->total_localtax1; + $this->total_localtax2 -= $sit->total_localtax2; + $this->total_ttc -= $sit->total_ttc; + $this->multicurrency_total_ht -= $sit->multicurrency_total_ht; + $this->multicurrency_total_tva -= $sit->multicurrency_total_tva; + $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc; + } + } @@ -3877 +3177 @@ - // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object + // Now update global field total_ht, total_ttc and tva @@ -3884,15 +3184,19 @@ - if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) { - $fieldtva = 'total_tva'; - } - - if (!$error && empty($nodatabaseupdate)) { - $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET'; - $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).","; - $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).","; - $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).","; - $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).","; - $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1)); - $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1)); - $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1)); - $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1)); - $sql .= " WHERE rowid = ".((int) $this->id); + if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht = 'total'; + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva'; + if ($this->element == 'propal') $fieldttc = 'total'; + if ($this->element == 'expensereport') $fieldtva = 'total_tva'; + if ($this->element == 'supplier_proposal') $fieldttc = 'total'; + + if (empty($nodatabaseupdate)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; + $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; + $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; + $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',"; + $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',"; + $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'"; + $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'"; + $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'"; + $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; + $sql .= ' WHERE rowid = '.$this->id; + @@ -3902,2 +3206,2 @@ - - if (!$resql) { + if (!$resql) + { @@ -3910,2 +3214,2 @@ - if (!$error) { - $this->db->commit(); + if (!$error) + { @@ -3913,2 +3217,3 @@ - } else { - $this->db->rollback(); + } + else + { @@ -3917 +3222,3 @@ - } else { + } + else + { @@ -3925 +3232 @@ - * Add an object link into llx_element_element. + * Add objects linked in llx_element_element. @@ -3929,3 +3236 @@ - * @param User $f_user User that create - * @param int $notrigger 1=Does not execute triggers, 0=execute triggers - * @return int Return integer <=0 if KO, >0 if OK + * @return int <=0 if KO, >0 if OK @@ -3934 +3239 @@ - public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0) + public function add_object_linked($origin = null, $origin_id = null) @@ -3937 +3241,0 @@ - global $user, $hookmanager, $action; @@ -3940 +3243,0 @@ - $f_user = isset($f_user) ? $f_user : $user; @@ -3943,28 +3246,4 @@ - if ($origin == 'order') { - $origin = 'commande'; - } - if ($origin == 'invoice') { - $origin = 'facture'; - } - if ($origin == 'invoice_template') { - $origin = 'facturerec'; - } - if ($origin == 'supplierorder') { - $origin = 'order_supplier'; - } - - // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element. - // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target. - $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset'); - // Add module part to target type if object has $module property and isn't in core modules. - $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element; - - $parameters = array('targettype'=>$targettype); - // Hook for explicitly set the targettype if it must be differtent than $this->element - $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - if (!empty($hookmanager->resArray['targettype'])) { - $targettype = $hookmanager->resArray['targettype']; - } - } - + if ($origin == 'order') $origin = 'commande'; + if ($origin == 'invoice') $origin = 'facture'; + if ($origin == 'invoice_template') $origin = 'facturerec'; + if ($origin == 'supplierorder') $origin = 'order_supplier'; @@ -3972,3 +3251,2 @@ - $error = 0; - - $sql = "INSERT INTO " . $this->db->prefix() . "element_element ("; + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; @@ -3980,4 +3258,4 @@ - $sql .= ((int) $origin_id); - $sql .= ", '" . $this->db->escape($origin) . "'"; - $sql .= ", " . ((int) $this->id); - $sql .= ", '" . $this->db->escape($targettype) . "'"; + $sql .= $origin_id; + $sql .= ", '".$this->db->escape($origin)."'"; + $sql .= ", ".$this->id; + $sql .= ", '".$this->db->escape($this->element)."'"; @@ -3986,18 +3264,3 @@ - dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG); - if ($this->db->query($sql)) { - if (!$notrigger) { - // Call trigger - $this->context['link_origin'] = $origin; - $this->context['link_origin_id'] = $origin_id; - $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user); - if ($result < 0) { - $error++; - } - // End call triggers - } - } else { - $this->error = $this->db->lasterror(); - $error++; - } - - if (!$error) { + dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); + if ($this->db->query($sql)) + { @@ -4006 +3269,4 @@ - } else { + } + else + { + $this->error = $this->db->lasterror(); @@ -4014,2 +3280,2 @@ - * this->linkedObjectsIds array + - * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type + * this->linkedObjectsIds array and + * this->linkedObjects array if $loadalsoobjects = 1 @@ -4018,14 +3284,14 @@ - * - source id+type -> will get list of targets linked to source - * - target id+type -> will get list of sources linked to target - * - source id+type + target type -> will get list of targets of the type linked to source - * - target id+type + source type -> will get list of sources of the type linked to target - * - * @param int $sourceid Object source id (if not defined, $this->id) - * @param string $sourcetype Object source type (if not defined, $this->element) - * @param int $targetid Object target id (if not defined, $this->id) - * @param string $targettype Object target type (if not defined, $this->element) - * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided - * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type. - * @param string $orderby SQL 'ORDER BY' clause - * @param int|string $loadalsoobjects Load also the array $this->linkedObjects. Use 0 to not load (increase performances), Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object. - * @return int Return integer <0 if KO, >0 if OK + * - source id+type -> will get target list linked to source + * - target id+type -> will get source list linked to target + * - source id+type + target type -> will get target list of the type + * - target id+type + target source -> will get source list of the type + * + * @param int $sourceid Object source id (if not defined, id of object) + * @param string $sourcetype Object source type (if not defined, element name of object) + * @param int $targetid Object target id (if not defined, id of object) + * @param string $targettype Object target type (if not defined, elemennt name of object) + * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided + * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type. + * @param string $orderby SQL 'ORDER BY' clause + * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances) + * @return int <0 if KO, >0 if OK @@ -4036,8 +3302 @@ - global $conf, $hookmanager, $action; - - // Important for pdf generation time reduction - // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter - // If you need to force the reload, you can call clearObjectLinkedCache() before calling fetchObjectLinked() - if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) { - return 1; - } + global $conf; @@ -4053,19 +3312,2 @@ - $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid); - // Hook for explicitly set the targettype if it must be differtent than $this->element - $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - if (!empty($hookmanager->resArray['sourcetype'])) { - $sourcetype = $hookmanager->resArray['sourcetype']; - } - if (!empty($hookmanager->resArray['sourceid'])) { - $sourceid = $hookmanager->resArray['sourceid']; - } - if (!empty($hookmanager->resArray['targettype'])) { - $targettype = $hookmanager->resArray['targettype']; - } - if (!empty($hookmanager->resArray['targetid'])) { - $targetid = $hookmanager->resArray['targetid']; - } - } - - if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) { + if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) + { @@ -4073,5 +3315,4 @@ - if (!empty($targettype)) { - $withtargettype = true; - } - } - if (!empty($targetid) && !empty($targettype) && empty($sourceid)) { + if (!empty($targettype)) $withtargettype = true; + } + if (!empty($targetid) && !empty($targettype) && empty($sourceid)) + { @@ -4079,3 +3320 @@ - if (!empty($sourcetype)) { - $withsourcetype = true; - } + if (!empty($sourcetype)) $withsourcetype = true; @@ -4096,2 +3335,2 @@ - $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype"; - $sql .= " FROM ".$this->db->prefix()."element_element"; + $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element'; @@ -4099,20 +3338,19 @@ - if ($justsource || $justtarget) { - if ($justsource) { - $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'"; - if ($withtargettype) { - $sql .= " AND targettype = '".$this->db->escape($targettype)."'"; - } - } elseif ($justtarget) { - $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'"; - if ($withsourcetype) { - $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'"; - } - } - } else { - $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')"; - $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')"; - if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') { - $this->linkedObjectsFullLoaded[$this->id] = true; - } - } - $sql .= " ORDER BY ".$orderby; + if ($justsource || $justtarget) + { + if ($justsource) + { + $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; @@ -4122 +3360,2 @@ - if ($resql) { + if ($resql) + { @@ -4125 +3364,2 @@ - while ($i < $num) { + while ($i < $num) + { @@ -4127,2 +3367,4 @@ - if ($justsource || $justtarget) { - if ($justsource) { + if ($justsource || $justtarget) + { + if ($justsource) + { @@ -4130 +3372,3 @@ - } elseif ($justtarget) { + } + elseif ($justtarget) + { @@ -4133,2 +3377,5 @@ - } else { - if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) { + } + else + { + if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) + { @@ -4137 +3384,2 @@ - if ($obj->fk_target == $targetid && $obj->targettype == $targettype) { + if ($obj->fk_target == $targetid && $obj->targettype == $targettype) + { @@ -4144 +3392,2 @@ - if (!empty($this->linkedObjectsIds)) { + if (!empty($this->linkedObjectsIds)) + { @@ -4146 +3395,2 @@ - foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) + foreach ($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) + { @@ -4149 +3398,0 @@ - $regs = array(); @@ -4151 +3400,2 @@ - && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) { + && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) + { @@ -4160,4 +3410,5 @@ - } elseif ($objecttype == 'facturerec') { - $classpath = 'compta/facture/class'; - $module = 'facture'; - } elseif ($objecttype == 'propal') { + } + elseif ($objecttype == 'facturerec') { + $classpath = 'compta/facture/class'; $module = 'facture'; + } + elseif ($objecttype == 'propal') { @@ -4165 +3416,2 @@ - } elseif ($objecttype == 'supplier_proposal') { + } + elseif ($objecttype == 'supplier_proposal') { @@ -4167,21 +3419,20 @@ - } elseif ($objecttype == 'shipping') { - $classpath = 'expedition/class'; - $subelement = 'expedition'; - $module = 'expedition'; - } elseif ($objecttype == 'delivery') { - $classpath = 'delivery/class'; - $subelement = 'delivery'; - $module = 'delivery_note'; - } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { - $classpath = 'fourn/class'; - $module = 'fournisseur'; - } elseif ($objecttype == 'fichinter') { - $classpath = 'fichinter/class'; - $subelement = 'fichinter'; - $module = 'ficheinter'; - } elseif ($objecttype == 'subscription') { - $classpath = 'adherents/class'; - $module = 'adherent'; - } elseif ($objecttype == 'contact') { - $module = 'societe'; - } + } + elseif ($objecttype == 'shipping') { + $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; + } + 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') { + $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; + } + elseif ($objecttype == 'subscription') { + $classpath = 'adherents/class'; $module = 'adherent'; + } + elseif ($objecttype == 'contact') { + $module = 'societe'; + } + @@ -4189,2 +3440 @@ - $classfile = strtolower($subelement); - $classname = ucfirst($subelement); + $classfile = strtolower($subelement); $classname = ucfirst($subelement); @@ -4193,41 +3443,26 @@ - $classfile = 'commande'; - $classname = 'Commande'; - } elseif ($objecttype == 'invoice_supplier') { - $classfile = 'fournisseur.facture'; - $classname = 'FactureFournisseur'; - } elseif ($objecttype == 'order_supplier') { - $classfile = 'fournisseur.commande'; - $classname = 'CommandeFournisseur'; - } elseif ($objecttype == 'supplier_proposal') { - $classfile = 'supplier_proposal'; - $classname = 'SupplierProposal'; - } elseif ($objecttype == 'facturerec') { - $classfile = 'facture-rec'; - $classname = 'FactureRec'; - } elseif ($objecttype == 'subscription') { - $classfile = 'subscription'; - $classname = 'Subscription'; - } elseif ($objecttype == 'project' || $objecttype == 'projet') { - $classpath = 'projet/class'; - $classfile = 'project'; - $classname = 'Project'; - } elseif ($objecttype == 'conferenceorboothattendee') { - $classpath = 'eventorganization/class'; - $classfile = 'conferenceorboothattendee'; - $classname = 'ConferenceOrBoothAttendee'; - $module = 'eventorganization'; - } elseif ($objecttype == 'conferenceorbooth') { - $classpath = 'eventorganization/class'; - $classfile = 'conferenceorbooth'; - $classname = 'ConferenceOrBooth'; - $module = 'eventorganization'; - } elseif ($objecttype == 'mo') { - $classpath = 'mrp/class'; - $classfile = 'mo'; - $classname = 'Mo'; - $module = 'mrp'; - } - - // Here $module, $classfile and $classname are set, we can use them. - if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) { - if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) { + $classfile = 'commande'; $classname = 'Commande'; + } + elseif ($objecttype == 'invoice_supplier') { + $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; + } + elseif ($objecttype == 'order_supplier') { + $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; + } + elseif ($objecttype == 'supplier_proposal') { + $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; + } + elseif ($objecttype == 'facturerec') { + $classfile = 'facture-rec'; $classname = 'FactureRec'; + } + elseif ($objecttype == 'subscription') { + $classfile = 'subscription'; $classname = 'Subscription'; + } + elseif ($objecttype == 'project' || $objecttype == 'projet') { + $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project'; + } + + // Here $module, $classfile and $classname are set + if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) + { + if ($loadalsoobjects) + { @@ -4236,2 +3471,4 @@ - if (class_exists($classname)) { - foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element + if (class_exists($classname)) + { + foreach ($objectids as $i => $objectid) // $i is rowid into llx_element_element + { @@ -4240 +3477,2 @@ - if ($ret >= 0) { + if ($ret >= 0) + { @@ -4246 +3484,3 @@ - } else { + } + else + { @@ -4252 +3492,3 @@ - } else { + } + else + { @@ -4256,15 +3497,0 @@ - } - - /** - * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links. - * - * @return int Return integer <0 if KO, >0 if OK - * @see fetchObjectLinked() - */ - public function clearObjectLinkedCache() - { - if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) { - unset($this->linkedObjectsFullLoaded[$this->id]); - } - - return 1; @@ -4280,2 +3506,0 @@ - * @param User $f_user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers @@ -4285,3 +3510,2 @@ - public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0) - { - global $user; + public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '') + { @@ -4290,39 +3514,27 @@ - $f_user = isset($f_user) ? $f_user : $user; - - if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) { - $updatesource = true; - } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) { - $updatetarget = true; - } - - $this->db->begin(); - $error = 0; - - $sql = "UPDATE " . $this->db->prefix() . "element_element SET "; - if ($updatesource) { - $sql .= "fk_source = " . ((int) $sourceid); - $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'"; - $sql .= " WHERE fk_target = " . ((int) $this->id); - $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'"; - } elseif ($updatetarget) { - $sql .= "fk_target = " . ((int) $targetid); - $sql .= ", targettype = '" . $this->db->escape($targettype) . "'"; - $sql .= " WHERE fk_source = " . ((int) $this->id); - $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'"; - } - - dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) { - if (!$notrigger) { - // Call trigger - $this->context['link_source_id'] = $sourceid; - $this->context['link_source_type'] = $sourcetype; - $this->context['link_target_id'] = $targetid; - $this->context['link_target_type'] = $targettype; - $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user); - if ($result < 0) { - $error++; - } - // End call triggers - } - } else { + + if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true; + elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true; + + $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; + if ($updatesource) + { + $sql .= "fk_source = ".$sourceid; + $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'"; + $sql .= " WHERE fk_target = ".$this->id; + $sql .= " AND targettype = '".$this->db->escape($this->element)."'"; + } + elseif ($updatetarget) + { + $sql .= "fk_target = ".$targetid; + $sql .= ", targettype = '".$this->db->escape($targettype)."'"; + $sql .= " WHERE fk_source = ".$this->id; + $sql .= " AND sourcetype = '".$this->db->escape($this->element)."'"; + } + + dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); + if ($this->db->query($sql)) + { + return 1; + } + else + { @@ -4330,8 +3541,0 @@ - $error++; - } - - if (!$error) { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); @@ -4350,2 +3553,0 @@ - * @param User $f_user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers @@ -4355,3 +3557,2 @@ - public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0) - { - global $user; + public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '') + { @@ -4360,7 +3561,3 @@ - $f_user = isset($f_user) ? $f_user : $user; - - if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) { - $deletesource = true; - } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) { - $deletetarget = true; - } + + if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true; + elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true; @@ -4372,46 +3569,30 @@ - $this->db->begin(); - $error = 0; - - if (!$notrigger) { - // Call trigger - $this->context['link_id'] = $rowid; - $this->context['link_source_id'] = $sourceid; - $this->context['link_source_type'] = $sourcetype; - $this->context['link_target_id'] = $targetid; - $this->context['link_target_type'] = $targettype; - $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user); - if ($result < 0) { - $error++; - } - // End call triggers - } - - if (!$error) { - $sql = "DELETE FROM " . $this->db->prefix() . "element_element"; - $sql .= " WHERE"; - if ($rowid > 0) { - $sql .= " rowid = " . ((int) $rowid); - } else { - if ($deletesource) { - $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'"; - $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'"; - } elseif ($deletetarget) { - $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'"; - $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'"; - } else { - $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')"; - $sql .= " OR"; - $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')"; - } - } - - dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG); - if (!$this->db->query($sql)) { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - $error++; - } - } - - if (!$error) { - $this->db->commit(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element"; + $sql .= " WHERE"; + if ($rowid > 0) + { + $sql .= " rowid = ".$rowid; + } + 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) + { + $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; + $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'"; + } + 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)."')"; + } + } + + dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG); + if ($this->db->query($sql)) + { @@ -4419,18 +3600,5 @@ - } else { - $this->db->rollback(); - return 0; - } - } - - /** - * Function used to get an array with all items linked to an object id in association table - * - * @param int $fk_object_where id of object we need to get linked items - * @param string $field_select name of field we need to get a list - * @param string $field_where name of field of object we need to get linked items - * @param string $table_element name of association table - * @return array|int Array of record, -1 if empty - */ - public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element) - { - if (empty($fk_object_where) || empty($field_where) || empty($table_element)) { + } + else + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; @@ -4439,76 +3607,4 @@ - if (!preg_match('/^[_a-zA-Z0-9]+$/', $field_select)) { - dol_syslog('Invalid value $field_select for parameter '.$field_select.' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR); - } - - global $db; - - $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where); - $resql = $db->query($sql); - - $TRes = array(); - if (!empty($resql)) { - while ($res = $db->fetch_object($resql)) { - $TRes[] = $res->{$field_select}; - } - } - - return $TRes; - } - - /** - * Count items linked to an object id in association table - * - * @param int $fk_object_where id of object we need to get linked items - * @param string $field_where name of field of object we need to get linked items - * @param string $table_element name of association table - * @return array|int Array of record, -1 if empty - */ - public static function getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element) - { - if (empty($fk_object_where) || empty($field_where) || empty($table_element)) { - return -1; - } - - global $db; - - $sql = "SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where); - $resql = $db->query($sql); - $n = 0; - if ($resql) { - $res = $db->fetch_object($resql); - if ($res) { - $n = $res->nb; - } - } - - return $n; - } - - /** - * Function used to remove all items linked to an object id in association table - * - * @param int $fk_object_where id of object we need to remove linked items - * @param string $field_where name of field of object we need to delete linked items - * @param string $table_element name of association table - * @return int Return integer <0 if KO, 0 if nothing done, >0 if OK and something done - */ - public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element) - { - if (empty($fk_object_where) || empty($field_where) || empty($table_element)) { - return -1; - } - - global $db; - - $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where); - $resql = $db->query($sql); - - if (empty($resql)) { - return 0; - } - - return 1; - } - - /** - * Set status of an object. + } + + /** + * Set status of an object @@ -4517 +3613 @@ - * @param int $elementId Id of element to force (use this->id by default if null) + * @param int $elementId Id of element to force (use this->id by default) @@ -4519,5 +3615,4 @@ - * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated. - * @param string $fieldstatus Name of status field in this->table_element - * @return int Return integer <0 if KO, >0 if OK - */ - public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut') + * @param string $trigkey Trigger key to use for trigger + * @return int <0 if KO, >0 if OK + */ + public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '') @@ -4534,27 +3629,11 @@ - if ($elementTable == 'facture_rec') { - $fieldstatus = "suspended"; - } - if ($elementTable == 'mailing') { - $fieldstatus = "statut"; - } - if ($elementTable == 'cronjob') { - $fieldstatus = "status"; - } - if ($elementTable == 'user') { - $fieldstatus = "statut"; - } - if ($elementTable == 'expensereport') { - $fieldstatus = "fk_statut"; - } - if ($elementTable == 'commande_fournisseur_dispatch') { - $fieldstatus = "status"; - } - if ($elementTable == 'prelevement_bons') { - $fieldstatus = "statut"; - } - if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) { - $fieldstatus = 'status'; - } - - $sql = "UPDATE ".$this->db->prefix().$elementTable; - $sql .= " SET ".$fieldstatus." = ".((int) $status); + $fieldstatus = "fk_statut"; + if ($elementTable == 'facture_rec') $fieldstatus = "suspended"; + if ($elementTable == 'mailing') $fieldstatus = "statut"; + if ($elementTable == 'cronjob') $fieldstatus = "status"; + if ($elementTable == 'user') $fieldstatus = "statut"; + if ($elementTable == 'expensereport') $fieldstatus = "fk_statut"; + if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus = "status"; + if (is_array($this->fields) && array_key_exists('status', $this->fields)) $fieldstatus = 'status'; + + $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; + $sql .= " SET ".$fieldstatus." = ".$status; @@ -4562,12 +3641,2 @@ - // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields - if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) { - $sql .= ", fk_user_valid = ".((int) $user->id); - } - if ($status == 1 && in_array($elementTable, array('expensereport'))) { - $sql .= ", date_valid = '".$this->db->idate(dol_now())."'"; - } - if ($status == 1 && in_array($elementTable, array('inventory'))) { - $sql .= ", date_validation = '".$this->db->idate(dol_now())."'"; - } - $sql .= " WHERE rowid = ".((int) $elementId); - $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct + if ($status == 1 && $elementTable == 'expensereport') $sql .= ", fk_user_valid = ".$user->id; + $sql .= " WHERE rowid=".$elementId; @@ -4576,2 +3645,2 @@ - $resql = $this->db->query($sql); - if ($resql) { + if ($this->db->query($sql)) + { @@ -4580,38 +3649,21 @@ - $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct - - if ($nb_rows_affected > 0) { - if (empty($trigkey)) { - // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus) - if ($this->element == 'supplier_proposal' && $status == 2) { - $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class - } - if ($this->element == 'supplier_proposal' && $status == 3) { - $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class - } - if ($this->element == 'supplier_proposal' && $status == 4) { - $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class - } - if ($this->element == 'fichinter' && $status == 3) { - $trigkey = 'FICHINTER_CLASSIFY_DONE'; - } - if ($this->element == 'fichinter' && $status == 2) { - $trigkey = 'FICHINTER_CLASSIFY_BILLED'; - } - if ($this->element == 'fichinter' && $status == 1) { - $trigkey = 'FICHINTER_CLASSIFY_UNBILLED'; - } - } - - if ($trigkey) { - // Call trigger - $result = $this->call_trigger($trigkey, $user); - if ($result < 0) { - $error++; - } - // End call triggers - } - } else { - // The status was probably already good. We do nothing more, no triggers. - } - - if (!$error) { + // Try autoset of trigkey + if (empty($trigkey)) + { + if ($this->element == 'supplier_proposal' && $status == 2) $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 3) $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 4) $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class + if ($this->element == 'fichinter' && $status == 3) $trigkey = 'FICHINTER_CLASSIFY_DONE'; + if ($this->element == 'fichinter' && $status == 2) $trigkey = 'FICHINTER_CLASSIFY_BILLED'; + if ($this->element == 'fichinter' && $status == 1) $trigkey = 'FICHINTER_CLASSIFY_UNBILLED'; + } + + if ($trigkey) + { + // Call trigger + $result = $this->call_trigger($trigkey, $user); + if ($result < 0) $error++; + // End call triggers + } + + if (!$error) + { @@ -4620,10 +3672,4 @@ - if (empty($savElementId)) { - // If the element we update is $this (so $elementId was provided as null) - if ($fieldstatus == 'tosell') { - $this->status = $status; - } elseif ($fieldstatus == 'tobuy') { - $this->status_buy = $status; // @phpstan-ignore-line - } else { - $this->statut = $status; - $this->status = $status; - } + if (empty($savElementId)) // If the element we update was $this (so $elementId is null) + { + $this->statut = $status; + $this->status = $status; @@ -4633 +3679,3 @@ - } else { + } + else + { @@ -4638 +3686,3 @@ - } else { + } + else + { @@ -4651 +3701 @@ - * @return int Return integer <0 if KO, 0 if nothing done, >0 if OK + * @return int <0 if KO, 0 if nothing done, >0 if OK @@ -4657,6 +3707,2 @@ - if (empty($id) && empty($ref)) { - return 0; - } - if (getDolGlobalString('MAIN_DISABLE_CANVAS')) { - return 0; // To increase speed. Not enabled by default. - } + if (empty($id) && empty($ref)) return 0; + if (!empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. @@ -4668 +3714 @@ - $sql .= " FROM ".$this->db->prefix().$this->table_element; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; @@ -4670,6 +3716,2 @@ - if (!empty($id)) { - $sql .= " AND rowid = ".((int) $id); - } - if (!empty($ref)) { - $sql .= " AND ref = '".$this->db->escape($ref)."'"; - } + if (!empty($id)) $sql .= " AND rowid = ".$id; + if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'"; @@ -4678 +3720,2 @@ - if ($resql) { + if ($resql) + { @@ -4680 +3723,2 @@ - if ($obj) { + if ($obj) + { @@ -4683,4 +3727,5 @@ - } else { - return 0; - } - } else { + } + else return 0; + } + else + { @@ -4701,2 +3746,2 @@ - $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE rowid = ".((int) $lineid); + $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE rowid = '.$lineid; @@ -4704 +3749,2 @@ - if ($resql) { + if ($resql) + { @@ -4706,8 +3752,6 @@ - return (!empty($row[0]) ? $row[0] : 0); - } - - return 0; - } - - /** - * Function to check if an object is used by others (by children). + return $row[0]; + } + } + + /** + * Function to check if an object is used by others. @@ -4717,4 +3761,3 @@ - * @param int $entity Force entity to check - * @return int Return integer <0 if KO, 0 if not used, >0 if already used - */ - public function isObjectUsed($id = 0, $entity = 0) + * @return int <0 if KO, 0 if not used, >0 if already used + */ + public function isObjectUsed($id = 0) @@ -4724,3 +3767 @@ - if (empty($id)) { - $id = $this->id; - } + if (empty($id)) $id = $this->id; @@ -4729 +3770,2 @@ - if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) { + if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) + { @@ -4734,2 +3776,2 @@ - $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...) - // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...) + $arraytoscan = $this->childtables; + // For backward compatibility, we check if array is old format array('table1', 'table2', ...) @@ -4737 +3779,2 @@ - if (is_numeric($tmparray[0])) { + if (is_numeric($tmparray[0])) + { @@ -4743 +3786,2 @@ - foreach ($arraytoscan as $table => $element) { + foreach ($arraytoscan as $table => $elementname) + { @@ -4745,25 +3789,3 @@ - // Check if element can be deleted - $sql = "SELECT COUNT(*) as nb"; - $sql.= " FROM ".$this->db->prefix().$table." as c"; - if (!empty($element['parent']) && !empty($element['parentkey'])) { - $sql.= ", ".$this->db->prefix().$element['parent']." as p"; - } - if (!empty($element['fk_element'])) { - $sql.= " WHERE c.".$element['fk_element']." = ".((int) $id); - } else { - $sql.= " WHERE c.".$this->fk_element." = ".((int) $id); - } - if (!empty($element['parent']) && !empty($element['parentkey'])) { - $sql.= " AND c.".$element['parentkey']." = p.rowid"; - } - if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) { - $sql.= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'"; - } - if (!empty($entity)) { - if (!empty($element['parent']) && !empty($element['parentkey'])) { - $sql.= " AND p.entity = ".((int) $entity); - } else { - $sql.= " AND c.entity = ".((int) $entity); - } - } - + // Check if third party can be deleted + $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; + $sql .= " WHERE ".$this->fk_element." = ".$id; @@ -4771 +3793,2 @@ - if ($resql) { + if ($resql) + { @@ -4773 +3796,2 @@ - if ($obj->nb > 0) { + if ($obj->nb > 0) + { @@ -4777,6 +3801,7 @@ - if (is_numeric($element)) { // very old usage array('table1', 'table2', ...) - $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table); - } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...) - $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element)); - } else { // new usage: $element['name']=Translation key - $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name'])); + if (is_numeric($elementname)) // old usage + { + $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table); + } + else // new usage: $elementname=Translation key + { + $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); @@ -4786 +3811,3 @@ - } else { + } + else + { @@ -4791 +3818,2 @@ - if ($haschild > 0) { + if ($haschild > 0) + { @@ -4794,3 +3822,2 @@ - } else { - return 0; - } + } + else return 0; @@ -4803 +3830 @@ - * @return int Return integer <0 if KO, 0 if no predefined products, nb of lines with predefined products if found + * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found @@ -4809 +3836,2 @@ - foreach ($this->lines as $key => $val) { + foreach ($this->lines as $key => $val) + { @@ -4811,18 +3839,6 @@ - if ($predefined == -1) { - $qualified = 1; - } - if ($predefined == 1 && $val->fk_product > 0) { - $qualified = 1; - } - if ($predefined == 0 && $val->fk_product <= 0) { - $qualified = 1; - } - if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) { - $qualified = 1; - } - if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) { - $qualified = 1; - } - if ($qualified) { - $nb++; - } + if ($predefined == -1) $qualified = 1; + if ($predefined == 1 && $val->fk_product > 0) $qualified = 1; + if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1; + if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1; + if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1; + if ($qualified) $nb++; @@ -4837 +3853 @@ - * @return float|string Total amout of discount + * @return float @@ -4841,31 +3857,29 @@ - if (!empty($this->table_element_line)) { - $total_discount = 0.00; - - $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; - $sql .= " FROM ".$this->db->prefix().$this->table_element_line; - $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - - dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) { - $obj = $this->db->fetch_object($resql); - - $pu_ht = $obj->pu_ht; - $qty = $obj->qty; - $total_ht = $obj->total_ht; - - $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT'); - $total_discount += $total_discount_line; - - $i++; - } - } - - //print $total_discount; exit; - return price2num($total_discount); - } - - return null; + $total_discount = 0.00; + + $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; + $sql .= " WHERE ".$this->fk_element." = ".$this->id; + + dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + $pu_ht = $obj->pu_ht; + $qty = $obj->qty; + $total_ht = $obj->total_ht; + + $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); + $total_discount += $total_discount_line; + + $i++; + } + } + + //print $total_discount; exit; + return price2num($total_discount); @@ -4890,5 +3904,5 @@ - foreach ($this->lines as $line) { - if (isset($line->qty_asked)) { - if (empty($totalOrdered)) { - $totalOrdered = 0; // Avoid warning because $totalOrdered is '' - } + foreach ($this->lines as $line) + { + if (isset($line->qty_asked)) + { + if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is '' @@ -4897,4 +3911,3 @@ - if (isset($line->qty_shipped)) { - if (empty($totalToShip)) { - $totalToShip = 0; // Avoid warning because $totalToShip is '' - } + if (isset($line->qty_shipped)) + { + if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is '' @@ -4902,4 +3915,4 @@ - } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) { - if (empty($totalToShip)) { - $totalToShip = 0; - } + } + elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) + { + if (empty($totalToShip)) $totalToShip = 0; @@ -4913 +3926,2 @@ - } else { + } + else { @@ -4917,3 +3931,3 @@ - $weight = !empty($line->weight) ? $line->weight : 0; - ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; - $volume = !empty($line->volume) ? $line->volume : 0; + $weight = $line->weight ? $line->weight : 0; + ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; + $volume = $line->volume ? $line->volume : 0; @@ -4922 +3936 @@ - $weight_units = !empty($line->weight_units) ? $line->weight_units : 0; + $weight_units = $line->weight_units; @@ -4924 +3938 @@ - $volume_units = !empty($line->volume_units) ? $line->volume_units : 0; + $volume_units = $line->volume_units; @@ -4929,13 +3943,5 @@ - if (!empty($weight_units)) { - $weightUnit = $weight_units; - } - if (!empty($volume_units)) { - $volumeUnit = $volume_units; - } - - if (empty($totalWeight)) { - $totalWeight = 0; // Avoid warning because $totalWeight is '' - } - if (empty($totalVolume)) { - $totalVolume = 0; // Avoid warning because $totalVolume is '' - } + if (!empty($weight_units)) $weightUnit = $weight_units; + if (!empty($volume_units)) $volumeUnit = $volume_units; + + if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is '' + if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is '' @@ -4944 +3950,2 @@ - if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + if ($weight_units < 50) // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + { @@ -4947 +3954,2 @@ - } else { + } + else { @@ -4956 +3964,2 @@ - } else { + } + else { @@ -4960 +3969,2 @@ - if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + { @@ -4965 +3975,3 @@ - } else { + } + else + { @@ -4977 +3989 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -4985 +3997 @@ - $sql = "UPDATE ".$this->db->prefix().$this->table_element; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; @@ -4987 +3999 @@ - $sql .= " WHERE rowid = ".((int) $this->id); + $sql .= " WHERE rowid = ".$this->id; @@ -4991 +4003,2 @@ - if (!$resql) { + if (!$resql) + { @@ -4995 +4008,3 @@ - } else { + } + else + { @@ -4998,0 +4014,98 @@ + } + + + // 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; @@ -5019 +4132,2 @@ - global $conf, $user, $langs, $object, $hookmanager, $extrafields, $form; + global $conf, $user, $langs, $object, $hookmanager, $extrafields; + global $form; @@ -5022 +4136,2 @@ - if (!is_object($extrafields)) { + if (!is_object($extrafields)) + { @@ -5032,2 +4147,4 @@ - foreach ($dirtpls as $module => $reldir) { - if (!empty($module)) { + foreach ($dirtpls as $module => $reldir) + { + if (!empty($module)) + { @@ -5035 +4152,3 @@ - } else { + } + else + { @@ -5044,3 +4163 @@ - if ($res) { - break; - } + if ($res) break; @@ -5062,3 +4179,3 @@ - * @param Societe $seller Object of seller third party - * @param Societe $buyer Object of buyer third party - * @param int $selected ID line selected + * @param string $seller Object of seller third party + * @param string $buyer Object of buyer third party + * @param int $selected Object line selected @@ -5077,3 +4194 @@ - if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) { - $usemargins = 1; - } + if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1; @@ -5084 +4199,2 @@ - if (!is_object($extrafields)) { + if (!is_object($extrafields)) + { @@ -5092 +4208,2 @@ - if (empty($reshook)) { + if (empty($reshook)) + { @@ -5097,3 +4214,4 @@ - foreach ($dirtpls as $module => $reldir) { - $res = 0; - if (!empty($module)) { + foreach ($dirtpls as $module => $reldir) + { + if (!empty($module)) + { @@ -5100,0 +4219,7 @@ + } + else + { + $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php'; + } + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; @@ -5102,12 +4227,3 @@ - $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php'; - } - if (file_exists($tpl)) { - if (empty($conf->file->strict_mode)) { - $res = @include $tpl; - } else { - $res = include $tpl; // for debug - } - } - if ($res) { - break; - } + $res = include $tpl; // for debug + } + if ($res) break; @@ -5120 +4236,2 @@ - foreach ($this->lines as $line) { + foreach ($this->lines as $line) + { @@ -5124,4 +4241,6 @@ - //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) - if (is_object($hookmanager)) { // Old code is commented on preceding line. - if (empty($line->fk_parent_line)) { - $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'defaulttpldir'=>$defaulttpldir); + //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) + if (is_object($hookmanager)) // Old code is commented on preceding line. + { + if (empty($line->fk_parent_line)) + { + $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element); @@ -5129,2 +4248,4 @@ - } 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, 'defaulttpldir'=>$defaulttpldir); + } + 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); @@ -5134 +4255,2 @@ - if (empty($reshook)) { + if (empty($reshook)) + { @@ -5149 +4271 @@ - * @param string $var Not used + * @param string $var Is it a an odd line (true) @@ -5153,3 +4275,3 @@ - * @param Societe $seller Object of seller third party - * @param Societe $buyer Object of buyer third party - * @param int $selected ID line selected + * @param string $seller Object of seller third party + * @param string $buyer Object of buyer third party + * @param int $selected Object line selected @@ -5168,3 +4290,3 @@ - // var used into tpl - $text = ''; - $description = ''; + $element = $this->element; + + $text = ''; $description = ''; @@ -5173 +4295,2 @@ - if ($action != 'editline' || $selected != $line->id) { + if ($action != 'editline' || $selected != $line->id) + { @@ -5175 +4298,2 @@ - if (!empty($line->fk_product) && $line->fk_product > 0) { + if ($line->fk_product > 0) + { @@ -5180 +4304 @@ - $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook + $product_static->label = $line->label; //can change label in hook @@ -5185,2 +4309,4 @@ - if (getDolGlobalInt('MAIN_MULTILANGS')) { - if (property_exists($this, 'socid') && !is_object($this->thirdparty)) { + if (!empty($conf->global->MAIN_MULTILANGS)) + { + if (property_exists($this, 'socid') && !is_object($this->thirdparty)) + { @@ -5196,7 +4322,4 @@ - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { - $newlang = GETPOST('lang_id', 'aZ09'); - } - if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) { - $newlang = $this->thirdparty->default_lang; // To use language of customer - } - if (!empty($newlang)) { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); + if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) $newlang = $this->thirdparty->default_lang; // To use language of customer + if (!empty($newlang)) + { @@ -5208 +4331,3 @@ - } else { + } + else + { @@ -5213,4 +4338,4 @@ - $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc. - } - - $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU'); + $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc. + } + + $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU'); @@ -5222,3 +4347,4 @@ - foreach ($dirtpls as $module => $reldir) { - $res = 0; - if (!empty($module)) { + foreach ($dirtpls as $module => $reldir) + { + if (!empty($module)) + { @@ -5225,0 +4352,8 @@ + } + else + { + $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php'; + } + + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; @@ -5227,13 +4361,3 @@ - $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php'; - } - //var_dump($tpl); - if (file_exists($tpl)) { - if (empty($conf->file->strict_mode)) { - $res = @include $tpl; - } else { - $res = include $tpl; // for debug - } - } - if ($res) { - break; - } + $res = include $tpl; // for debug + } + if ($res) break; @@ -5244 +4368,2 @@ - if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) { + if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) + { @@ -5253,2 +4378,4 @@ - foreach ($dirtpls as $module => $reldir) { - if (!empty($module)) { + foreach ($dirtpls as $module => $reldir) + { + if (!empty($module)) + { @@ -5256 +4383,3 @@ - } else { + } + else + { @@ -5265,3 +4394 @@ - if ($res) { - break; - } + if ($res) break; @@ -5288 +4415 @@ - global $langs, $hookmanager, $conf, $form, $action; + global $langs, $hookmanager, $conf, $form; @@ -5291,15 +4418,13 @@ - print ''.$langs->trans('Ref').''; - print ''.$langs->trans('Description').''; - print ''.$langs->trans('VATRate').''; - print ''.$langs->trans('PriceUHT').''; - if (isModEnabled("multicurrency")) { - print ''.$langs->trans('PriceUHTCurrency').''; - } - print ''.$langs->trans('Qty').''; - if (getDolGlobalInt('PRODUCT_USE_UNITS')) { - print ''.$langs->trans('Unit').''; - } - print ''.$langs->trans('ReductionShort').''; - print ''.$langs->trans('TotalHT').''; - print ''.$form->showCheckAddButtons('checkforselect', 1).''; - print ''; + print ''.$langs->trans('Ref').''; + print ''.$langs->trans('Description').''; + print ''.$langs->trans('VATRate').''; + print ''.$langs->trans('PriceUHT').''; + if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency').''; + print ''.$langs->trans('Qty').''; + if ($conf->global->PRODUCT_USE_UNITS) + { + print ''.$langs->trans('Unit').''; + } + print ''.$langs->trans('ReductionShort').''; + print ''.$form->showCheckAddButtons('checkforselect', 1).''; + print ''; @@ -5308,12 +4433,15 @@ - if (!empty($this->lines)) { - foreach ($this->lines as $line) { - $reshook = 0; - //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) { - if (is_object($hookmanager)) { // Old code is commented on preceding line. - $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines); - if (!empty($line->fk_parent_line)) { - $parameters['fk_parent_line'] = $line->fk_parent_line; - } - $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - } - if (empty($reshook)) { + if (!empty($this->lines)) + { + foreach ($this->lines as $line) + { + if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) + { + if (empty($line->fk_parent_line)) + { + $parameters = array('line'=>$line, 'i'=>$i); + $action = ''; + $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + } + } + else + { @@ -5335 +4463 @@ - * @param string $var Not used + * @param string $var Var @@ -5346 +4474,2 @@ - if (!empty($line->date_start)) { + if (!empty($line->date_start)) + { @@ -5348 +4477,3 @@ - } else { + } + else + { @@ -5350,5 +4481,4 @@ - if ($line->date_debut_reel) { - $date_start = $line->date_debut_reel; - } - } - if (!empty($line->date_end)) { + if ($line->date_debut_reel) $date_start = $line->date_debut_reel; + } + if (!empty($line->date_end)) + { @@ -5356 +4486,3 @@ - } else { + } + else + { @@ -5358,6 +4490,4 @@ - if ($line->date_fin_reel) { - $date_end = $line->date_fin_reel; - } - } - - $this->tpl['id'] = $line->id; + if ($line->date_fin_reel) $date_end = $line->date_fin_reel; + } + + $this->tpl['id'] = $line->id; @@ -5366,5 +4496,4 @@ - if (!empty($line->fk_parent_line)) { - $this->tpl['label'] .= img_picto('', 'rightarrow'); - } - - if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object + if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow'); + + if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object + { @@ -5372,3 +4501 @@ - if (property_exists($this, 'socid')) { - $discount->fk_soc = $this->socid; - } + $discount->fk_soc = $this->socid; @@ -5376 +4503,3 @@ - } elseif (!empty($line->fk_product)) { + } + elseif (!empty($line->fk_product)) + { @@ -5389 +4518,2 @@ - if ($line->product_type == 1 && ($date_start || $date_end)) { + if ($line->product_type == 1 && ($date_start || $date_end)) + { @@ -5392 +4522,3 @@ - } else { + } + else + { @@ -5401 +4533,2 @@ - if ($line->product_type == 1 && ($date_start || $date_end)) { + if ($line->product_type == 1 && ($date_start || $date_end)) + { @@ -5406,2 +4539,4 @@ - if (!empty($line->desc)) { - if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object + if (!empty($line->desc)) + { + if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object + { @@ -5411 +4546,3 @@ - } 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 + { @@ -5415 +4552,3 @@ - } elseif ($line->desc == '(EXCESS RECEIVED)') { + } + elseif ($line->desc == '(EXCESS RECEIVED)') + { @@ -5419 +4558,3 @@ - } elseif ($line->desc == '(EXCESS PAID)') { + } + elseif ($line->desc == '(EXCESS PAID)') + { @@ -5423 +4564,3 @@ - } else { + } + else + { @@ -5426 +4569,3 @@ - } else { + } + else + { @@ -5430,6 +4575,4 @@ - // 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.')'; @@ -5438 +4580,0 @@ - $this->tpl['total_ht'] = price($line->total_ht); @@ -5441,3 +4583 @@ - if (getDolGlobalInt('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')); @@ -5448,3 +4588 @@ - if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) { - $this->tpl['strike'] = 1; - } + if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1; @@ -5455,2 +4593,4 @@ - foreach ($dirtpls as $module => $reldir) { - if (!empty($module)) { + foreach ($dirtpls as $module => $reldir) + { + if (!empty($module)) + { @@ -5458 +4598,3 @@ - } else { + } + else + { @@ -5467,8 +4609,6 @@ - if ($res) { - break; - } - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + if ($res) break; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -5483 +4623 @@ - * @return int Return integer <=0 if KO, >0 if OK + * @return int <=0 if KO, >0 if OK @@ -5487 +4627 @@ - // phpcs:enable + // phpcs:enable @@ -5490 +4630 @@ - $sql = "INSERT INTO ".$this->db->prefix()."element_resources ("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources ("; @@ -5498 +4638 @@ - $sql .= ((int) $resource_id); + $sql .= $resource_id; @@ -5507 +4647,2 @@ - if ($this->db->query($sql)) { + if ($this->db->query($sql)) + { @@ -5510 +4651,3 @@ - } else { + } + else + { @@ -5517 +4660 @@ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -5528 +4671 @@ - // phpcs:enable + // phpcs:enable @@ -5533,2 +4676,2 @@ - $sql = "DELETE FROM ".$this->db->prefix()."element_resources"; - $sql .= " WHERE rowid = ".((int) $rowid); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; + $sql .= " WHERE rowid=".$rowid; @@ -5539 +4682,2 @@ - if (!$resql) { + if (!$resql) + { @@ -5543,2 +4687,5 @@ - } else { - if (!$notrigger) { + } + else + { + if (!$notrigger) + { @@ -5546,4 +4693 @@ - if ($result < 0) { - $this->db->rollback(); - return -1; - } + if ($result < 0) { $this->db->rollback(); return -1; } @@ -5565 +4709,2 @@ - if (isset($this->lines) && is_array($this->lines)) { + if (isset($this->lines) && is_array($this->lines)) + { @@ -5567,4 +4712,3 @@ - for ($i = 0; $i < $nboflines; $i++) { - if (is_object($this->lines[$i])) { - $this->lines[$i] = clone $this->lines[$i]; - } + for ($i = 0; $i < $nboflines; $i++) + { + $this->lines[$i] = clone $this->lines[$i]; @@ -5579 +4723 @@ - * @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. @@ -5597,293 +4741,251 @@ - if (!empty($reshook)) { - return $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); - $saved_model = $modele; - 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"; - } - - $file = dol_sanitizeFileName($file); - - // We chack if file exists - $file = dol_buildpath($reldir.$modelspath.$file, 0); - if (file_exists($file)) { - $filefound = $file; - $classname = $prefix.'_'.$modele; - break; - } - } - if ($filefound) { - break; - } - } - - if (!$filefound) { - $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; - $this->errors[] = $this->error; - dol_syslog($this->error, LOG_ERR); - return -1; - } - - // Sanitize $filefound - $filefound = dol_sanitizePathName($filefound); - - // If generator was found - global $db; // Required to solve a conception default making an include of some code that uses $db instead of $this->db just after. - - require_once $filefound; - - $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 && getDolGlobalString($varfortemplatedir)) { - $dirtoscan = getDolGlobalString($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 = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output; - - // update model_pdf in object - $this->model_pdf = $saved_model; - - if (in_array(get_class($this), array('Adherent'))) { - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $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']; - - // Update the last_main_doc field into main object (if document 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; - } - - // Check that the file exists, before indexing it. - // Hint: It does not exist, if we create a PDF and auto delete the ODT File - if (dol_is_file($destfull)) { - $this->indexFile($destfull, $update_main_doc_field); - } - } 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; - $this->error = $obj->error; - $this->errors = $obj->errors; - dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR); - return -1; - } - } - - /** - * Index a file into the ECM database - * - * @param string $destfull Full path of file to index - * @param int $update_main_doc_field Update field main_doc fied into the table of object. - * This param is set when called for a document generation if document generator hase - * ->update_main_doc_field set and returns ->result['fullpath']. - * @return int Return integer <0 if KO, >0 if OK - */ - public function indexFile($destfull, $update_main_doc_field) - { - global $conf, $user; - - $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' || $this->element == 'proposal') { - if (getDolGlobalInt("PROPOSAL_ALLOW_ONLINESIGN")) { - $setsharekey = true; // feature to make online signature is not set or set to on (default) - } - if (getDolGlobalInt("PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - } - if ($this->element == 'commande' && getDolGlobalInt("ORDER_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'facture' && getDolGlobalInt("INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'bank_account' && getDolGlobalInt("BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'product' && getDolGlobalInt("PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'contrat' && getDolGlobalInt("CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'fichinter' && getDolGlobalInt("FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'supplier_proposal' && getDolGlobalInt("SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) { - $setsharekey = true; - } - if ($this->element == 'societe_rib' && getDolGlobalInt("SOCIETE_RIB_ALLOW_ONLINESIGN")) { - $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->keywords = ''; // keyword content - $result = $ecmfile->update($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - return -1; - } - } 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->keywords = ''; // keyword content - $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'. - $ecmfile->src_object_id = $this->id; - - $result = $ecmfile->create($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - return -1; - } - } - - /*$this->result['fullname']=$destfull; - $this->result['filepath']=$ecmfile->filepath; - $this->result['filename']=$ecmfile->filename;*/ - //var_dump($obj->update_main_doc_field);exit; - - if ($update_main_doc_field && !empty($this->table_element)) { - $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'"; - $sql .= " WHERE rowid = ".((int) $this->id); - - $resql = $this->db->query($sql); - if (!$resql) { - dol_print_error($this->db); - return -1; - } else { - $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; - } - } - } - - return 1; + if (empty($reshook)) + { + 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'))) $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) { + 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; @@ -5900,0 +5003,4 @@ + global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ... + @@ -5902,12 +5008,2 @@ - - if (file_exists($file_osencoded)) { - require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - - $tmparraysize = getDefaultImageSizes(); - $maxwidthsmall = $tmparraysize['maxwidthsmall']; - $maxheightsmall = $tmparraysize['maxheightsmall']; - $maxwidthmini = $tmparraysize['maxwidthmini']; - $maxheightmini = $tmparraysize['maxheightmini']; - //$quality = $tmparraysize['quality']; - $quality = 50; // For thumbs, we force quality to 50 - + if (file_exists($file_osencoded)) + { @@ -5922,15 +5017,0 @@ - } - - /** - * Delete thumbs - * @todo Move this into files.lib.php - * - * @param string $file Path file in UTF8 to original file to delete thumbs. - * @return void - */ - public function delThumbs($file) - { - $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file - dol_delete_file($imgThumbName); - $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file - dol_delete_file($imgThumbName); @@ -5954 +5034,0 @@ - * @param string $type Type of data @@ -5957 +5037 @@ - public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml') + public function getDefaultCreateValueFor($fieldname, $alternatevalue = null) @@ -5962,7 +5042,3 @@ - if (GETPOSTISSET($fieldname)) { - return GETPOST($fieldname, $type, 3); - } - - if (isset($alternatevalue)) { - return $alternatevalue; - } + if (GETPOSTISSET($fieldname)) return GETPOST($fieldname, 'alphanohtml', 3); + + if (isset($alternatevalue)) return $alternatevalue; @@ -5971,7 +5047,4 @@ - if ($newelement == 'facture') { - $newelement = 'invoice'; - } - if ($newelement == 'commande') { - $newelement = 'order'; - } - if (empty($newelement)) { + if ($newelement == 'facture') $newelement = 'invoice'; + if ($newelement == 'commande') $newelement = 'order'; + if (empty($newelement)) + { @@ -5984,3 +5057 @@ - if (getDolGlobalString($keyforfieldname)) { - return getDolGlobalString($keyforfieldname); - } + if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; @@ -5989,3 +5059,0 @@ - // store content into $conf->cache['overwrite_default'] - - return ''; @@ -6014,5 +5082 @@ - if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) { - dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.'); - exit; - } - if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers(). + if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers. @@ -6027,2 +5091,4 @@ - if ($result < 0) { - if (!empty($this->errors)) { + if ($result < 0) + { + if (!empty($this->errors)) + { @@ -6030 +5096,3 @@ - } else { + } + else + { @@ -6045 +5113 @@ - * @return int Return integer <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded + * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded @@ -6064,3 +5132 @@ - if ($element == 'categorie') { - $element = 'categories'; // For compatibility - } + if ($element == 'categorie') $element = 'categories'; // For compatibility @@ -6070,3 +5136,3 @@ - $sql .= " FROM ".$this->db->prefix()."object_lang"; - $sql .= " WHERE type_object = '".$this->db->escape($element)."'"; - $sql .= " AND fk_object = ".((int) $this->id); + $sql .= " FROM ".MAIN_DB_PREFIX."object_lang"; + $sql .= " WHERE type_object = '".$element."'"; + $sql .= " AND fk_object = ".$this->id; @@ -6076 +5142,2 @@ - if ($resql) { + if ($resql) + { @@ -6078 +5145,2 @@ - if ($numrows) { + if ($numrows) + { @@ -6088 +5156,2 @@ - if (preg_match('/date/', $type)) { + if (preg_match('/date/', $type)) + { @@ -6090 +5159,3 @@ - } else { + } + else + { @@ -6100,6 +5171,5 @@ - if ($numrows) { - return $numrows; - } else { - return 0; - } - } else { + if ($numrows) return $numrows; + else return 0; + } + else + { @@ -6124,3 +5194 @@ - if ($tmparray[0] != 'field') { - continue; - } + if ($tmparray[0] != 'field') continue; @@ -6133,6 +5201,2 @@ - if (!empty($onlykey) && $key != $onlykey) { - continue; - } - if ($element != $this->element) { - continue; - } + if (!empty($onlykey) && $key != $onlykey) continue; + if ($element != $this->element) continue; @@ -6143,2 +5207,3 @@ - if (isset($this->fields[$key]['enabled'])) { - $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1'); + if (isset($this->fields[$key]['enabled'])) + { + $enabled = dol_eval($this->fields[$key]['enabled'], 1); @@ -6149 +5214 @@ - $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1'); + $perms = dol_eval($this->fields[$key]['perms'], 1); @@ -6151,3 +5216 @@ - if (empty($enabled)) { - continue; - } + if (empty($enabled)) continue; @@ -6156 +5219,2 @@ - if (in_array($key_type, array('date'))) { + if (in_array($key_type, array('date'))) + { @@ -6159,2 +5223,4 @@ - $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int')); - } elseif (in_array($key_type, array('datetime'))) { + $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]); + } + elseif (in_array($key_type, array('datetime'))) + { @@ -6163,2 +5229,4 @@ - $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int')); - } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) { + $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'))) + { @@ -6167 +5235 @@ - $value_key = implode(',', $value_arr); + $value_key = implode($value_arr, ','); @@ -6171 +5239,3 @@ - } elseif (in_array($key_type, array('price', 'double'))) { + } + elseif (in_array($key_type, array('price', 'double'))) + { @@ -6174 +5244,3 @@ - } else { + } + else + { @@ -6176,3 +5248 @@ - if (in_array($key_type, array('link')) && $value_key == '-1') { - $value_key = ''; - } + if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = ''; @@ -6209 +5279 @@ - $ret = $this->fetch($id); /* @phpstan-ignore-line */ + $ret = $this->fetch($id); @@ -6223 +5293 @@ - * @return int Return integer <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded + * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded @@ -6231,6 +5301,2 @@ - if (empty($rowid)) { - $rowid = $this->id; - } - if (empty($rowid) && isset($this->rowid)) { - $rowid = $this->rowid; // deprecated - } + if (empty($rowid)) $rowid = $this->id; + if (empty($rowid)) $rowid = $this->rowid; @@ -6245 +5311,2 @@ - if (!is_array($optionsArray)) { + if (!is_array($optionsArray)) + { @@ -6247 +5314,2 @@ - if (!isset($extrafields) || !is_object($extrafields)) { + if (!isset($extrafields) || !is_object($extrafields)) + { @@ -6253 +5321,2 @@ - if (empty($extrafields->attributes[$this->table_element]['loaded'])) { + if (empty($extrafields->attributes[$this->table_element]['loaded'])) + { @@ -6257 +5326,3 @@ - } else { + } + else + { @@ -6263,3 +5334 @@ - if ($table_element == 'categorie') { - $table_element = 'categories'; // For compatibility - } + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility @@ -6268 +5337,2 @@ - if (is_array($optionsArray) && count($optionsArray) > 0) { + if (is_array($optionsArray) && count($optionsArray) > 0) + { @@ -6270,2 +5340,4 @@ - foreach ($optionsArray as $name => $label) { - if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') { + foreach ($optionsArray as $name => $label) + { + if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') + { @@ -6275,2 +5347,2 @@ - $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields"; - $sql .= " WHERE fk_object = ".((int) $rowid); + $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; + $sql .= " WHERE fk_object = ".$rowid; @@ -6280 +5352,2 @@ - if ($resql) { + if ($resql) + { @@ -6282 +5355,2 @@ - if ($numrows) { + if ($numrows) + { @@ -6285 +5359,2 @@ - foreach ($tab as $key => $value) { + foreach ($tab as $key => $value) + { @@ -6287 +5362,2 @@ - if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) { + if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) + { @@ -6289 +5365,2 @@ - if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) { + if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) + { @@ -6292 +5369,3 @@ - } else { + } + else + { @@ -6298,3 +5377,9 @@ - if (!empty($extrafields->attributes[$this->table_element]['type'][$key]) && $extrafields->attributes[$this->table_element]['type'][$key] == 'password') { - if (!empty($value) && preg_match('/^dolcrypt:/', $value)) { - $this->array_options["options_".$key] = dolDecrypt($value); + } + + // If field is a computed field, value must become result of compute + foreach ($tab as $key => $value) { + if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) + { + //var_dump($conf->disable_compute); + if (empty($conf->disable_compute)) { + $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0); @@ -6306,15 +5390,0 @@ - // If field is a computed field, value must become result of compute (regardless of whether a row exists - // in the element's extrafields table) - if (is_array($extrafields->attributes[$this->table_element]['label'])) { - foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) { - if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) { - //var_dump($conf->disable_compute); - if (empty($conf->disable_compute)) { - global $objectoffield; // We set a global variable to $objectoffield so - $objectoffield = $this; // we can use it inside computed formula - $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2'); - } - } - } - } - @@ -6323,7 +5393,6 @@ - if ($numrows) { - return $numrows; - } else { - return 0; - } - } else { - $this->errors[]=$this->db->lasterror; + if ($numrows) return $numrows; + else return 0; + } + else + { + dol_print_error($this->db); @@ -6339 +5408 @@ - * @return int Return integer <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK @@ -6346,3 +5415 @@ - if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) { - return 0; - } + if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; @@ -6353,4 +5420,3 @@ - if ($table_element == 'categorie') { - $table_element = 'categories'; // For compatibility - } - + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility + + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; @@ -6358,3 +5423,0 @@ - - $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id); - @@ -6362 +5425,2 @@ - if (!$resql) { + if (!$resql) + { @@ -6366 +5430,3 @@ - } else { + } + else + { @@ -6386,7 +5452,3 @@ - if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) { - return 0; - } - - if (empty($userused)) { - $userused = $user; - } + if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; + + if (empty($userused)) $userused = $user; @@ -6396 +5458,2 @@ - if (!empty($this->array_options)) { + if (!empty($this->array_options)) + { @@ -6403 +5466 @@ - // 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 @@ -6406 +5469 @@ - if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test + if (in_array(substr($key, 8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test @@ -6408 +5471 @@ - } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix + elseif (in_array($key, array_keys($target_extrafields))) // We test on $key that does not contains the 'options_' prefix @@ -6410,10 +5473,9 @@ - } - } - - foreach ($new_array_options as $key => $value) { - $attributeKey = substr($key, 8); // Remove 'options_' prefix - $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey]; - $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element]['label'][$attributeKey]); - $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey]; - $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey]; - $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey]; + } + + foreach ($new_array_options as $key => $value) + { + $attributeKey = substr($key, 8); // Remove 'options_' prefix + $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey]; + $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey]; + $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey]; + $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey]; @@ -6422,16 +5484,12 @@ - // If we clone, we have to clean unique extrafields to prevent duplicates. - // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook - if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) { - $new_array_options[$key] = null; - } - - // Similar code than into insertExtraFields - if ($attributeRequired) { - $v = $this->array_options[$key]; - if (ExtraFields::isEmptyValue($v, $attributeType)) { - $langs->load("errors"); - dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields"); - $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); - return -1; - } - } + if ($attributeRequired) + { + $mandatorypb = false; + if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true; + if ($this->array_options[$key] === '') $mandatorypb = true; + if ($mandatorypb) + { + dol_syslog("Mandatory extra field ".$key." is empty"); + $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); + return -1; + } + } @@ -6442,6 +5500,10 @@ - if (!empty($attrfieldcomputed)) { - if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) { - $value = dol_eval($attrfieldcomputed, 1, 0, '2'); - dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG); - $new_array_options[$key] = $value; - } else { + 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); + $new_array_options[$key] = $value; + } + else + { @@ -6452,3 +5514,18 @@ - switch ($attributeType) { - case 'int': - if (!is_numeric($value) && $value != '') { + switch ($attributeType) + { + case 'int': + if (!is_numeric($value) && $value != '') + { + $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); + return -1; + } + elseif ($value == '') + { + $new_array_options[$key] = null; + } + break; + case 'double': + $value = price2num($value); + if (!is_numeric($value) && $value != '') + { + dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); @@ -6457 +5534,3 @@ - } elseif ($value == '') { + } + elseif ($value == '') + { @@ -6459,11 +5537,0 @@ - } - break; - case 'price': - case 'double': - $value = price2num($value); - if (!is_numeric($value) && $value != '') { - dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); - $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); - return -1; - } elseif ($value == '') { - $value = null; @@ -6474,40 +5542,30 @@ - /*case 'select': // Not required, we chosed value='0' for undefined values - if ($value=='-1') - { - $this->array_options[$key] = null; - } - break;*/ - case 'password': - $algo = ''; - if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) { - // If there is an encryption choice, we use it to crypt data before insert - $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']); - $algo = reset($tmparrays); - if ($algo != '') { - //global $action; // $action may be 'create', 'update', 'update_extras'... - //var_dump($action); - //var_dump($this->oldcopy);exit; - if (is_object($this->oldcopy)) { // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value - //var_dump('iii'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]); - if (isset($this->oldcopy->array_options[$key]) && $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. - if ($algo == 'dolcrypt') { // dolibarr reversible encryption - if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) { - $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master - } else { - $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } - } else { - $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } - } else { - // If value has changed - if ($algo == 'dolcrypt') { // dolibarr reversible encryption - if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) { - $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master - } else { - $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } - } else { - $new_array_options[$key] = dol_hash($this->array_options[$key], $algo); - } + /*case 'select': // Not required, we chosed value='0' for undefined values + if ($value=='-1') + { + $this->array_options[$key] = null; + } + break;*/ + case 'password': + $algo = ''; + if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) + { + // If there is an encryption choice, we use it to crypt data before insert + $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']); + $algo = reset($tmparrays); + if ($algo != '') + { + //global $action; // $action may be 'create', 'update', 'update_extras'... + //var_dump($action); + //var_dump($this->oldcopy);exit; + if (is_object($this->oldcopy)) // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value + { + //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]); + 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 + { + // var_dump($algo); + $newvalue = dol_hash($this->array_options[$key], $algo); + $new_array_options[$key] = $newvalue; @@ -6515,16 +5573,14 @@ - } else { - //var_dump('jjj'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]); - // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value - if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options[$key])) { // dolibarr reversible encryption - $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master - } else { - $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } - } - } else { - // No encryption - $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } - } else { // Common usage - $new_array_options[$key] = $this->array_options[$key]; // Value is kept - } + } + else + { + $new_array_options[$key] = $this->array_options[$key]; // Value is kept + } + } + } + else // Common usage + { + $new_array_options[$key] = $this->array_options[$key]; + } + break; + case 'price': + $new_array_options[$key] = price2num($this->array_options[$key]); @@ -6535 +5591 @@ - if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) { + if (!is_int($this->array_options[$key])) { @@ -6540,8 +5596 @@ - case 'datetimegmt': - // If data is a string instead of a timestamp, we convert it - if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) { - $this->array_options[$key] = strtotime($this->array_options[$key]); - } - $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt'); - break; - case 'link': + case 'link': @@ -6553,2 +5602,4 @@ - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) { - if ($value == '-1') { // -1 is key for no defined in combo list of objects + if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) + { + if ($value == '-1') // -1 is key for no defined in combo list of objects + { @@ -6556 +5607,3 @@ - } elseif ($value) { + } + elseif ($value) + { @@ -6558,9 +5611,6 @@ - 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 { + if (is_numeric($value)) $res = $object->fetch($value); + else $res = $object->fetch('', $value); + + if ($res > 0) $new_array_options[$key] = $object->id; + else + { @@ -6567,0 +5618 @@ + $this->db->rollback(); @@ -6571 +5622,3 @@ - } else { + } + else + { @@ -6575,9 +5628 @@ - case 'checkbox': - case 'chkbxlst': - if (is_array($this->array_options[$key])) { - $new_array_options[$key] = implode(',', $this->array_options[$key]); - } else { - $new_array_options[$key] = $this->array_options[$key]; - } - break; - } + } @@ -6589,3 +5634 @@ - if ($table_element == 'categorie') { - $table_element = 'categories'; // For compatibility - } + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility @@ -6595 +5638 @@ - $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id); + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; @@ -6598,2 +5641,3 @@ - $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object"; - foreach ($new_array_options as $key => $value) { + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; + foreach ($new_array_options as $key => $value) + { @@ -6602 +5646 @@ - if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator + if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator @@ -6604 +5647,0 @@ - } @@ -6607,6 +5650,9 @@ - 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; + } + } @@ -6616 +5662,2 @@ - foreach ($new_array_options as $key => $value) { + foreach ($new_array_options as $key => $value) + { @@ -6619,2 +5666,4 @@ - 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') + { @@ -6622 +5671,3 @@ - } else { + } + else + { @@ -6628,10 +5679,10 @@ - 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 .= ", ''"; + } + } @@ -6643 +5694,3 @@ - if (!$resql) { + + if (!$resql) + { @@ -6648 +5701,2 @@ - if (!$error && $trigger) { + if (!$error && $trigger) + { @@ -6652,3 +5706 @@ - if ($result < 0) { - $error++; - } + if ($result < 0) $error++; @@ -6658 +5710,2 @@ - if ($error) { + if ($error) + { @@ -6661 +5714,3 @@ - } else { + } + else + { @@ -6665,3 +5720,2 @@ - } else { - return 0; - } + } + else return 0; @@ -6684,3 +5738 @@ - if (empty($userused)) { - $userused = $user; - } + if (empty($userused)) $userused = $user; @@ -6690,5 +5742,4 @@ - if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { - return 0; // For avoid conflicts if trigger used - } - - if (is_array($this->array_languages)) { + if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used + + if (is_array($this->array_languages)) + { @@ -6697 +5748,2 @@ - foreach ($new_array_languages as $key => $value) { + foreach ($new_array_languages as $key => $value) + { @@ -6705 +5757,2 @@ - switch ($attributeType) { + switch ($attributeType) + { @@ -6707 +5760,2 @@ - if (!is_numeric($value) && $value != '') { + if (!is_numeric($value) && $value != '') + { @@ -6710 +5764,3 @@ - } elseif ($value == '') { + } + elseif ($value == '') + { @@ -6716 +5772,2 @@ - if (!is_numeric($value) && $value != '') { + if (!is_numeric($value) && $value != '') + { @@ -6720 +5777,3 @@ - } elseif ($value == '') { + } + elseif ($value == '') + { @@ -6722,2 +5780,0 @@ - } else { - $new_array_languages[$key] = $value; @@ -6724,0 +5782,2 @@ + //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG); + $new_array_languages[$key] = $value; @@ -6738,3 +5797 @@ - if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this. - $table_element = 'categories'; // For compatibility - } + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility @@ -6746,2 +5803,2 @@ - $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang"; - $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'"; + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang"; + $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'"; @@ -6752 +5809 @@ - $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value"; @@ -6757 +5814,2 @@ - if (!$resql) { + if (!$resql) + { @@ -6766 +5824,2 @@ - if (!$error && $trigger) { + if (!$error && $trigger) + { @@ -6770,3 +5829 @@ - if ($result < 0) { - $error++; - } + if ($result < 0) $error++; @@ -6776 +5833,2 @@ - if ($error) { + if ($error) + { @@ -6779 +5837,3 @@ - } else { + } + else + { @@ -6783,7 +5843,6 @@ - } 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. @@ -6800,9 +5859,5 @@ - global $conf, $langs, $user, $hookmanager; - - if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) { - return 0; - } - - if (empty($userused)) { - $userused = $user; - } + global $conf, $langs, $user; + + if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; + + if (empty($userused)) $userused = $user; @@ -6812 +5867,2 @@ - if (!empty($this->array_options) && isset($this->array_options["options_".$key])) { + if (!empty($this->array_options) && isset($this->array_options["options_".$key])) + { @@ -6821 +5876,0 @@ - $attributeKey = $key; @@ -6826,22 +5880,0 @@ - $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey]; - $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) { - $langs->load("errors"); - dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields"); - $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); - return -1; - } - } - - // $new_array_options will be used for direct update, so must contains formated data for the UPDATE. - $new_array_options = $this->array_options; @@ -6851,16 +5884,3 @@ - if (!empty($attrfieldcomputed)) { - if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) { - $value = dol_eval($attrfieldcomputed, 1, 0, '2'); - dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); - - $new_array_options["options_".$key] = $value; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } else { - $new_array_options["options_".$key] = null; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } - } - - switch ($attributeType) { + + switch ($attributeType) + { @@ -6868 +5888,2 @@ - if (!is_numeric($value) && $value != '') { + if (!is_numeric($value) && $value != '') + { @@ -6871,4 +5892,4 @@ - } elseif ($value === '') { - $new_array_options["options_".$key] = null; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; + } + elseif ($value === '') + { + $this->array_options["options_".$key] = null; @@ -6877 +5897,0 @@ - case 'price': @@ -6880 +5900,2 @@ - if (!is_numeric($value) && $value != '') { + if (!is_numeric($value) && $value != '') + { @@ -6884,2 +5905,4 @@ - } elseif ($value === '') { - $value = null; + } + elseif ($value === '') + { + $this->array_options["options_".$key] = null; @@ -6888,3 +5911 @@ - $new_array_options["options_".$key] = $value; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; + $this->array_options["options_".$key] = $value; @@ -6892,58 +5913,8 @@ - /*case 'select': // Not required, we chosed value='0' for undefined values - if ($value=='-1') - { - $new_array_options["options_".$key] = $value; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } - break;*/ - case 'password': - $algo = ''; - if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) { - // If there is an encryption choice, we use it to crypt data before insert - $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']); - $algo = reset($tmparrays); - if ($algo != '') { - //global $action; // $action may be 'create', 'update', 'update_extras'... - //var_dump($action); - //var_dump($this->oldcopy);exit; - //var_dump($key.' '.$this->array_options["options_".$key].' '.$algo); - if (is_object($this->oldcopy)) { // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value - //var_dump($this->oldcopy->array_options["options_".$key]); var_dump($this->array_options["options_".$key]); - if (isset($this->oldcopy->array_options["options_".$key]) && $this->array_options["options_".$key] == $this->oldcopy->array_options["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. - if ($algo == 'dolcrypt') { // dolibarr reversible encryption - if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { - $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master - } else { - $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept - } - } else { - $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept - } - } else { - if ($algo == 'dolcrypt') { // dolibarr reversible encryption - if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { - $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); - } else { - $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept - } - } else { - $new_array_options["options_".$key] = dol_hash($this->array_options["options_".$key], $algo); - } - } - } else { - if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { // dolibarr reversible encryption - $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master - } else { - $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept - } - } - } else { - // No encryption - $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept - } - } else { // Common usage - $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept - } - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; + /*case 'select': // Not required, we chosed value='0' for undefined values + if ($value=='-1') + { + $this->array_options[$key] = null; + } + break;*/ + case 'price': + $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); @@ -6951,0 +5923,2 @@ + $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); + break; @@ -6953,7 +5926 @@ - if (empty($this->array_options["options_".$key])) { - $new_array_options["options_".$key] = null; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } else { - $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); - } + $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); @@ -6961,24 +5927,0 @@ - case 'datetimegmt': - if (empty($this->array_options["options_".$key])) { - $new_array_options["options_".$key] = null; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } else { - $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt'); - } - break; - case 'boolean': - if (empty($this->array_options["options_".$key])) { - $new_array_options["options_".$key] = null; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } - break; - case 'link': - if ($this->array_options["options_".$key] === '') { - $new_array_options["options_".$key] = null; - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - } - break; - /* @@ -6991 +5934 @@ - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) + if ($value) @@ -6993,17 +5936,3 @@ - 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; @@ -7012,12 +5940,0 @@ - */ - case 'checkbox': - case 'chkbxlst': - $new_array_options = array(); - if (is_array($this->array_options["options_".$key])) { - $new_array_options["options_".$key] = implode(',', $this->array_options["options_".$key]); - } else { - $new_array_options["options_".$key] = $this->array_options["options_".$key]; - } - - $this->array_options["options_".$key] = $new_array_options["options_".$key]; - break; @@ -7027,10 +5944,2 @@ - - $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) - $table_element = $this->table_element; - if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this. - $table_element = 'categories'; // For compatibility - } - - $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id); + $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; @@ -7038,37 +5947,8 @@ - if ($resql) { - $tmpobj = $this->db->fetch_object($resql); - if ($tmpobj) { - $linealreadyfound = $tmpobj->nb; - } - } - - //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit; - if ($linealreadyfound) { - if ($this->array_options["options_".$key] === null) { - $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = null"; - } else { - $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = '".$this->db->escape($new_array_options["options_".$key])."'"; - } - $sql .= " WHERE fk_object = ".((int) $this->id); - - $resql = $this->db->query($sql); - if (!$resql) { - $error++; - $this->error = $this->db->lasterror(); - } - } else { - $result = $this->insertExtraFields('', $user); - if ($result < 0) { - $error++; - } - } - - if (!$error) { - $parameters = array('key'=>$key); - $reshook = $hookmanager->executeHooks('updateExtraFieldBeforeCommit', $parameters, $this, $action); - if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } - } - - if (!$error && $trigger) { + if (!$resql) + { + $error++; + $this->error = $this->db->lasterror(); + } + + if (!$error && $trigger) + { @@ -7078,3 +5958 @@ - if ($result < 0) { - $error++; - } + if ($result < 0) $error++; @@ -7084 +5962,2 @@ - if ($error) { + if ($error) + { @@ -7088 +5967,3 @@ - } else { + } + else + { @@ -7092,3 +5973,2 @@ - } else { - return 0; - } + } + else return 0; @@ -7105 +5985 @@ - * @see updateExtraField(), insertExtraLanguages() + * @see updateExtraFields(), insertExtraLanguages() @@ -7111,3 +5991 @@ - if (empty($userused)) { - $userused = $user; - } + if (empty($userused)) $userused = $user; @@ -7117,3 +5995 @@ - if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) { - return 0; // For avoid conflicts if trigger used - } + if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) return 0; // For avoid conflicts if trigger used @@ -7129 +6005 @@ - * @param array|null $val Array of properties for field to show (used only if ->fields not defined) + * @param array $val Array of properties for field to show (used only if ->fields not defined) @@ -7131 +6007 @@ - * @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) @@ -7143 +6019,2 @@ - if (!is_object($form)) { + if (!is_object($form)) + { @@ -7152,10 +6028,0 @@ - // Validation tests and output - $fieldValidationErrorMsg = ''; - $validationClass = ''; - $fieldValidationErrorMsg = $this->getFieldError($key); - if (!empty($fieldValidationErrorMsg)) { - $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error - } else { - $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success - } - @@ -7163,46 +6030,32 @@ - $type = ''; - $isDependList = 0; - $param = array(); - $param['options'] = array(); - $reg = array(); - $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0; - // 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('/^chkbxlst:(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[1] => 'N'); - $type = 'chkbxlst'; - } 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'; - } else { - $param['options'] = array(); - $type = $this->fields[$key]['type']; - } - //var_dump($type); var_dump($param['options']); - - // Special case that force options and type ($type can be integer, varchar, ...) - if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) { - $param['options'] = $this->fields[$key]['arrayofkeyval']; - $type = (($this->fields[$key]['type']=='checkbox') ? $this->fields[$key]['type'] : 'select'); - } + $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']; + } @@ -7212,8 +6065,8 @@ - $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : ''); - $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : ''); - $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0); - $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0); - $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0); - - $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : ''); - $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0); + $default = $this->fields[$key]['default']; + $computed = $this->fields[$key]['computed']; + $unique = $this->fields[$key]['unique']; + $required = $this->fields[$key]['required']; + $autofocusoncreate = $this->fields[$key]['autofocusoncreate']; + + $langfile = $this->fields[$key]['langfile']; + $list = $this->fields[$key]['list']; @@ -7224,6 +6077,4 @@ - if ($computed) { - if (!preg_match('/^search_/', $keyprefix)) { - return ''.$langs->trans("AutomaticallyCalculated").''; - } else { - return ''; - } + if ($computed) + { + if (!preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + else return ''; @@ -7233,4 +6084,8 @@ - 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') + { @@ -7238 +6093,3 @@ - } 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 + { @@ -7240 +6097,3 @@ - } 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)) + { @@ -7244 +6103,3 @@ - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { @@ -7246,2 +6107,5 @@ - } else { - if (round($size) < 12) { + } + else + { + if (round($size) < 12) + { @@ -7249 +6113,3 @@ - } elseif (round($size) <= 48) { + } + elseif (round($size) <= 48) + { @@ -7251 +6117,3 @@ - } else { + } + else + { @@ -7257,6 +6125,2 @@ - // Add validation state class - if (!empty($validationClass)) { - $morecss.= $validationClass; - } - - if (in_array($type, array('date'))) { + if (in_array($type, array('date', 'datetime'))) + { @@ -7265 +6129,2 @@ - $showtime = 0; + + $showtime = in_array($type, array('datetime')) ? 1 : 0; @@ -7268,3 +6133 @@ - if (!$required && $value == '') { - $value = '-1'; - } + if (!$required && $value == '') $value = '-1'; @@ -7274 +6137,7 @@ - } 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'))) + { @@ -7277,23 +6146,18 @@ - $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 = ' 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>'; - } elseif (in_array($type, array('real'))) { - $out = ''; - } elseif (preg_match('/varchar/', $type)) { - $out = ' 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>'; - } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) { - $out = ''; - } elseif (preg_match('/^text/', $type)) { - if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field + $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 + { @@ -7303 +6167,3 @@ - } else { + } + else + { @@ -7306,2 +6172,5 @@ - } 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 + { @@ -7309,3 +6178,5 @@ - $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); - $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss); - } else { + $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 + { @@ -7314 +6185,3 @@ - } elseif ($type == 'boolean') { + } + elseif ($type == 'boolean') + { @@ -7322 +6195,3 @@ - } elseif ($type == 'price') { + } + elseif ($type == 'price') + { @@ -7327 +6202,3 @@ - } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) { + } + elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) + { @@ -7332 +6209,3 @@ - } elseif ($type == 'select') { // combo list + } + elseif ($type == 'select') + { @@ -7334 +6213,2 @@ - if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) { + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { @@ -7340,15 +6220,7 @@ - if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) { - $out .= ''; - } - foreach ($param['options'] as $keyb => $valb) { - if ((string) $keyb == '') { - continue; - } - if (strpos($valb, "|") !== false) { - list($valb, $parent) = explode('|', $valb); - } - $out .= ''; + foreach ($param['options'] as $key => $val) + { + if ((string) $key == '') continue; + list($val, $parent) = explode('|', $val); + $out .= ''; + $out .= '>'.$val.''; @@ -7359 +6231,3 @@ - } elseif ($type == 'sellist') { + } + elseif ($type == 'sellist') + { @@ -7361 +6235,2 @@ - if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) { + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { @@ -7367 +6242,2 @@ - if (is_array($param['options'])) { + if (is_array($param['options'])) + { @@ -7369,22 +6245 @@ - $InfoFieldList = explode(":", $param_list[0], 5); - if (! empty($InfoFieldList[4])) { - $pos = 0; - $parenthesisopen = 0; - while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) { - if (substr($InfoFieldList[4], $pos, 1) == '(') { - $parenthesisopen++; - } - if (substr($InfoFieldList[4], $pos, 1) == ')') { - $parenthesisopen--; - } - $pos++; - } - $tmpbefore = substr($InfoFieldList[4], 0, $pos); - $tmpafter = substr($InfoFieldList[4], $pos+1); - //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter); - $InfoFieldList[4] = $tmpbefore; - if ($tmpafter !== '') { - $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter)); - } - //var_dump($InfoFieldList); - } + $InfoFieldList = explode(":", $param_list[0]); @@ -7393 +6247,0 @@ - @@ -7399,3 +6252,0 @@ - // 5 : id category type - // 6 : ids categories list separated by comma for category root - // 7 : sort field @@ -7404,2 +6255,5 @@ - if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { - if (strpos($InfoFieldList[4], 'extra.') !== false) { + + if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) + { + if (strpos($InfoFieldList[4], 'extra.') !== false) + { @@ -7411 +6265,2 @@ - if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) { + if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) + { @@ -7416,21 +6271,70 @@ - $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 " . $this->db->prefix() . $InfoFieldList[0]; - if (!empty($InfoFieldList[4])) { - // can use SELECT request - if (strpos($InfoFieldList[4], '$SEL$') !== false) { - $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); + $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 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 (count($fields_label) > 1) + { + $notrans = true; + foreach ($fields_label as $field_toshow) + { + $labeltoshow .= $obj->$field_toshow.' '; + } @@ -7438,6 +6342,3 @@ - - // 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]); + else + { + $labeltoshow = $obj->{$InfoFieldList[1]}; @@ -7445,9 +6346,14 @@ - - // We have to join on extrafield table - $errstr = ''; - if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra"; - $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2]; - $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1); - } else { - $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1); + $labeltoshow = dol_trunc($labeltoshow, 45); + + if ($value == $obj->rowid) + { + foreach ($fields_label as $field_toshow) + { + $translabel = $langs->trans($obj->$field_toshow); + if ($translabel != $obj->$field_toshow) { + $labeltoshow = dol_trunc($translabel, 18).' '; + } else { + $labeltoshow = dol_trunc($obj->$field_toshow, 18).' '; + } + } + $out .= ''; @@ -7455,34 +6361,7 @@ - } 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 = " . ((int) $conf->entity); - } - $sql .= $sqlwhere; - //print $sql; - - // Note: $InfoFieldList can be 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:Sortfield]]]]]]' - if (isset($InfoFieldList[7]) && preg_match('/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) { - $sql .= " ORDER BY ".$this->db->escape($InfoFieldList[7]); - } else { - $sql .= " ORDER BY ".$this->db->sanitize(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 (count($fields_label) > 1) { - $notrans = true; - foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow . ' '; + else + { + if (!$notrans) + { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + if ($translabel != $obj->{$InfoFieldList[1]}) { + $labeltoshow = dol_trunc($translabel, 18); @@ -7490,2 +6369,3 @@ - } else { - $labeltoshow = $obj->{$InfoFieldList[1]}; + else { + $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); + } @@ -7493,37 +6373,4 @@ - $labeltoshow = dol_trunc($labeltoshow, 45); - - if ($value == $obj->rowid) { - foreach ($fields_label as $field_toshow) { - $translabel = $langs->trans($obj->$field_toshow); - if ($translabel != $obj->$field_toshow) { - $labeltoshow = dol_trunc($translabel) . ' '; - } else { - $labeltoshow = dol_trunc($obj->$field_toshow) . ' '; - } - } - $out .= ''; - } else { - if (!$notrans) { - $translabel = $langs->trans($obj->{$InfoFieldList[1]}); - if ($translabel != $obj->{$InfoFieldList[1]}) { - $labeltoshow = dol_trunc($translabel, 18); - } else { - $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}); - } - } - if (empty($labeltoshow)) { - $labeltoshow = '(not defined)'; - } - if ($value == $obj->rowid) { - $out .= ''; - } - - if (!empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName . ':' . $obj->{$parentField}; - $isDependList = 1; - } - - $out .= ''; + if (empty($labeltoshow)) $labeltoshow = '(not defined)'; + if ($value == $obj->rowid) + { + $out .= ''; @@ -7532 +6379,9 @@ - $i++; + if (!empty($InfoFieldList[3]) && $parentField) + { + $parent = $parentName.':'.$obj->{$parentField}; + } + + $out .= ''; @@ -7534,13 +6389,7 @@ - $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 .= '