From a34b99f3ec86ae472d6c3701d870f71ac9efab5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 21 Jan 2018 15:55:56 +0100 Subject: [PATCH 01/91] swiftmailer --- htdocs/core/class/CMailFile.class.php | 48 +- htdocs/core/class/notify.class.php | 51 ++- .../EmailValidator/EmailLexer.php | 221 +++++++++ .../EmailValidator/EmailParser.php | 104 +++++ .../EmailValidator/EmailValidator.php | 67 +++ .../Exception/AtextAfterCFWS.php | 9 + .../EmailValidator/Exception/CRLFAtTheEnd.php | 9 + .../EmailValidator/Exception/CRLFX2.php | 9 + .../EmailValidator/Exception/CRNoLF.php | 9 + .../Exception/CharNotAllowed.php | 9 + .../Exception/CommaInDomain.php | 9 + .../Exception/ConsecutiveAt.php | 9 + .../Exception/ConsecutiveDot.php | 9 + .../Exception/DomainHyphened.php | 9 + .../EmailValidator/Exception/DotAtEnd.php | 9 + .../EmailValidator/Exception/DotAtStart.php | 9 + .../EmailValidator/Exception/ExpectingAT.php | 9 + .../Exception/ExpectingATEXT.php | 9 + .../Exception/ExpectingCTEXT.php | 9 + .../Exception/ExpectingDTEXT.php | 9 + .../Exception/ExpectingDomainLiteralClose.php | 9 + .../Exception/ExpectingQPair.php | 9 + .../EmailValidator/Exception/InvalidEmail.php | 14 + .../EmailValidator/Exception/NoDNSRecord.php | 11 + .../EmailValidator/Exception/NoDomainPart.php | 9 + .../EmailValidator/Exception/NoLocalPart.php | 9 + .../Exception/UnclosedComment.php | 9 + .../Exception/UnclosedQuotedString.php | 9 + .../Exception/UnopenedComment.php | 9 + .../EmailValidator/Parser/DomainPart.php | 368 +++++++++++++++ .../EmailValidator/Parser/LocalPart.php | 138 ++++++ .../EmailValidator/Parser/Parser.php | 215 +++++++++ .../Validation/DNSCheckValidation.php | 61 +++ .../Validation/EmailValidation.php | 34 ++ .../Validation/Error/RFCWarnings.php | 11 + .../Validation/Error/SpoofEmail.php | 11 + .../Exception/EmptyValidationList.php | 13 + .../Validation/MultipleErrors.php | 26 ++ .../Validation/MultipleValidationWithAnd.php | 110 +++++ .../Validation/NoRFCWarningsValidation.php | 41 ++ .../Validation/RFCValidation.php | 49 ++ .../Validation/SpoofCheckValidation.php | 45 ++ .../EmailValidator/Warning/AddressLiteral.php | 14 + .../EmailValidator/Warning/CFWSNearAt.php | 13 + .../EmailValidator/Warning/CFWSWithFWS.php | 13 + .../EmailValidator/Warning/Comment.php | 13 + .../Warning/DeprecatedComment.php | 13 + .../EmailValidator/Warning/DomainLiteral.php | 14 + .../EmailValidator/Warning/DomainTooLong.php | 14 + .../EmailValidator/Warning/EmailTooLong.php | 15 + .../EmailValidator/Warning/IPV6BadChar.php | 14 + .../EmailValidator/Warning/IPV6ColonEnd.php | 14 + .../EmailValidator/Warning/IPV6ColonStart.php | 14 + .../EmailValidator/Warning/IPV6Deprecated.php | 14 + .../Warning/IPV6DoubleColon.php | 14 + .../EmailValidator/Warning/IPV6GroupCount.php | 14 + .../EmailValidator/Warning/IPV6MaxGroups.php | 14 + .../EmailValidator/Warning/LabelTooLong.php | 14 + .../EmailValidator/Warning/LocalTooLong.php | 15 + .../EmailValidator/Warning/NoDNSMXRecord.php | 14 + .../EmailValidator/Warning/ObsoleteDTEXT.php | 14 + .../EmailValidator/Warning/QuotedPart.php | 13 + .../EmailValidator/Warning/QuotedString.php | 13 + .../EmailValidator/Warning/TLD.php | 13 + .../EmailValidator/Warning/Warning.php | 30 ++ .../includes/egulias/email-validator/LICENSE | 19 + .../egulias/email-validator/README.md | 79 ++++ htdocs/includes/lexer/LICENSE | 19 + htdocs/includes/lexer/README.md | 5 + htdocs/includes/lexer/composer.json | 24 + .../Doctrine/Common/Lexer/AbstractLexer.php | 327 ++++++++++++++ .../swiftmailer/lib/classes/Swift.php | 5 +- .../lib/classes/Swift/Attachment.php | 20 +- .../AbstractFilterableInputStream.php | 58 +-- .../Swift/ByteStream/ArrayByteStream.php | 52 +-- .../Swift/ByteStream/FileByteStream.php | 131 +++--- .../lib/classes/Swift/CharacterReader.php | 4 +- .../GenericFixedWidthReader.php | 20 +- .../Swift/CharacterReader/Utf8Reader.php | 32 +- .../SimpleCharacterReaderFactory.php | 46 +- .../CharacterStream/ArrayCharacterStream.php | 114 ++--- .../CharacterStream/NgCharacterStream.php | 104 ++--- .../lib/classes/Swift/ConfigurableSpool.php | 12 +- .../lib/classes/Swift/DependencyContainer.php | 110 ++--- .../lib/classes/Swift/EmbeddedFile.php | 18 +- .../lib/classes/Swift/Encoder/QpEncoder.php | 76 ++-- .../classes/Swift/Encoder/Rfc2231Encoder.php | 14 +- .../lib/classes/Swift/Encoding.php | 64 --- .../lib/classes/Swift/Events/CommandEvent.php | 16 +- .../classes/Swift/Events/EventDispatcher.php | 4 +- .../lib/classes/Swift/Events/EventObject.php | 12 +- .../classes/Swift/Events/ResponseEvent.php | 12 +- .../lib/classes/Swift/Events/SendEvent.php | 30 +- .../Swift/Events/SimpleEventDispatcher.php | 38 +- .../Swift/Events/TransportExceptionEvent.php | 6 +- .../lib/classes/Swift/FailoverTransport.php | 12 - .../lib/classes/Swift/FileSpool.php | 32 +- .../lib/classes/Swift/IdGenerator.php | 22 + .../swiftmailer/lib/classes/Swift/Image.php | 22 +- .../classes/Swift/KeyCache/ArrayKeyCache.php | 42 +- .../classes/Swift/KeyCache/DiskKeyCache.php | 105 ++--- .../KeyCache/SimpleKeyCacheInputStream.php | 28 +- .../classes/Swift/LoadBalancedTransport.php | 12 - .../lib/classes/Swift/MailTransport.php | 45 -- .../swiftmailer/lib/classes/Swift/Mailer.php | 34 +- .../Swift/Mailer/ArrayRecipientIterator.php | 8 +- .../lib/classes/Swift/MemorySpool.php | 34 +- .../swiftmailer/lib/classes/Swift/Message.php | 35 +- .../lib/classes/Swift/Mime/Attachment.php | 44 +- .../ContentEncoder/NativeQpContentEncoder.php | 4 +- .../ContentEncoder/PlainContentEncoder.php | 26 +- .../Mime/ContentEncoder/QpContentEncoder.php | 34 +- .../lib/classes/Swift/Mime/EmbeddedFile.php | 14 +- .../lib/classes/Swift/Mime/Grammar.php | 176 -------- .../Mime/HeaderEncoder/QpHeaderEncoder.php | 2 +- .../lib/classes/Swift/Mime/HeaderFactory.php | 78 ---- .../lib/classes/Swift/Mime/HeaderSet.php | 169 ------- .../Swift/Mime/Headers/AbstractHeader.php | 146 +++--- .../classes/Swift/Mime/Headers/DateHeader.php | 62 ++- .../Mime/Headers/IdentificationHeader.php | 46 +- .../Swift/Mime/Headers/MailboxHeader.php | 65 +-- .../Swift/Mime/Headers/OpenDKIMHeader.php | 22 +- .../Mime/Headers/ParameterizedHeader.php | 53 ++- .../classes/Swift/Mime/Headers/PathHeader.php | 43 +- .../Swift/Mime/Headers/UnstructuredHeader.php | 14 +- .../lib/classes/Swift/Mime/IdGenerator.php | 53 +++ .../lib/classes/Swift/Mime/Message.php | 223 ---------- .../lib/classes/Swift/Mime/MimeEntity.php | 117 ----- .../lib/classes/Swift/Mime/MimePart.php | 82 ++-- .../Swift/Mime/ParameterizedHeader.php | 34 -- .../Swift/Mime/SimpleHeaderFactory.php | 84 ++-- .../classes/Swift/Mime/SimpleHeaderSet.php | 156 ++++--- .../lib/classes/Swift/Mime/SimpleMessage.php | 162 +++---- .../classes/Swift/Mime/SimpleMimeEntity.php | 418 +++++++++--------- .../lib/classes/Swift/MimePart.php | 14 - .../lib/classes/Swift/NullTransport.php | 13 - .../classes/Swift/Plugins/AntiFloodPlugin.php | 32 +- .../Swift/Plugins/BandwidthMonitorPlugin.php | 30 +- .../classes/Swift/Plugins/DecoratorPlugin.php | 62 +-- .../Swift/Plugins/ImpersonatePlugin.php | 8 +- .../classes/Swift/Plugins/LoggerPlugin.php | 28 +- .../Swift/Plugins/Loggers/ArrayLogger.php | 16 +- .../Swift/Plugins/Loggers/EchoLogger.php | 6 +- .../classes/Swift/Plugins/MessageLogger.php | 4 +- .../Swift/Plugins/PopBeforeSmtpPlugin.php | 112 ++--- .../Swift/Plugins/RedirectingPlugin.php | 48 +- .../lib/classes/Swift/Plugins/Reporter.php | 8 +- .../classes/Swift/Plugins/ReporterPlugin.php | 10 +- .../Swift/Plugins/Reporters/HitReporter.php | 22 +- .../Swift/Plugins/Reporters/HtmlReporter.php | 8 +- .../classes/Swift/Plugins/ThrottlerPlugin.php | 64 +-- .../lib/classes/Swift/Preferences.php | 27 +- .../lib/classes/Swift/SendmailTransport.php | 12 - .../lib/classes/Swift/SignedMessage.php | 23 - .../lib/classes/Swift/Signers/BodySigner.php | 2 +- .../lib/classes/Swift/Signers/DKIMSigner.php | 364 ++++++++------- .../classes/Swift/Signers/DomainKeySigner.php | 239 +++++----- .../classes/Swift/Signers/HeaderSigner.php | 16 +- .../classes/Swift/Signers/OpenDKIMSigner.php | 77 ++-- .../lib/classes/Swift/Signers/SMimeSigner.php | 41 +- .../lib/classes/Swift/SmtpTransport.php | 16 +- .../swiftmailer/lib/classes/Swift/Spool.php | 4 +- .../lib/classes/Swift/SpoolTransport.php | 12 - .../ByteArrayReplacementFilter.php | 61 +-- .../StreamFilters/StringReplacementFilter.php | 16 +- .../StringReplacementFilterFactory.php | 16 +- .../lib/classes/Swift/Transport.php | 27 +- .../Swift/Transport/AbstractSmtpTransport.php | 233 +++++----- .../Esmtp/Auth/CramMd5Authenticator.php | 4 +- .../Esmtp/Auth/NTLMAuthenticator.php | 94 ++-- .../Esmtp/Auth/XOAuth2Authenticator.php | 2 +- .../Swift/Transport/Esmtp/AuthHandler.php | 46 +- .../Swift/Transport/EsmtpTransport.php | 133 +++--- .../Swift/Transport/FailoverTransport.php | 56 ++- .../Swift/Transport/LoadBalancedTransport.php | 69 +-- .../classes/Swift/Transport/MailInvoker.php | 32 -- .../classes/Swift/Transport/MailTransport.php | 239 ---------- .../classes/Swift/Transport/NullTransport.php | 24 +- .../Swift/Transport/SendmailTransport.php | 33 +- .../Swift/Transport/SimpleMailInvoker.php | 39 -- .../Swift/Transport/SpoolTransport.php | 36 +- .../classes/Swift/Transport/StreamBuffer.php | 167 +++---- .../lib/classes/Swift/Validate.php | 43 -- .../lib/dependency_maps/mime_deps.php | 35 +- .../lib/dependency_maps/transport_deps.php | 15 +- .../includes/swiftmailer/lib/mime_types.php | 2 +- .../includes/swiftmailer/lib/preferences.php | 6 - .../includes/swiftmailer/lib/swift_init.php | 28 -- .../swiftmailer/lib/swift_required.php | 28 +- .../swiftmailer/lib/swift_required_pear.php | 30 -- .../lib/swiftmailer_generate_mimes_config.php | 8 +- 191 files changed, 5164 insertions(+), 4074 deletions(-) create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFX2.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRNoLF.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtStart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php create mode 100644 htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php create mode 100644 htdocs/includes/egulias/email-validator/LICENSE create mode 100644 htdocs/includes/egulias/email-validator/README.md create mode 100644 htdocs/includes/lexer/LICENSE create mode 100644 htdocs/includes/lexer/README.md create mode 100644 htdocs/includes/lexer/composer.json create mode 100644 htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php create mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderSet.php create mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailTransport.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php delete mode 100644 htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php delete mode 100644 htdocs/includes/swiftmailer/lib/swift_init.php delete mode 100644 htdocs/includes/swiftmailer/lib/swift_required_pear.php mode change 100644 => 100755 htdocs/includes/swiftmailer/lib/swiftmailer_generate_mimes_config.php diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 86a6cb008d3..25988fd801d 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -80,14 +80,16 @@ class CMailFile var $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). var $html_images=array(); var $images_encoded=array(); - var $image_types = array('gif' => 'image/gif', - 'jpg' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'bmp' => 'image/bmp', - 'png' => 'image/png', - 'tif' => 'image/tiff', - 'tiff' => 'image/tiff'); + var $image_types = array( + 'gif' => 'image/gif', + 'jpg' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'bmp' => 'image/bmp', + 'png' => 'image/png', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + ); /** @@ -395,9 +397,21 @@ class CMailFile $host = dol_getprefix('email'); + require_once DOL_DOCUMENT_ROOT.'/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/Warning.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/Parser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Create the message - $this->message = Swift_Message::newInstance(); + //$this->message = Swift_Message::newInstance(); + $this->message = new Swift_Message(); // Adding a trackid header to a message $headers = $this->message->getHeaders(); @@ -449,11 +463,11 @@ class CMailFile if ($this->msgishtml) { $this->message->setBody($msg,'text/html'); // And optionally an alternative body - //$this->message->addPart('Here is the message itself', 'text/plain'); + $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain'); } else { $this->message->setBody($msg,'text/plain'); // And optionally an alternative body - //$this->message->addPart('Here is the message itself', 'text/html'); + $this->message->addPart($msg, 'text/html'); } if ($this->atleastonefile) @@ -491,7 +505,7 @@ class CMailFile global $conf,$db,$langs; $errorlevel=error_reporting(); - error_reporting($errorlevel ^ E_WARNING); // Desactive warnings + //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings $res=false; @@ -721,19 +735,19 @@ class CMailFile if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); // If we use SSL/TLS - $server=$conf->global->$keyforsmtpserver; - $secure=''; + $server = $conf->global->$keyforsmtpserver; + $secure = ''; if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; - $this->transport = Swift_SmtpTransport::newInstance($server, $conf->global->$keyforsmtpport, $secure); + $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); //$smtps->_msgReplyTo = 'reply@web.com'; // Create the Mailer using your created Transport - $this->mailer = Swift_Mailer::newInstance($this->transport); + $this->mailer = new Swift_Mailer($this->transport); if (! empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger @@ -751,7 +765,7 @@ class CMailFile if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); $res = true; - if (! empty($this->error) && ! $result) { + if (! empty($this->error) || ! $result) { dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res=false; } else { diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php index d40fcadc17c..2cd919db296 100644 --- a/htdocs/core/class/notify.class.php +++ b/htdocs/core/class/notify.class.php @@ -460,7 +460,7 @@ class Notify $message.= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; $message.= "\n"; $message.= $mesg; - if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); + if ($link) $message.= "\n" . $urlwithroot . $link; $parameters=array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$file, 'mimefile'=>$mimefile, 'filename'=>$filename); $reshook=$hookmanager->executeHooks('formatNotificationMessage',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -555,77 +555,77 @@ class Notify switch ($notifcode) { case 'BILL_VALIDATE': - $link='/compta/facture/card.php?facid='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'facture'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$link); break; case 'BILL_PAYED': - $link='/compta/facture/card.php?facid='.$object->id; + $link ='' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'facture'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInvoicePayed",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInvoicePayed",$link); break; case 'ORDER_VALIDATE': - $link='/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->commande->dir_output; $object_type = 'order'; - $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$link); break; case 'PROPAL_VALIDATE': - $link='/comm/propal/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->propal->dir_output; $object_type = 'propal'; - $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$link); break; case 'PROPAL_CLOSE_SIGNED': - $link='/comm/propal/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->propal->dir_output; $object_type = 'propal'; - $mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned",$link); break; case 'FICHINTER_ADD_CONTACT': - $link='/fichinter/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'ficheinter'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact",$link); break; case 'FICHINTER_VALIDATE': - $link='/fichinter/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->facture->dir_output; $object_type = 'ficheinter'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$newref); + $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$link); break; case 'ORDER_SUPPLIER_VALIDATE': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'ORDER_SUPPLIER_APPROVE': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'ORDER_SUPPLIER_APPROVE2': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'ORDER_SUPPLIER_REFUSE': - $link='/fourn/commande/card.php?id='.$object->id; + $link = '' . $newref . ''; $dir_output = $conf->fournisseur->dir_output.'/commande/'; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$newref,$user->getFullName($langs)); + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$link,$user->getFullName($langs)); $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; break; case 'SHIPPING_VALIDATE': @@ -650,7 +650,7 @@ class Notify $message.= $langs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; $message.= "\n"; $message.= $mesg; - if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); + $message = nl2br($message); // Replace keyword __SUPERVISOREMAIL__ if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) @@ -677,7 +677,6 @@ class Notify if (! empty($hookmanager->resArray['subject'])) $subject.=$hookmanager->resArray['subject']; if (! empty($hookmanager->resArray['message'])) $message.=$hookmanager->resArray['message']; } - $mailfile = new CMailFile( $subject, $sendto, @@ -689,7 +688,7 @@ class Notify '', '', 0, - -1 + 1 ); if ($mailfile->sendfile()) diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php b/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php new file mode 100644 index 00000000000..882c968154d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php @@ -0,0 +1,221 @@ + self::S_OPENPARENTHESIS, + ')' => self::S_CLOSEPARENTHESIS, + '<' => self::S_LOWERTHAN, + '>' => self::S_GREATERTHAN, + '[' => self::S_OPENBRACKET, + ']' => self::S_CLOSEBRACKET, + ':' => self::S_COLON, + ';' => self::S_SEMICOLON, + '@' => self::S_AT, + '\\' => self::S_BACKSLASH, + '/' => self::S_SLASH, + ',' => self::S_COMMA, + '.' => self::S_DOT, + '"' => self::S_DQUOTE, + '-' => self::S_HYPHEN, + '::' => self::S_DOUBLECOLON, + ' ' => self::S_SP, + "\t" => self::S_HTAB, + "\r" => self::S_CR, + "\n" => self::S_LF, + "\r\n" => self::CRLF, + 'IPv6' => self::S_IPV6TAG, + '{' => self::S_OPENQBRACKET, + '}' => self::S_CLOSEQBRACKET, + '' => self::S_EMPTY, + '\0' => self::C_NUL, + ); + + protected $hasInvalidTokens = false; + + protected $previous; + + public function reset() + { + $this->hasInvalidTokens = false; + parent::reset(); + } + + public function hasInvalidTokens() + { + return $this->hasInvalidTokens; + } + + /** + * @param $type + * @throws \UnexpectedValueException + * @return boolean + */ + public function find($type) + { + $search = clone $this; + $search->skipUntil($type); + + if (!$search->lookahead) { + throw new \UnexpectedValueException($type . ' not found'); + } + return true; + } + + /** + * getPrevious + * + * @return array token + */ + public function getPrevious() + { + return $this->previous; + } + + /** + * moveNext + * + * @return boolean + */ + public function moveNext() + { + $this->previous = $this->token; + + return parent::moveNext(); + } + + /** + * Lexical catchable patterns. + * + * @return string[] + */ + protected function getCatchablePatterns() + { + return array( + '[a-zA-Z_]+[46]?', //ASCII and domain literal + '[^\x00-\x7F]', //UTF-8 + '[0-9]+', + '\r\n', + '::', + '\s+?', + '.', + ); + } + + /** + * Lexical non-catchable patterns. + * + * @return string[] + */ + protected function getNonCatchablePatterns() + { + return array('[\xA0-\xff]+'); + } + + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @param string $value + * @throws \InvalidArgumentException + * @return integer + */ + protected function getType(&$value) + { + if ($this->isNullType($value)) { + return self::C_NUL; + } + + if ($this->isValid($value)) { + return $this->charValue[$value]; + } + + if ($this->isUTF8Invalid($value)) { + $this->hasInvalidTokens = true; + return self::INVALID; + } + + return self::GENERIC; + } + + protected function isValid($value) + { + if (isset($this->charValue[$value])) { + return true; + } + + return false; + } + + /** + * @param $value + * @return bool + */ + protected function isNullType($value) + { + if ($value === "\0") { + return true; + } + + return false; + } + + /** + * @param $value + * @return bool + */ + protected function isUTF8Invalid($value) + { + if (preg_match('/\p{Cc}+/u', $value)) { + return true; + } + + return false; + } + + protected function getModifiers() + { + return 'iu'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php b/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php new file mode 100644 index 00000000000..d0627d82410 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php @@ -0,0 +1,104 @@ + + */ +class EmailParser +{ + const EMAIL_MAX_LENGTH = 254; + + protected $warnings; + protected $domainPart = ''; + protected $localPart = ''; + protected $lexer; + protected $localPartParser; + protected $domainPartParser; + + public function __construct(EmailLexer $lexer) + { + $this->lexer = $lexer; + $this->localPartParser = new LocalPart($this->lexer); + $this->domainPartParser = new DomainPart($this->lexer); + $this->warnings = new \SplObjectStorage(); + } + + /** + * @param $str + * @return array + */ + public function parse($str) + { + $this->lexer->setInput($str); + + if (!$this->hasAtToken()) { + throw new NoLocalPart(); + } + + + $this->localPartParser->parse($str); + $this->domainPartParser->parse($str); + + $this->setParts($str); + + if ($this->lexer->hasInvalidTokens()) { + throw new ExpectingATEXT(); + } + + return array('local' => $this->localPart, 'domain' => $this->domainPart); + } + + public function getWarnings() + { + $localPartWarnings = $this->localPartParser->getWarnings(); + $domainPartWarnings = $this->domainPartParser->getWarnings(); + $this->warnings = array_merge($localPartWarnings, $domainPartWarnings); + + $this->addLongEmailWarning($this->localPart, $this->domainPart); + + return $this->warnings; + } + + public function getParsedDomainPart() + { + return $this->domainPart; + } + + protected function setParts($email) + { + $parts = explode('@', $email); + $this->domainPart = $this->domainPartParser->getDomainPart(); + $this->localPart = $parts[0]; + } + + protected function hasAtToken() + { + $this->lexer->moveNext(); + $this->lexer->moveNext(); + if ($this->lexer->token['type'] === EmailLexer::S_AT) { + return false; + } + + return true; + } + + /** + * @param string $localPart + * @param string $parsedDomainPart + */ + protected function addLongEmailWarning($localPart, $parsedDomainPart) + { + if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) { + $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php b/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php new file mode 100644 index 00000000000..44b4b93c6bb --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php @@ -0,0 +1,67 @@ +lexer = new EmailLexer(); + } + + /** + * @param $email + * @param EmailValidation $emailValidation + * @return bool + */ + public function isValid($email, EmailValidation $emailValidation) + { + $isValid = $emailValidation->isValid($email, $this->lexer); + $this->warnings = $emailValidation->getWarnings(); + $this->error = $emailValidation->getError(); + + return $isValid; + } + + /** + * @return boolean + */ + public function hasWarnings() + { + return !empty($this->warnings); + } + + /** + * @return array + */ + public function getWarnings() + { + return $this->warnings; + } + + /** + * @return InvalidEmail + */ + public function getError() + { + return $this->error; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php b/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php new file mode 100644 index 00000000000..97f41a2caae --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php @@ -0,0 +1,9 @@ +lexer->moveNext(); + + if ($this->lexer->token['type'] === EmailLexer::S_DOT) { + throw new DotAtStart(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_EMPTY) { + throw new NoDomainPart(); + } + if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) { + throw new DomainHyphened(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->warnings[DeprecatedComment::CODE] = new DeprecatedComment(); + $this->parseDomainComments(); + } + + $domain = $this->doParseDomainPart(); + + $prev = $this->lexer->getPrevious(); + $length = strlen($domain); + + if ($prev['type'] === EmailLexer::S_DOT) { + throw new DotAtEnd(); + } + if ($prev['type'] === EmailLexer::S_HYPHEN) { + throw new DomainHyphened(); + } + if ($length > self::DOMAIN_MAX_LENGTH) { + $this->warnings[DomainTooLong::CODE] = new DomainTooLong(); + } + if ($prev['type'] === EmailLexer::S_CR) { + throw new CRLFAtTheEnd(); + } + $this->domainPart = $domain; + } + + public function getDomainPart() + { + return $this->domainPart; + } + + public function checkIPV6Tag($addressLiteral, $maxGroups = 8) + { + $prev = $this->lexer->getPrevious(); + if ($prev['type'] === EmailLexer::S_COLON) { + $this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd(); + } + + $IPv6 = substr($addressLiteral, 5); + //Daniel Marschall's new IPv6 testing strategy + $matchesIP = explode(':', $IPv6); + $groupCount = count($matchesIP); + $colons = strpos($IPv6, '::'); + + if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) { + $this->warnings[IPV6BadChar::CODE] = new IPV6BadChar(); + } + + if ($colons === false) { + // We need exactly the right number of groups + if ($groupCount !== $maxGroups) { + $this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount(); + } + return; + } + + if ($colons !== strrpos($IPv6, '::')) { + $this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon(); + return; + } + + if ($colons === 0 || $colons === (strlen($IPv6) - 2)) { + // RFC 4291 allows :: at the start or end of an address + //with 7 other groups in addition + ++$maxGroups; + } + + if ($groupCount > $maxGroups) { + $this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups(); + } elseif ($groupCount === $maxGroups) { + $this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated(); + } + } + + protected function doParseDomainPart() + { + $domain = ''; + $openedParenthesis = 0; + do { + $prev = $this->lexer->getPrevious(); + + $this->checkNotAllowedChars($this->lexer->token); + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->parseComments(); + $openedParenthesis += $this->getOpenedParenthesis(); + $this->lexer->moveNext(); + $tmpPrev = $this->lexer->getPrevious(); + if ($tmpPrev['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + $openedParenthesis--; + } + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + if ($openedParenthesis === 0) { + throw new UnopenedComment(); + } else { + $openedParenthesis--; + } + } + + $this->checkConsecutiveDots(); + $this->checkDomainPartExceptions($prev); + + if ($this->hasBrackets()) { + $this->parseDomainLiteral(); + } + + $this->checkLabelLength($prev); + + if ($this->isFWS()) { + $this->parseFWS(); + } + + $domain .= $this->lexer->token['value']; + $this->lexer->moveNext(); + } while ($this->lexer->token); + + return $domain; + } + + private function checkNotAllowedChars($token) + { + $notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH=> true]; + if (isset($notAllowed[$token['type']])) { + throw new CharNotAllowed(); + } + } + + protected function parseDomainLiteral() + { + if ($this->lexer->isNextToken(EmailLexer::S_COLON)) { + $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); + } + if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) { + $lexer = clone $this->lexer; + $lexer->moveNext(); + if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) { + $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); + } + } + + return $this->doParseDomainLiteral(); + } + + protected function doParseDomainLiteral() + { + $IPv6TAG = false; + $addressLiteral = ''; + do { + if ($this->lexer->token['type'] === EmailLexer::C_NUL) { + throw new ExpectingDTEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::INVALID || + $this->lexer->token['type'] === EmailLexer::C_DEL || + $this->lexer->token['type'] === EmailLexer::S_LF + ) { + $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); + } + + if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENQBRACKET, EmailLexer::S_OPENBRACKET))) { + throw new ExpectingDTEXT(); + } + + if ($this->lexer->isNextTokenAny( + array(EmailLexer::S_HTAB, EmailLexer::S_SP, $this->lexer->token['type'] === EmailLexer::CRLF) + )) { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + $this->parseFWS(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_CR)) { + throw new CRNoLF(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH) { + $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); + $addressLiteral .= $this->lexer->token['value']; + $this->lexer->moveNext(); + $this->validateQuotedPair(); + } + if ($this->lexer->token['type'] === EmailLexer::S_IPV6TAG) { + $IPv6TAG = true; + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEQBRACKET) { + break; + } + + $addressLiteral .= $this->lexer->token['value']; + + } while ($this->lexer->moveNext()); + + $addressLiteral = str_replace('[', '', $addressLiteral); + $addressLiteral = $this->checkIPV4Tag($addressLiteral); + + if (false === $addressLiteral) { + return $addressLiteral; + } + + if (!$IPv6TAG) { + $this->warnings[DomainLiteral::CODE] = new DomainLiteral(); + return $addressLiteral; + } + + $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); + + $this->checkIPV6Tag($addressLiteral); + + return $addressLiteral; + } + + protected function checkIPV4Tag($addressLiteral) + { + $matchesIP = array(); + + // Extract IPv4 part from the end of the address-literal (if there is one) + if (preg_match( + '/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/', + $addressLiteral, + $matchesIP + ) > 0 + ) { + $index = strrpos($addressLiteral, $matchesIP[0]); + if ($index === 0) { + $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); + return false; + } + // Convert IPv4 part to IPv6 format for further testing + $addressLiteral = substr($addressLiteral, 0, $index) . '0:0'; + } + + return $addressLiteral; + } + + protected function checkDomainPartExceptions($prev) + { + $invalidDomainTokens = array( + EmailLexer::S_DQUOTE => true, + EmailLexer::S_SEMICOLON => true, + EmailLexer::S_GREATERTHAN => true, + EmailLexer::S_LOWERTHAN => true, + ); + + if (isset($invalidDomainTokens[$this->lexer->token['type']])) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_COMMA) { + throw new CommaInDomain(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_AT) { + throw new ConsecutiveAt(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENQBRACKET && $prev['type'] !== EmailLexer::S_AT) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN && $this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new DomainHyphened(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH + && $this->lexer->isNextToken(EmailLexer::GENERIC)) { + throw new ExpectingATEXT(); + } + } + + protected function hasBrackets() + { + if ($this->lexer->token['type'] !== EmailLexer::S_OPENBRACKET) { + return false; + } + + try { + $this->lexer->find(EmailLexer::S_CLOSEBRACKET); + } catch (\RuntimeException $e) { + throw new ExpectingDomainLiteralClose(); + } + + return true; + } + + protected function checkLabelLength($prev) + { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && + $prev['type'] === EmailLexer::GENERIC && + strlen($prev['value']) > 63 + ) { + $this->warnings[LabelTooLong::CODE] = new LabelTooLong(); + } + } + + protected function parseDomainComments() + { + $this->isUnclosedComment(); + while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { + $this->warnEscaping(); + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + if ($this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new ExpectingATEXT(); + } + } + + protected function addTLDWarnings() + { + if ($this->warnings[DomainLiteral::CODE]) { + $this->warnings[TLD::CODE] = new TLD(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php new file mode 100644 index 00000000000..8ab16ab4a1f --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php @@ -0,0 +1,138 @@ +lexer->token['type'] !== EmailLexer::S_AT && $this->lexer->token) { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && !$this->lexer->getPrevious()) { + throw new DotAtStart(); + } + + $closingQuote = $this->checkDQUOTE($closingQuote); + if ($closingQuote && $parseDQuote) { + $parseDQuote = $this->parseDoubleQuote(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { + $this->parseComments(); + $openedParenthesis += $this->getOpenedParenthesis(); + } + if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { + if ($openedParenthesis === 0) { + throw new UnopenedComment(); + } else { + $openedParenthesis--; + } + } + + $this->checkConsecutiveDots(); + + if ($this->lexer->token['type'] === EmailLexer::S_DOT && + $this->lexer->isNextToken(EmailLexer::S_AT) + ) { + throw new DotAtEnd(); + } + + $this->warnEscaping(); + $this->isInvalidToken($this->lexer->token, $closingQuote); + + if ($this->isFWS()) { + $this->parseFWS(); + } + + $this->lexer->moveNext(); + } + + $prev = $this->lexer->getPrevious(); + if (strlen($prev['value']) > LocalTooLong::LOCAL_PART_LENGTH) { + $this->warnings[LocalTooLong::CODE] = new LocalTooLong(); + } + } + + protected function parseDoubleQuote() + { + $parseAgain = true; + $special = array( + EmailLexer::S_CR => true, + EmailLexer::S_HTAB => true, + EmailLexer::S_LF => true + ); + + $invalid = array( + EmailLexer::C_NUL => true, + EmailLexer::S_HTAB => true, + EmailLexer::S_CR => true, + EmailLexer::S_LF => true + ); + $setSpecialsWarning = true; + + $this->lexer->moveNext(); + + while ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE && $this->lexer->token) { + $parseAgain = false; + if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + $setSpecialsWarning = false; + } + if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) { + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + + if (!$this->escaped() && isset($invalid[$this->lexer->token['type']])) { + throw new ExpectingATEXT(); + } + } + + $prev = $this->lexer->getPrevious(); + + if ($prev['type'] === EmailLexer::S_BACKSLASH) { + if (!$this->checkDQUOTE(false)) { + throw new UnclosedQuotedString(); + } + } + + if (!$this->lexer->isNextToken(EmailLexer::S_AT) && $prev['type'] !== EmailLexer::S_BACKSLASH) { + throw new ExpectingAT(); + } + + return $parseAgain; + } + + protected function isInvalidToken($token, $closingQuote) + { + $forbidden = array( + EmailLexer::S_COMMA, + EmailLexer::S_CLOSEBRACKET, + EmailLexer::S_OPENBRACKET, + EmailLexer::S_GREATERTHAN, + EmailLexer::S_LOWERTHAN, + EmailLexer::S_COLON, + EmailLexer::S_SEMICOLON, + EmailLexer::INVALID + ); + + if (in_array($token['type'], $forbidden) && !$closingQuote) { + throw new ExpectingATEXT(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php new file mode 100644 index 00000000000..e5042e1a859 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php @@ -0,0 +1,215 @@ +lexer = $lexer; + } + + public function getWarnings() + { + return $this->warnings; + } + + abstract public function parse($str); + + /** @return int */ + public function getOpenedParenthesis() + { + return $this->openedParenthesis; + } + + /** + * validateQuotedPair + */ + protected function validateQuotedPair() + { + if (!($this->lexer->token['type'] === EmailLexer::INVALID + || $this->lexer->token['type'] === EmailLexer::C_DEL)) { + throw new ExpectedQPair(); + } + + $this->warnings[QuotedPart::CODE] = + new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); + } + + protected function parseComments() + { + $this->openedParenthesis = 1; + $this->isUnclosedComment(); + $this->warnings[Comment::CODE] = new Comment(); + while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { + if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) { + $this->openedParenthesis++; + } + $this->warnEscaping(); + $this->lexer->moveNext(); + } + + $this->lexer->moveNext(); + if ($this->lexer->isNextTokenAny(array(EmailLexer::GENERIC, EmailLexer::S_EMPTY))) { + throw new ExpectingATEXT(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_AT)) { + $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); + } + } + + protected function isUnclosedComment() + { + try { + $this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS); + return true; + } catch (\RuntimeException $e) { + throw new UnclosedComment(); + } + } + + protected function parseFWS() + { + $previous = $this->lexer->getPrevious(); + + $this->checkCRLFInFWS(); + + if ($this->lexer->token['type'] === EmailLexer::S_CR) { + throw new CRNoLF(); + } + + if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] !== EmailLexer::S_AT) { + throw new AtextAfterCFWS(); + } + + if ($this->lexer->token['type'] === EmailLexer::S_LF || $this->lexer->token['type'] === EmailLexer::C_NUL) { + throw new ExpectingCTEXT(); + } + + if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous['type'] === EmailLexer::S_AT) { + $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); + } else { + $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); + } + } + + protected function checkConsecutiveDots() + { + if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_DOT)) { + throw new ConsecutiveDot(); + } + } + + protected function isFWS() + { + if ($this->escaped()) { + return false; + } + + if ($this->lexer->token['type'] === EmailLexer::S_SP || + $this->lexer->token['type'] === EmailLexer::S_HTAB || + $this->lexer->token['type'] === EmailLexer::S_CR || + $this->lexer->token['type'] === EmailLexer::S_LF || + $this->lexer->token['type'] === EmailLexer::CRLF + ) { + return true; + } + + return false; + } + + protected function escaped() + { + $previous = $this->lexer->getPrevious(); + + if ($previous['type'] === EmailLexer::S_BACKSLASH + && + $this->lexer->token['type'] !== EmailLexer::GENERIC + ) { + return true; + } + + return false; + } + + protected function warnEscaping() + { + if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) { + return false; + } + + if ($this->lexer->isNextToken(EmailLexer::GENERIC)) { + throw new ExpectingATEXT(); + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) { + return false; + } + + $this->warnings[QuotedPart::CODE] = + new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); + return true; + + } + + protected function checkDQUOTE($hasClosingQuote) + { + if ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE) { + return $hasClosingQuote; + } + if ($hasClosingQuote) { + return $hasClosingQuote; + } + $previous = $this->lexer->getPrevious(); + if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] === EmailLexer::GENERIC) { + throw new ExpectingATEXT(); + } + + try { + $this->lexer->find(EmailLexer::S_DQUOTE); + $hasClosingQuote = true; + } catch (\Exception $e) { + throw new UnclosedQuotedString(); + } + $this->warnings[QuotedString::CODE] = new QuotedString($previous['value'], $this->lexer->token['value']); + + return $hasClosingQuote; + } + + protected function checkCRLFInFWS() + { + if ($this->lexer->token['type'] !== EmailLexer::CRLF) { + return; + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { + throw new CRLFX2(); + } + + if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { + throw new CRLFAtTheEnd(); + } + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php new file mode 100644 index 00000000000..ecca1dd976a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php @@ -0,0 +1,61 @@ +checkDNS($host); + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return $this->warnings; + } + + protected function checkDNS($host) + { + $host = rtrim($host, '.') . '.'; + + $Aresult = true; + $MXresult = checkdnsrr($host, 'MX'); + + if (!$MXresult) { + $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord(); + $Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA'); + if (!$Aresult) { + $this->error = new NoDNSRecord(); + } + } + return $MXresult || $Aresult; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php new file mode 100644 index 00000000000..d5a015be574 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php @@ -0,0 +1,34 @@ +errors = $errors; + parent::__construct(); + } + + public function getErrors() + { + return $this->errors; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php new file mode 100644 index 00000000000..43fa42a64b7 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php @@ -0,0 +1,110 @@ +validations = $validations; + $this->mode = $mode; + } + + /** + * {@inheritdoc} + */ + public function isValid($email, EmailLexer $emailLexer) + { + $result = true; + $errors = []; + foreach ($this->validations as $validation) { + $emailLexer->reset(); + $result = $result && $validation->isValid($email, $emailLexer); + $this->warnings = array_merge($this->warnings, $validation->getWarnings()); + $errors = $this->addNewError($validation->getError(), $errors); + + if ($this->shouldStop($result)) { + break; + } + } + + if (!empty($errors)) { + $this->error = new MultipleErrors($errors); + } + + return $result; + } + + private function addNewError($possibleError, array $errors) + { + if (null !== $possibleError) { + $errors[] = $possibleError; + } + + return $errors; + } + + private function shouldStop($result) + { + return !$result && $this->mode === self::STOP_ON_ERROR; + } + + /** + * {@inheritdoc} + */ + public function getError() + { + return $this->error; + } + + /** + * {@inheritdoc} + */ + public function getWarnings() + { + return $this->warnings; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php new file mode 100644 index 00000000000..e4bf0cc4df9 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php @@ -0,0 +1,41 @@ +getWarnings())) { + return true; + } + + $this->error = new RFCWarnings(); + + return false; + } + + /** + * {@inheritdoc} + */ + public function getError() + { + return $this->error ?: parent::getError(); + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php new file mode 100644 index 00000000000..c4ffe35034b --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php @@ -0,0 +1,49 @@ +parser = new EmailParser($emailLexer); + try { + $this->parser->parse((string)$email); + } catch (InvalidEmail $invalid) { + $this->error = $invalid; + return false; + } + + $this->warnings = $this->parser->getWarnings(); + return true; + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return $this->warnings; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php new file mode 100644 index 00000000000..dd270556e8a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php @@ -0,0 +1,45 @@ +setChecks(Spoofchecker::SINGLE_SCRIPT); + + if ($checker->isSuspicious($email)) { + $this->error = new SpoofEmail(); + } + + return $this->error === null; + } + + public function getError() + { + return $this->error; + } + + public function getWarnings() + { + return []; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php new file mode 100644 index 00000000000..77e70f7f554 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php @@ -0,0 +1,14 @@ +message = 'Address literal in domain part'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php new file mode 100644 index 00000000000..be43bbe6f62 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php @@ -0,0 +1,13 @@ +message = "Deprecated folding white space near @"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php new file mode 100644 index 00000000000..dea3450ec8e --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php @@ -0,0 +1,13 @@ +message = 'Folding whites space followed by folding white space'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php new file mode 100644 index 00000000000..704c2908b9a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php @@ -0,0 +1,13 @@ +message = "Comments found in this email"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php new file mode 100644 index 00000000000..ad43bd7c970 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php @@ -0,0 +1,13 @@ +message = 'Deprecated comments'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php new file mode 100644 index 00000000000..6f36b5e293d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php @@ -0,0 +1,14 @@ +message = 'Domain Literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php new file mode 100644 index 00000000000..61ff17a767d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php @@ -0,0 +1,14 @@ +message = 'Domain is too long, exceeds 255 chars'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php new file mode 100644 index 00000000000..497309dbb0f --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php @@ -0,0 +1,15 @@ +message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php new file mode 100644 index 00000000000..ba2fcc01b83 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php @@ -0,0 +1,14 @@ +message = 'Bad char in IPV6 domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php new file mode 100644 index 00000000000..41afa78c63f --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php @@ -0,0 +1,14 @@ +message = ':: found at the end of the domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php new file mode 100644 index 00000000000..1bf754e30cd --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php @@ -0,0 +1,14 @@ +message = ':: found at the start of the domain literal'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php new file mode 100644 index 00000000000..d752caaa19d --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php @@ -0,0 +1,14 @@ +message = 'Deprecated form of IPV6'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php new file mode 100644 index 00000000000..4f823949962 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php @@ -0,0 +1,14 @@ +message = 'Double colon found after IPV6 tag'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php new file mode 100644 index 00000000000..a59d317f287 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php @@ -0,0 +1,14 @@ +message = 'Group count is not IPV6 valid'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php new file mode 100644 index 00000000000..936274c13ee --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php @@ -0,0 +1,14 @@ +message = 'Reached the maximum number of IPV6 groups allowed'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php new file mode 100644 index 00000000000..daf07f4083c --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php @@ -0,0 +1,14 @@ +message = 'Label too long'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php new file mode 100644 index 00000000000..0d08d8b35c6 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php @@ -0,0 +1,15 @@ +message = 'Local part is too long, exceeds 64 chars (octets)'; + $this->rfcNumber = 5322; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php new file mode 100644 index 00000000000..b3c21a1f3bf --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php @@ -0,0 +1,14 @@ +message = 'No MX DSN record was found for this email'; + $this->rfcNumber = 5321; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php new file mode 100644 index 00000000000..10f19e33409 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php @@ -0,0 +1,14 @@ +rfcNumber = 5322; + $this->message = 'Obsolete DTEXT in domain literal'; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php new file mode 100644 index 00000000000..7be9e6a3f25 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php @@ -0,0 +1,13 @@ +message = "Deprecated Quoted String found between $prevToken and $postToken"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php new file mode 100644 index 00000000000..e9d56e1e032 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php @@ -0,0 +1,13 @@ +message = "Quoted String found between $prevToken and $postToken"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php new file mode 100644 index 00000000000..2338b9f442a --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php @@ -0,0 +1,13 @@ +message = "RFC5321, TLD"; + } +} diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php new file mode 100644 index 00000000000..ec6a365ffb7 --- /dev/null +++ b/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php @@ -0,0 +1,30 @@ +message; + } + + public function code() + { + return self::CODE; + } + + public function RFCNumber() + { + return $this->rfcNumber; + } + + public function __toString() + { + return $this->message() . " rfc: " . $this->rfcNumber . "interal code: " . static::CODE; + } +} diff --git a/htdocs/includes/egulias/email-validator/LICENSE b/htdocs/includes/egulias/email-validator/LICENSE new file mode 100644 index 00000000000..c34d2c197da --- /dev/null +++ b/htdocs/includes/egulias/email-validator/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2016 Eduardo Gulias Davis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/htdocs/includes/egulias/email-validator/README.md b/htdocs/includes/egulias/email-validator/README.md new file mode 100644 index 00000000000..fc7c89ea67c --- /dev/null +++ b/htdocs/includes/egulias/email-validator/README.md @@ -0,0 +1,79 @@ +# EmailValidator +[![Build Status](https://travis-ci.org/egulias/EmailValidator.png?branch=master)](https://travis-ci.org/egulias/EmailValidator) [![Coverage Status](https://coveralls.io/repos/egulias/EmailValidator/badge.png?branch=master)](https://coveralls.io/r/egulias/EmailValidator?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/egulias/EmailValidator/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/egulias/EmailValidator/?branch=master) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/22ba6692-9c02-42e5-a65d-1c5696bfffc6/small.png)](https://insight.sensiolabs.com/projects/22ba6692-9c02-42e5-a65d-1c5696bfffc6) +============================= +With the help of [PHPStorm](https://www.jetbrains.com/phpstorm/) + +## Requirements ## + + * [Composer](https://getcomposer.org) is required for installation + * [Spoofchecking](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/SpoofCheckValidation.php) validation requires that your PHP system have the [PHP Internationalization Libraries](http://php.net/manual/en/book.intl.php) (also known as PHP Intl) + +## Installation ## + +Run the command below to install via Composer + +```shell +composer require egulias/email-validator "~2.1" +``` + +## Getting Started ## +`EmailValidator`requires you to decide which (or combination of them) validation/s strategy/ies you'd like to follow for each [validation](#available-validations). + +A basic example with the RFC validation +```php +isValid("example@example.com", new RFCValidation()); //true +``` + + +### Available validations ### + +1. [RFCValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/RFCValidation.php) +2. [NoRFCWarningsValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/NoRFCWarningsValidation.php) +3. [DNSCheckValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/DNSCheckValidation.php) +4. [SpoofCheckValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/SpoofCheckValidation.php) +5. [MultipleValidationWithAnd](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/MultipleValidationWithAnd.php) +6. [Your own validation](#how-to-extend) + +`MultipleValidationWithAnd` + +It is a validation that operates over other validations performing a logical and (&&) over the result of each validation. + +```php +isValid("example@example.com", $multipleValidations); //true +``` + +### How to extend ### + +It's easy! You just need to extend [EmailValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/EmailValidation.php) and you can use your own validation. + + +## Other Contributors ## +(You can find current contributors [here](https://github.com/egulias/EmailValidator/graphs/contributors)) + +As this is a port from another library and work, here are other people related to the previous one: + +* Ricard Clau [@ricardclau](http://github.com/ricardclau): Performance against PHP built-in filter_var +* Josepf Bielawski [@stloyd](http://github.com/stloyd): For its first re-work of Dominic's lib +* Dominic Sayers [@dominicsayers](http://github.com/dominicsayers): The original isemail function + +## License ## +Released under the MIT License attached with this code. + diff --git a/htdocs/includes/lexer/LICENSE b/htdocs/includes/lexer/LICENSE new file mode 100644 index 00000000000..5e781fce4bb --- /dev/null +++ b/htdocs/includes/lexer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2006-2013 Doctrine Project + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/htdocs/includes/lexer/README.md b/htdocs/includes/lexer/README.md new file mode 100644 index 00000000000..66f443089eb --- /dev/null +++ b/htdocs/includes/lexer/README.md @@ -0,0 +1,5 @@ +# Doctrine Lexer + +Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers. + +This lexer is used in Doctrine Annotations and in Doctrine ORM (DQL). diff --git a/htdocs/includes/lexer/composer.json b/htdocs/includes/lexer/composer.json new file mode 100644 index 00000000000..8cd694c6525 --- /dev/null +++ b/htdocs/includes/lexer/composer.json @@ -0,0 +1,24 @@ +{ + "name": "doctrine/lexer", + "type": "library", + "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", + "keywords": ["lexer", "parser"], + "homepage": "http://www.doctrine-project.org", + "license": "MIT", + "authors": [ + {"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"}, + {"name": "Roman Borschel", "email": "roman@code-factory.org"}, + {"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"} + ], + "require": { + "php": ">=5.3.2" + }, + "autoload": { + "psr-0": { "Doctrine\\Common\\Lexer\\": "lib/" } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php b/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php new file mode 100644 index 00000000000..399a55230b0 --- /dev/null +++ b/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php @@ -0,0 +1,327 @@ +. + */ + +namespace Doctrine\Common\Lexer; + +/** + * Base class for writing simple lexers, i.e. for creating small DSLs. + * + * @since 2.0 + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + */ +abstract class AbstractLexer +{ + /** + * Lexer original input string. + * + * @var string + */ + private $input; + + /** + * Array of scanned tokens. + * + * Each token is an associative array containing three items: + * - 'value' : the string value of the token in the input string + * - 'type' : the type of the token (identifier, numeric, string, input + * parameter, none) + * - 'position' : the position of the token in the input string + * + * @var array + */ + private $tokens = array(); + + /** + * Current lexer position in input string. + * + * @var integer + */ + private $position = 0; + + /** + * Current peek of current lexer position. + * + * @var integer + */ + private $peek = 0; + + /** + * The next token in the input. + * + * @var array + */ + public $lookahead; + + /** + * The last matched/seen token. + * + * @var array + */ + public $token; + + /** + * Sets the input data to be tokenized. + * + * The Lexer is immediately reset and the new input tokenized. + * Any unprocessed tokens from any previous input are lost. + * + * @param string $input The input to be tokenized. + * + * @return void + */ + public function setInput($input) + { + $this->input = $input; + $this->tokens = array(); + + $this->reset(); + $this->scan($input); + } + + /** + * Resets the lexer. + * + * @return void + */ + public function reset() + { + $this->lookahead = null; + $this->token = null; + $this->peek = 0; + $this->position = 0; + } + + /** + * Resets the peek pointer to 0. + * + * @return void + */ + public function resetPeek() + { + $this->peek = 0; + } + + /** + * Resets the lexer position on the input to the given position. + * + * @param integer $position Position to place the lexical scanner. + * + * @return void + */ + public function resetPosition($position = 0) + { + $this->position = $position; + } + + /** + * Retrieve the original lexer's input until a given position. + * + * @param integer $position + * + * @return string + */ + public function getInputUntilPosition($position) + { + return substr($this->input, 0, $position); + } + + /** + * Checks whether a given token matches the current lookahead. + * + * @param integer|string $token + * + * @return boolean + */ + public function isNextToken($token) + { + return null !== $this->lookahead && $this->lookahead['type'] === $token; + } + + /** + * Checks whether any of the given tokens matches the current lookahead. + * + * @param array $tokens + * + * @return boolean + */ + public function isNextTokenAny(array $tokens) + { + return null !== $this->lookahead && in_array($this->lookahead['type'], $tokens, true); + } + + /** + * Moves to the next token in the input string. + * + * @return boolean + */ + public function moveNext() + { + $this->peek = 0; + $this->token = $this->lookahead; + $this->lookahead = (isset($this->tokens[$this->position])) + ? $this->tokens[$this->position++] : null; + + return $this->lookahead !== null; + } + + /** + * Tells the lexer to skip input tokens until it sees a token with the given value. + * + * @param string $type The token type to skip until. + * + * @return void + */ + public function skipUntil($type) + { + while ($this->lookahead !== null && $this->lookahead['type'] !== $type) { + $this->moveNext(); + } + } + + /** + * Checks if given value is identical to the given token. + * + * @param mixed $value + * @param integer $token + * + * @return boolean + */ + public function isA($value, $token) + { + return $this->getType($value) === $token; + } + + /** + * Moves the lookahead token forward. + * + * @return array|null The next token or NULL if there are no more tokens ahead. + */ + public function peek() + { + if (isset($this->tokens[$this->position + $this->peek])) { + return $this->tokens[$this->position + $this->peek++]; + } else { + return null; + } + } + + /** + * Peeks at the next token, returns it and immediately resets the peek. + * + * @return array|null The next token or NULL if there are no more tokens ahead. + */ + public function glimpse() + { + $peek = $this->peek(); + $this->peek = 0; + return $peek; + } + + /** + * Scans the input string for tokens. + * + * @param string $input A query string. + * + * @return void + */ + protected function scan($input) + { + static $regex; + + if ( ! isset($regex)) { + $regex = sprintf( + '/(%s)|%s/%s', + implode(')|(', $this->getCatchablePatterns()), + implode('|', $this->getNonCatchablePatterns()), + $this->getModifiers() + ); + } + + $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE; + $matches = preg_split($regex, $input, -1, $flags); + + foreach ($matches as $match) { + // Must remain before 'value' assignment since it can change content + $type = $this->getType($match[0]); + + $this->tokens[] = array( + 'value' => $match[0], + 'type' => $type, + 'position' => $match[1], + ); + } + } + + /** + * Gets the literal for a given token. + * + * @param integer $token + * + * @return string + */ + public function getLiteral($token) + { + $className = get_class($this); + $reflClass = new \ReflectionClass($className); + $constants = $reflClass->getConstants(); + + foreach ($constants as $name => $value) { + if ($value === $token) { + return $className . '::' . $name; + } + } + + return $token; + } + + /** + * Regex modifiers + * + * @return string + */ + protected function getModifiers() + { + return 'i'; + } + + /** + * Lexical catchable patterns. + * + * @return array + */ + abstract protected function getCatchablePatterns(); + + /** + * Lexical non-catchable patterns. + * + * @return array + */ + abstract protected function getNonCatchablePatterns(); + + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @param string $value + * + * @return integer + */ + abstract protected function getType(&$value); +} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift.php b/htdocs/includes/swiftmailer/lib/classes/Swift.php index 72419b334b7..e89703eaebb 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift.php @@ -16,8 +16,7 @@ */ abstract class Swift { - /** Swift Mailer Version number generated during dist release process */ - const VERSION = '@SWIFT_VERSION_NUMBER@'; + const VERSION = '6.0.2'; public static $initialized = false; public static $inits = array(); @@ -47,7 +46,7 @@ abstract class Swift return; } - $path = dirname(__FILE__).'/'.str_replace('_', '/', $class).'.php'; + $path = __DIR__.'/'.str_replace('_', '/', $class).'.php'; if (!file_exists($path)) { return; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php index a95bccfdf97..1fb232c9fe6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Attachment.php @@ -9,7 +9,7 @@ */ /** - * Attachment class for attaching files to a {@link Swift_Mime_Message}. + * Attachment class for attaching files to a {@link Swift_Mime_SimpleMessage}. * * @author Chris Corbyn */ @@ -39,20 +39,6 @@ class Swift_Attachment extends Swift_Mime_Attachment } } - /** - * Create a new Attachment. - * - * @param string|Swift_OutputByteStream $data - * @param string $filename - * @param string $contentType - * - * @return Swift_Mime_Attachment - */ - public static function newInstance($data = null, $filename = null, $contentType = null) - { - return new self($data, $filename, $contentType); - } - /** * Create a new Attachment from a filesystem path. * @@ -63,9 +49,9 @@ class Swift_Attachment extends Swift_Mime_Attachment */ public static function fromPath($path, $contentType = null) { - return self::newInstance()->setFile( + return (new self())->setFile( new Swift_ByteStream_FileByteStream($path), $contentType - ); + ); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php index a7b0e3a6207..bfd2c79bcbd 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php @@ -18,38 +18,38 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I /** * Write sequence. */ - protected $_sequence = 0; + protected $sequence = 0; /** * StreamFilters. * * @var Swift_StreamFilter[] */ - private $_filters = array(); + private $filters = array(); /** * A buffer for writing. */ - private $_writeBuffer = ''; + private $writeBuffer = ''; /** * Bound streams. * * @var Swift_InputByteStream[] */ - private $_mirrors = array(); + private $mirrors = array(); /** * Commit the given bytes to the storage medium immediately. * * @param string $bytes */ - abstract protected function _commit($bytes); + abstract protected function doCommit($bytes); /** * Flush any buffers/content with immediate effect. */ - abstract protected function _flush(); + abstract protected function flush(); /** * Add a StreamFilter to this InputByteStream. @@ -59,7 +59,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function addFilter(Swift_StreamFilter $filter, $key) { - $this->_filters[$key] = $filter; + $this->filters[$key] = $filter; } /** @@ -69,7 +69,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function removeFilter($key) { - unset($this->_filters[$key]); + unset($this->filters[$key]); } /** @@ -83,15 +83,15 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function write($bytes) { - $this->_writeBuffer .= $bytes; - foreach ($this->_filters as $filter) { - if ($filter->shouldBuffer($this->_writeBuffer)) { + $this->writeBuffer .= $bytes; + foreach ($this->filters as $filter) { + if ($filter->shouldBuffer($this->writeBuffer)) { return; } } - $this->_doWrite($this->_writeBuffer); + $this->doWrite($this->writeBuffer); - return ++$this->_sequence; + return ++$this->sequence; } /** @@ -102,7 +102,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function commit() { - $this->_doWrite($this->_writeBuffer); + $this->doWrite($this->writeBuffer); } /** @@ -115,7 +115,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function bind(Swift_InputByteStream $is) { - $this->_mirrors[] = $is; + $this->mirrors[] = $is; } /** @@ -129,12 +129,12 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function unbind(Swift_InputByteStream $is) { - foreach ($this->_mirrors as $k => $stream) { + foreach ($this->mirrors as $k => $stream) { if ($is === $stream) { - if ($this->_writeBuffer !== '') { - $stream->write($this->_writeBuffer); + if ($this->writeBuffer !== '') { + $stream->write($this->writeBuffer); } - unset($this->_mirrors[$k]); + unset($this->mirrors[$k]); } } } @@ -147,20 +147,20 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I */ public function flushBuffers() { - if ($this->_writeBuffer !== '') { - $this->_doWrite($this->_writeBuffer); + if ($this->writeBuffer !== '') { + $this->doWrite($this->writeBuffer); } - $this->_flush(); + $this->flush(); - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->flushBuffers(); } } /** Run $bytes through all filters */ - private function _filter($bytes) + private function filter($bytes) { - foreach ($this->_filters as $filter) { + foreach ($this->filters as $filter) { $bytes = $filter->filter($bytes); } @@ -168,14 +168,14 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I } /** Just write the bytes to the stream */ - private function _doWrite($bytes) + private function doWrite($bytes) { - $this->_commit($this->_filter($bytes)); + $this->doCommit($this->filter($bytes)); - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->write($bytes); } - $this->_writeBuffer = ''; + $this->writeBuffer = ''; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php index ef05a6d5e6e..31b85e0e02a 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php @@ -11,7 +11,7 @@ /** * Allows reading and writing of bytes to and from an array. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_OutputByteStream { @@ -20,28 +20,28 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O * * @var string[] */ - private $_array = array(); + private $array = array(); /** * The size of the stack. * * @var int */ - private $_arraySize = 0; + private $arraySize = 0; /** * The internal pointer offset. * * @var int */ - private $_offset = 0; + private $offset = 0; /** * Bound streams. * * @var Swift_InputByteStream[] */ - private $_mirrors = array(); + private $mirrors = array(); /** * Create a new ArrayByteStream. @@ -53,12 +53,12 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O public function __construct($stack = null) { if (is_array($stack)) { - $this->_array = $stack; - $this->_arraySize = count($stack); + $this->array = $stack; + $this->arraySize = count($stack); } elseif (is_string($stack)) { $this->write($stack); } else { - $this->_array = array(); + $this->array = array(); } } @@ -76,16 +76,16 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function read($length) { - if ($this->_offset == $this->_arraySize) { + if ($this->offset == $this->arraySize) { return false; } // Don't use array slice - $end = $length + $this->_offset; - $end = $this->_arraySize < $end ? $this->_arraySize : $end; + $end = $length + $this->offset; + $end = $this->arraySize < $end ? $this->arraySize : $end; $ret = ''; - for (; $this->_offset < $end; ++$this->_offset) { - $ret .= $this->_array[$this->_offset]; + for (; $this->offset < $end; ++$this->offset) { + $ret .= $this->array[$this->offset]; } return $ret; @@ -100,11 +100,11 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O { $to_add = str_split($bytes); foreach ($to_add as $value) { - $this->_array[] = $value; + $this->array[] = $value; } - $this->_arraySize = count($this->_array); + $this->arraySize = count($this->array); - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->write($bytes); } } @@ -126,7 +126,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function bind(Swift_InputByteStream $is) { - $this->_mirrors[] = $is; + $this->mirrors[] = $is; } /** @@ -140,9 +140,9 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function unbind(Swift_InputByteStream $is) { - foreach ($this->_mirrors as $k => $stream) { + foreach ($this->mirrors as $k => $stream) { if ($is === $stream) { - unset($this->_mirrors[$k]); + unset($this->mirrors[$k]); } } } @@ -156,13 +156,13 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function setReadPointer($byteOffset) { - if ($byteOffset > $this->_arraySize) { - $byteOffset = $this->_arraySize; + if ($byteOffset > $this->arraySize) { + $byteOffset = $this->arraySize; } elseif ($byteOffset < 0) { $byteOffset = 0; } - $this->_offset = $byteOffset; + $this->offset = $byteOffset; } /** @@ -171,11 +171,11 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O */ public function flushBuffers() { - $this->_offset = 0; - $this->_array = array(); - $this->_arraySize = 0; + $this->offset = 0; + $this->array = array(); + $this->arraySize = 0; - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->flushBuffers(); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php index 406104371e8..61f820e5a14 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php @@ -11,30 +11,27 @@ /** * Allows reading and writing of bytes to and from a file. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_FileStream { /** The internal pointer offset */ - private $_offset = 0; + private $offset = 0; /** The path to the file */ - private $_path; + private $path; /** The mode this file is opened in for writing */ - private $_mode; + private $mode; /** A lazy-loaded resource handle for reading the file */ - private $_reader; + private $reader; /** A lazy-loaded resource handle for writing the file */ - private $_writer; - - /** If magic_quotes_runtime is on, this will be true */ - private $_quotes = false; + private $writer; /** If stream is seekable true/false, or null if not known */ - private $_seekable = null; + private $seekable = null; /** * Create a new FileByteStream for $path. @@ -47,12 +44,8 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl if (empty($path)) { throw new Swift_IoException('The path cannot be empty'); } - $this->_path = $path; - $this->_mode = $writable ? 'w+b' : 'rb'; - - if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { - $this->_quotes = true; - } + $this->path = $path; + $this->mode = $writable ? 'w+b' : 'rb'; } /** @@ -62,7 +55,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl */ public function getPath() { - return $this->_path; + return $this->path; } /** @@ -75,27 +68,21 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl * * @param int $length * - * @throws Swift_IoException - * * @return string|bool + * + * @throws Swift_IoException */ public function read($length) { - $fp = $this->_getReadHandle(); + $fp = $this->getReadHandle(); if (!feof($fp)) { - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 0); - } $bytes = fread($fp, $length); - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 1); - } - $this->_offset = ftell($fp); + $this->offset = ftell($fp); // If we read one byte after reaching the end of the file // feof() will return false and an empty string is returned if ($bytes === '' && feof($fp)) { - $this->_resetReadHandle(); + $this->resetReadHandle(); return false; } @@ -103,7 +90,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl return $bytes; } - $this->_resetReadHandle(); + $this->resetReadHandle(); return false; } @@ -117,93 +104,93 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl */ public function setReadPointer($byteOffset) { - if (isset($this->_reader)) { - $this->_seekReadStreamToPosition($byteOffset); + if (isset($this->reader)) { + $this->seekReadStreamToPosition($byteOffset); } - $this->_offset = $byteOffset; + $this->offset = $byteOffset; } /** Just write the bytes to the file */ - protected function _commit($bytes) + protected function doCommit($bytes) { - fwrite($this->_getWriteHandle(), $bytes); - $this->_resetReadHandle(); + fwrite($this->getWriteHandle(), $bytes); + $this->resetReadHandle(); } /** Not used */ - protected function _flush() + protected function flush() { } /** Get the resource for reading */ - private function _getReadHandle() + private function getReadHandle() { - if (!isset($this->_reader)) { - if (!$this->_reader = fopen($this->_path, 'rb')) { - throw new Swift_IoException( - 'Unable to open file for reading ['.$this->_path.']' - ); + if (!isset($this->reader)) { + $pointer = @fopen($this->path, 'rb'); + if (!$pointer) { + throw new Swift_IoException('Unable to open file for reading ['.$this->path.']'); } - if ($this->_offset != 0) { - $this->_getReadStreamSeekableStatus(); - $this->_seekReadStreamToPosition($this->_offset); + $this->reader = $pointer; + if ($this->offset != 0) { + $this->getReadStreamSeekableStatus(); + $this->seekReadStreamToPosition($this->offset); } } - return $this->_reader; + return $this->reader; } /** Get the resource for writing */ - private function _getWriteHandle() + private function getWriteHandle() { - if (!isset($this->_writer)) { - if (!$this->_writer = fopen($this->_path, $this->_mode)) { + if (!isset($this->writer)) { + if (!$this->writer = fopen($this->path, $this->mode)) { throw new Swift_IoException( - 'Unable to open file for writing ['.$this->_path.']' + 'Unable to open file for writing ['.$this->path.']' ); } } - return $this->_writer; + return $this->writer; } /** Force a reload of the resource for reading */ - private function _resetReadHandle() + private function resetReadHandle() { - if (isset($this->_reader)) { - fclose($this->_reader); - $this->_reader = null; + if (isset($this->reader)) { + fclose($this->reader); + $this->reader = null; } } /** Check if ReadOnly Stream is seekable */ - private function _getReadStreamSeekableStatus() + private function getReadStreamSeekableStatus() { - $metas = stream_get_meta_data($this->_reader); - $this->_seekable = $metas['seekable']; + $metas = stream_get_meta_data($this->reader); + $this->seekable = $metas['seekable']; } /** Streams in a readOnly stream ensuring copy if needed */ - private function _seekReadStreamToPosition($offset) + private function seekReadStreamToPosition($offset) { - if ($this->_seekable === null) { - $this->_getReadStreamSeekableStatus(); + if ($this->seekable === null) { + $this->getReadStreamSeekableStatus(); } - if ($this->_seekable === false) { - $currentPos = ftell($this->_reader); + if ($this->seekable === false) { + $currentPos = ftell($this->reader); if ($currentPos < $offset) { $toDiscard = $offset - $currentPos; - fread($this->_reader, $toDiscard); + fread($this->reader, $toDiscard); return; } - $this->_copyReadStream(); + $this->copyReadStream(); } - fseek($this->_reader, $offset, SEEK_SET); + fseek($this->reader, $offset, SEEK_SET); } /** Copy a readOnly Stream to ensure seekability */ - private function _copyReadStream() + private function copyReadStream() { if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) { /* We have opened a php:// Stream Should work without problem */ @@ -212,11 +199,11 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl } else { throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available'); } - $currentPos = ftell($this->_reader); - fclose($this->_reader); - $source = fopen($this->_path, 'rb'); + $currentPos = ftell($this->reader); + fclose($this->reader); + $source = fopen($this->path, 'rb'); if (!$source) { - throw new Swift_IoException('Unable to open file for copying ['.$this->_path.']'); + throw new Swift_IoException('Unable to open file for copying ['.$this->path.']'); } fseek($tmpFile, 0, SEEK_SET); while (!feof($source)) { @@ -224,6 +211,6 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl } fseek($tmpFile, $currentPos, SEEK_SET); fclose($source); - $this->_reader = $tmpFile; + $this->reader = $tmpFile; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php index 3d5e854a884..4267adbc593 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader.php @@ -48,8 +48,8 @@ interface Swift_CharacterReader * A value of zero means this is already a valid character. * A value of -1 means this cannot possibly be a valid character. * - * @param integer[] $bytes - * @param int $size + * @param int[] $bytes + * @param int $size * * @return int */ diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php index ab8ebfda708..b09bb5b6c38 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php @@ -11,8 +11,8 @@ /** * Provides fixed-width byte sizes for reading fixed-width character sets. * - * @author Chris Corbyn - * @author Xavier De Cock + * @author Chris Corbyn + * @author Xavier De Cock */ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader { @@ -21,7 +21,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe * * @var int */ - private $_width; + private $width; /** * Creates a new GenericFixedWidthReader using $width bytes per character. @@ -30,7 +30,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe */ public function __construct($width) { - $this->_width = $width; + $this->width = $width; } /** @@ -47,11 +47,11 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe { $strlen = strlen($string); // % and / are CPU intensive, so, maybe find a better way - $ignored = $strlen % $this->_width; - $ignoredChars = substr($string, -$ignored); - $currentMap = $this->_width; + $ignored = $strlen % $this->width; + $ignoredChars = $ignored ? substr($string, -$ignored) : ''; + $currentMap = $this->width; - return ($strlen - $ignored) / $this->_width; + return ($strlen - $ignored) / $this->width; } /** @@ -80,7 +80,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe */ public function validateByteSequence($bytes, $size) { - $needed = $this->_width - $size; + $needed = $this->width - $size; return $needed > -1 ? $needed : -1; } @@ -92,6 +92,6 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe */ public function getInitialByteSize() { - return $this->_width; + return $this->width; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php index 7379bda258f..22746bd8575 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php @@ -19,22 +19,22 @@ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader /** Pre-computed for optimization */ private static $length_map = array( // N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x0N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x2N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x4N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x6N - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7N - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x8N - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9N - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xAN - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBN - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xCN - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDN - 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEN - 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, // 0xFN + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x0N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x2N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x4N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x6N + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x8N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9N + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xAN + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBN + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xCN + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDN + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEN + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // 0xFN ); private static $s_length_map = array( diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php index 9171a0bacbf..f3641f46b46 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php @@ -20,14 +20,14 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift * * @var array */ - private static $_map = array(); + private static $map = array(); /** * Factories which have already been loaded. * * @var Swift_CharacterReaderFactory[] */ - private static $_loaded = array(); + private static $loaded = array(); /** * Creates a new CharacterReaderFactory. @@ -44,7 +44,7 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift public function init() { - if (count(self::$_map) > 0) { + if (count(self::$map) > 0) { return; } @@ -66,32 +66,32 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift ); // Utf-8 - self::$_map['utf-?8'] = array( + self::$map['utf-?8'] = array( 'class' => $prefix.'Utf8Reader', 'constructor' => array(), ); //7-8 bit charsets - self::$_map['(us-)?ascii'] = $singleByte; - self::$_map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; - self::$_map['windows-?125[0-9]'] = $singleByte; - self::$_map['cp-?[0-9]+'] = $singleByte; - self::$_map['ansi'] = $singleByte; - self::$_map['macintosh'] = $singleByte; - self::$_map['koi-?7'] = $singleByte; - self::$_map['koi-?8-?.+'] = $singleByte; - self::$_map['mik'] = $singleByte; - self::$_map['(cork|t1)'] = $singleByte; - self::$_map['v?iscii'] = $singleByte; + self::$map['(us-)?ascii'] = $singleByte; + self::$map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; + self::$map['windows-?125[0-9]'] = $singleByte; + self::$map['cp-?[0-9]+'] = $singleByte; + self::$map['ansi'] = $singleByte; + self::$map['macintosh'] = $singleByte; + self::$map['koi-?7'] = $singleByte; + self::$map['koi-?8-?.+'] = $singleByte; + self::$map['mik'] = $singleByte; + self::$map['(cork|t1)'] = $singleByte; + self::$map['v?iscii'] = $singleByte; //16 bits - self::$_map['(ucs-?2|utf-?16)'] = $doubleByte; + self::$map['(ucs-?2|utf-?16)'] = $doubleByte; //32 bits - self::$_map['(ucs-?4|utf-?32)'] = $fourBytes; + self::$map['(ucs-?4|utf-?32)'] = $fourBytes; // Fallback - self::$_map['.*'] = $singleByte; + self::$map['.*'] = $singleByte; } /** @@ -103,21 +103,21 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift */ public function getReaderFor($charset) { - $charset = trim(strtolower($charset)); - foreach (self::$_map as $pattern => $spec) { + $charset = strtolower(trim($charset)); + foreach (self::$map as $pattern => $spec) { $re = '/^'.$pattern.'$/D'; if (preg_match($re, $charset)) { - if (!array_key_exists($pattern, self::$_loaded)) { + if (!array_key_exists($pattern, self::$loaded)) { $reflector = new ReflectionClass($spec['class']); if ($reflector->getConstructor()) { $reader = $reflector->newInstanceArgs($spec['constructor']); } else { $reader = $reflector->newInstance(); } - self::$_loaded[$pattern] = $reader; + self::$loaded[$pattern] = $reader; } - return self::$_loaded[$pattern]; + return self::$loaded[$pattern]; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php index d695a6e172b..fbfbceb01d1 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php @@ -16,28 +16,28 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStream { /** A map of byte values and their respective characters */ - private static $_charMap; + private static $charMap; /** A map of characters and their derivative byte values */ - private static $_byteMap; + private static $byteMap; /** The char reader (lazy-loaded) for the current charset */ - private $_charReader; + private $charReader; /** A factory for creating CharacterReader instances */ - private $_charReaderFactory; + private $charReaderFactory; /** The character set this stream is using */ - private $_charset; + private $charset; /** Array of characters */ - private $_array = array(); + private $array = array(); /** Size of the array of character */ - private $_array_size = array(); + private $array_size = array(); /** The current character offset in the stream */ - private $_offset = 0; + private $offset = 0; /** * Create a new CharacterStream with the given $chars, if set. @@ -47,7 +47,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function __construct(Swift_CharacterReaderFactory $factory, $charset) { - self::_initializeMaps(); + self::initializeMaps(); $this->setCharacterReaderFactory($factory); $this->setCharacterSet($charset); } @@ -59,8 +59,8 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function setCharacterSet($charset) { - $this->_charset = $charset; - $this->_charReader = null; + $this->charset = $charset; + $this->charReader = null; } /** @@ -70,7 +70,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) { - $this->_charReaderFactory = $factory; + $this->charReaderFactory = $factory; } /** @@ -80,28 +80,28 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function importByteStream(Swift_OutputByteStream $os) { - if (!isset($this->_charReader)) { - $this->_charReader = $this->_charReaderFactory - ->getReaderFor($this->_charset); + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory + ->getReaderFor($this->charset); } - $startLength = $this->_charReader->getInitialByteSize(); + $startLength = $this->charReader->getInitialByteSize(); while (false !== $bytes = $os->read($startLength)) { $c = array(); for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { - $c[] = self::$_byteMap[$bytes[$i]]; + $c[] = self::$byteMap[$bytes[$i]]; } $size = count($c); - $need = $this->_charReader + $need = $this->charReader ->validateByteSequence($c, $size); if ($need > 0 && false !== $bytes = $os->read($need)) { for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { - $c[] = self::$_byteMap[$bytes[$i]]; + $c[] = self::$byteMap[$bytes[$i]]; } } - $this->_array[] = $c; - ++$this->_array_size; + $this->array[] = $c; + ++$this->array_size; } } @@ -127,20 +127,20 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function read($length) { - if ($this->_offset == $this->_array_size) { + if ($this->offset == $this->array_size) { return false; } // Don't use array slice $arrays = array(); - $end = $length + $this->_offset; - for ($i = $this->_offset; $i < $end; ++$i) { - if (!isset($this->_array[$i])) { + $end = $length + $this->offset; + for ($i = $this->offset; $i < $end; ++$i) { + if (!isset($this->array[$i])) { break; } - $arrays[] = $this->_array[$i]; + $arrays[] = $this->array[$i]; } - $this->_offset += $i - $this->_offset; // Limit function calls + $this->offset += $i - $this->offset; // Limit function calls $chars = false; foreach ($arrays as $array) { $chars .= implode('', array_map('chr', $array)); @@ -155,24 +155,24 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea * * @param int $length * - * @return integer[] + * @return int[] */ public function readBytes($length) { - if ($this->_offset == $this->_array_size) { + if ($this->offset == $this->array_size) { return false; } $arrays = array(); - $end = $length + $this->_offset; - for ($i = $this->_offset; $i < $end; ++$i) { - if (!isset($this->_array[$i])) { + $end = $length + $this->offset; + for ($i = $this->offset; $i < $end; ++$i) { + if (!isset($this->array[$i])) { break; } - $arrays[] = $this->_array[$i]; + $arrays[] = $this->array[$i]; } - $this->_offset += ($i - $this->_offset); // Limit function calls + $this->offset += ($i - $this->offset); // Limit function calls - return call_user_func_array('array_merge', $arrays); + return array_merge(...$arrays); } /** @@ -182,12 +182,12 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function write($chars) { - if (!isset($this->_charReader)) { - $this->_charReader = $this->_charReaderFactory->getReaderFor( - $this->_charset); + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory->getReaderFor( + $this->charset); } - $startLength = $this->_charReader->getInitialByteSize(); + $startLength = $this->charReader->getInitialByteSize(); $fp = fopen('php://memory', 'w+b'); fwrite($fp, $chars); @@ -203,7 +203,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea // Buffer Filing if ($buf_len - $buf_pos < $startLength) { $buf = array_splice($buffer, $buf_pos); - $new = $this->_reloadBuffer($fp, 100); + $new = $this->reloadBuffer($fp, 100); if ($new) { $buffer = array_merge($buf, $new); $buf_len = count($buffer); @@ -218,11 +218,11 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea ++$size; $bytes[] = $buffer[$buf_pos++]; } - $need = $this->_charReader->validateByteSequence( + $need = $this->charReader->validateByteSequence( $bytes, $size); if ($need > 0) { if ($buf_len - $buf_pos < $need) { - $new = $this->_reloadBuffer($fp, $need); + $new = $this->reloadBuffer($fp, $need); if ($new) { $buffer = array_merge($buffer, $new); @@ -233,8 +233,8 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea $bytes[] = $buffer[$buf_pos++]; } } - $this->_array[] = $bytes; - ++$this->_array_size; + $this->array[] = $bytes; + ++$this->array_size; } } while ($has_datas); @@ -248,12 +248,12 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function setPointer($charOffset) { - if ($charOffset > $this->_array_size) { - $charOffset = $this->_array_size; + if ($charOffset > $this->array_size) { + $charOffset = $this->array_size; } elseif ($charOffset < 0) { $charOffset = 0; } - $this->_offset = $charOffset; + $this->offset = $charOffset; } /** @@ -261,17 +261,17 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea */ public function flushContents() { - $this->_offset = 0; - $this->_array = array(); - $this->_array_size = 0; + $this->offset = 0; + $this->array = array(); + $this->array_size = 0; } - private function _reloadBuffer($fp, $len) + private function reloadBuffer($fp, $len) { if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) { $buf = array(); for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { - $buf[] = self::$_byteMap[$bytes[$i]]; + $buf[] = self::$byteMap[$bytes[$i]]; } return $buf; @@ -280,14 +280,14 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea return false; } - private static function _initializeMaps() + private static function initializeMaps() { - if (!isset(self::$_charMap)) { - self::$_charMap = array(); + if (!isset(self::$charMap)) { + self::$charMap = array(); for ($byte = 0; $byte < 256; ++$byte) { - self::$_charMap[$byte] = chr($byte); + self::$charMap[$byte] = chr($byte); } - self::$_byteMap = array_flip(self::$_charMap); + self::$byteMap = array_flip(self::$charMap); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php index 1e8e2899672..0d62fa68ff3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php @@ -11,7 +11,7 @@ /** * A CharacterStream implementation which stores characters in an internal array. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream { @@ -20,63 +20,63 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream * * @var Swift_CharacterReader */ - private $_charReader; + private $charReader; /** * A factory for creating CharacterReader instances. * * @var Swift_CharacterReaderFactory */ - private $_charReaderFactory; + private $charReaderFactory; /** * The character set this stream is using. * * @var string */ - private $_charset; + private $charset; /** * The data's stored as-is. * * @var string */ - private $_datas = ''; + private $datas = ''; /** * Number of bytes in the stream. * * @var int */ - private $_datasSize = 0; + private $datasSize = 0; /** * Map. * * @var mixed */ - private $_map; + private $map; /** * Map Type. * * @var int */ - private $_mapType = 0; + private $mapType = 0; /** * Number of characters in the stream. * * @var int */ - private $_charCount = 0; + private $charCount = 0; /** * Position in the stream. * * @var int */ - private $_currentPos = 0; + private $currentPos = 0; /** * Constructor. @@ -99,9 +99,9 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function setCharacterSet($charset) { - $this->_charset = $charset; - $this->_charReader = null; - $this->_mapType = 0; + $this->charset = $charset; + $this->charReader = null; + $this->mapType = 0; } /** @@ -111,7 +111,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) { - $this->_charReaderFactory = $factory; + $this->charReaderFactory = $factory; } /** @@ -119,11 +119,11 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function flushContents() { - $this->_datas = null; - $this->_map = null; - $this->_charCount = 0; - $this->_currentPos = 0; - $this->_datasSize = 0; + $this->datas = null; + $this->map = null; + $this->charCount = 0; + $this->currentPos = 0; + $this->datasSize = 0; } /** @@ -161,49 +161,49 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function read($length) { - if ($this->_currentPos >= $this->_charCount) { + if ($this->currentPos >= $this->charCount) { return false; } $ret = false; - $length = $this->_currentPos + $length > $this->_charCount ? $this->_charCount - $this->_currentPos : $length; - switch ($this->_mapType) { + $length = ($this->currentPos + $length > $this->charCount) ? $this->charCount - $this->currentPos : $length; + switch ($this->mapType) { case Swift_CharacterReader::MAP_TYPE_FIXED_LEN: - $len = $length * $this->_map; - $ret = substr($this->_datas, - $this->_currentPos * $this->_map, + $len = $length * $this->map; + $ret = substr($this->datas, + $this->currentPos * $this->map, $len); - $this->_currentPos += $length; + $this->currentPos += $length; break; case Swift_CharacterReader::MAP_TYPE_INVALID: $ret = ''; - for (; $this->_currentPos < $length; ++$this->_currentPos) { - if (isset($this->_map[$this->_currentPos])) { + for (; $this->currentPos < $length; ++$this->currentPos) { + if (isset($this->map[$this->currentPos])) { $ret .= '?'; } else { - $ret .= $this->_datas[$this->_currentPos]; + $ret .= $this->datas[$this->currentPos]; } } break; case Swift_CharacterReader::MAP_TYPE_POSITIONS: - $end = $this->_currentPos + $length; - $end = $end > $this->_charCount ? $this->_charCount : $end; + $end = $this->currentPos + $length; + $end = $end > $this->charCount ? $this->charCount : $end; $ret = ''; $start = 0; - if ($this->_currentPos > 0) { - $start = $this->_map['p'][$this->_currentPos - 1]; + if ($this->currentPos > 0) { + $start = $this->map['p'][$this->currentPos - 1]; } $to = $start; - for (; $this->_currentPos < $end; ++$this->_currentPos) { - if (isset($this->_map['i'][$this->_currentPos])) { - $ret .= substr($this->_datas, $start, $to - $start).'?'; - $start = $this->_map['p'][$this->_currentPos]; + for (; $this->currentPos < $end; ++$this->currentPos) { + if (isset($this->map['i'][$this->currentPos])) { + $ret .= substr($this->datas, $start, $to - $start).'?'; + $start = $this->map['p'][$this->currentPos]; } else { - $to = $this->_map['p'][$this->_currentPos]; + $to = $this->map['p'][$this->currentPos]; } } - $ret .= substr($this->_datas, $start, $to - $start); + $ret .= substr($this->datas, $start, $to - $start); break; } @@ -215,7 +215,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream * * @param int $length * - * @return integer[] + * @return int[] */ public function readBytes($length) { @@ -236,10 +236,10 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function setPointer($charOffset) { - if ($this->_charCount < $charOffset) { - $charOffset = $this->_charCount; + if ($this->charCount < $charOffset) { + $charOffset = $this->charCount; } - $this->_currentPos = $charOffset; + $this->currentPos = $charOffset; } /** @@ -249,19 +249,19 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream */ public function write($chars) { - if (!isset($this->_charReader)) { - $this->_charReader = $this->_charReaderFactory->getReaderFor( - $this->_charset); - $this->_map = array(); - $this->_mapType = $this->_charReader->getMapType(); + if (!isset($this->charReader)) { + $this->charReader = $this->charReaderFactory->getReaderFor( + $this->charset); + $this->map = array(); + $this->mapType = $this->charReader->getMapType(); } $ignored = ''; - $this->_datas .= $chars; - $this->_charCount += $this->_charReader->getCharPositions(substr($this->_datas, $this->_datasSize), $this->_datasSize, $this->_map, $ignored); + $this->datas .= $chars; + $this->charCount += $this->charReader->getCharPositions(substr($this->datas, $this->datasSize), $this->datasSize, $this->map, $ignored); if ($ignored !== false) { - $this->_datasSize = strlen($this->_datas) - strlen($ignored); + $this->datasSize = strlen($this->datas) - strlen($ignored); } else { - $this->_datasSize = strlen($this->_datas); + $this->datasSize = strlen($this->datas); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php index 4ae5bacfc40..a711bac478f 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/ConfigurableSpool.php @@ -16,10 +16,10 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool { /** The maximum number of messages to send per flush */ - private $_message_limit; + private $message_limit; /** The time limit per flush */ - private $_time_limit; + private $time_limit; /** * Sets the maximum number of messages to send per flush. @@ -28,7 +28,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function setMessageLimit($limit) { - $this->_message_limit = (int) $limit; + $this->message_limit = (int) $limit; } /** @@ -38,7 +38,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function getMessageLimit() { - return $this->_message_limit; + return $this->message_limit; } /** @@ -48,7 +48,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function setTimeLimit($limit) { - $this->_time_limit = (int) $limit; + $this->time_limit = (int) $limit; } /** @@ -58,6 +58,6 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool */ public function getTimeLimit() { - return $this->_time_limit; + return $this->time_limit; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php b/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php index 8c1074a3a37..b1bc3306f22 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/DependencyContainer.php @@ -11,7 +11,7 @@ /** * Dependency Injection container. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_DependencyContainer { @@ -28,13 +28,13 @@ class Swift_DependencyContainer const TYPE_ALIAS = 0x1000; /** Singleton instance */ - private static $_instance = null; + private static $instance = null; /** The data container */ - private $_store = array(); + private $store = array(); /** The current endpoint in the data container */ - private $_endPoint; + private $endPoint; /** * Constructor should not be used. @@ -48,15 +48,15 @@ class Swift_DependencyContainer /** * Returns a singleton of the DependencyContainer. * - * @return Swift_DependencyContainer + * @return self */ public static function getInstance() { - if (!isset(self::$_instance)) { - self::$_instance = new self(); + if (!isset(self::$instance)) { + self::$instance = new self(); } - return self::$_instance; + return self::$instance; } /** @@ -66,7 +66,7 @@ class Swift_DependencyContainer */ public function listItems() { - return array_keys($this->_store); + return array_keys($this->store); } /** @@ -80,8 +80,8 @@ class Swift_DependencyContainer */ public function has($itemName) { - return array_key_exists($itemName, $this->_store) - && isset($this->_store[$itemName]['lookupType']); + return array_key_exists($itemName, $this->store) + && isset($this->store[$itemName]['lookupType']); } /** @@ -91,9 +91,9 @@ class Swift_DependencyContainer * * @param string $itemName * - * @throws Swift_DependencyException If the dependency is not found - * * @return mixed + * + * @throws Swift_DependencyException If the dependency is not found */ public function lookup($itemName) { @@ -103,15 +103,15 @@ class Swift_DependencyContainer ); } - switch ($this->_store[$itemName]['lookupType']) { + switch ($this->store[$itemName]['lookupType']) { case self::TYPE_ALIAS: - return $this->_createAlias($itemName); + return $this->createAlias($itemName); case self::TYPE_VALUE: - return $this->_getValue($itemName); + return $this->getValue($itemName); case self::TYPE_INSTANCE: - return $this->_createNewInstance($itemName); + return $this->createNewInstance($itemName); case self::TYPE_SHARED: - return $this->_createSharedInstance($itemName); + return $this->createSharedInstance($itemName); } } @@ -125,8 +125,8 @@ class Swift_DependencyContainer public function createDependenciesFor($itemName) { $args = array(); - if (isset($this->_store[$itemName]['args'])) { - $args = $this->_resolveArgs($this->_store[$itemName]['args']); + if (isset($this->store[$itemName]['args'])) { + $args = $this->resolveArgs($this->store[$itemName]['args']); } return $args; @@ -143,12 +143,12 @@ class Swift_DependencyContainer * * @param string $itemName * - * @return Swift_DependencyContainer + * @return $this */ public function register($itemName) { - $this->_store[$itemName] = array(); - $this->_endPoint = &$this->_store[$itemName]; + $this->store[$itemName] = array(); + $this->endPoint = &$this->store[$itemName]; return $this; } @@ -160,11 +160,11 @@ class Swift_DependencyContainer * * @param mixed $value * - * @return Swift_DependencyContainer + * @return $this */ public function asValue($value) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_VALUE; $endPoint['value'] = $value; @@ -176,11 +176,11 @@ class Swift_DependencyContainer * * @param string $lookup * - * @return Swift_DependencyContainer + * @return $this */ public function asAliasOf($lookup) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_ALIAS; $endPoint['ref'] = $lookup; @@ -198,11 +198,11 @@ class Swift_DependencyContainer * * @param string $className * - * @return Swift_DependencyContainer + * @return $this */ public function asNewInstanceOf($className) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_INSTANCE; $endPoint['className'] = $className; @@ -216,11 +216,11 @@ class Swift_DependencyContainer * * @param string $className * - * @return Swift_DependencyContainer + * @return $this */ public function asSharedInstanceOf($className) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['lookupType'] = self::TYPE_SHARED; $endPoint['className'] = $className; @@ -236,11 +236,11 @@ class Swift_DependencyContainer * * @param array $lookups * - * @return Swift_DependencyContainer + * @return $this */ public function withDependencies(array $lookups) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); $endPoint['args'] = array(); foreach ($lookups as $lookup) { $this->addConstructorLookup($lookup); @@ -257,11 +257,11 @@ class Swift_DependencyContainer * * @param mixed $value * - * @return Swift_DependencyContainer + * @return $this */ public function addConstructorValue($value) { - $endPoint = &$this->_getEndPoint(); + $endPoint = &$this->getEndPoint(); if (!isset($endPoint['args'])) { $endPoint['args'] = array(); } @@ -278,12 +278,12 @@ class Swift_DependencyContainer * * @param string $lookup * - * @return Swift_DependencyContainer + * @return $this */ public function addConstructorLookup($lookup) { - $endPoint = &$this->_getEndPoint(); - if (!isset($this->_endPoint['args'])) { + $endPoint = &$this->getEndPoint(); + if (!isset($this->endPoint['args'])) { $endPoint['args'] = array(); } $endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup); @@ -292,21 +292,21 @@ class Swift_DependencyContainer } /** Get the literal value with $itemName */ - private function _getValue($itemName) + private function getValue($itemName) { - return $this->_store[$itemName]['value']; + return $this->store[$itemName]['value']; } /** Resolve an alias to another item */ - private function _createAlias($itemName) + private function createAlias($itemName) { - return $this->lookup($this->_store[$itemName]['ref']); + return $this->lookup($this->store[$itemName]['ref']); } /** Create a fresh instance of $itemName */ - private function _createNewInstance($itemName) + private function createNewInstance($itemName) { - $reflector = new ReflectionClass($this->_store[$itemName]['className']); + $reflector = new ReflectionClass($this->store[$itemName]['className']); if ($reflector->getConstructor()) { return $reflector->newInstanceArgs( $this->createDependenciesFor($itemName) @@ -317,35 +317,35 @@ class Swift_DependencyContainer } /** Create and register a shared instance of $itemName */ - private function _createSharedInstance($itemName) + private function createSharedInstance($itemName) { - if (!isset($this->_store[$itemName]['instance'])) { - $this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName); + if (!isset($this->store[$itemName]['instance'])) { + $this->store[$itemName]['instance'] = $this->createNewInstance($itemName); } - return $this->_store[$itemName]['instance']; + return $this->store[$itemName]['instance']; } /** Get the current endpoint in the store */ - private function &_getEndPoint() + private function &getEndPoint() { - if (!isset($this->_endPoint)) { + if (!isset($this->endPoint)) { throw new BadMethodCallException( 'Component must first be registered by calling register()' ); } - return $this->_endPoint; + return $this->endPoint; } /** Get an argument list with dependencies resolved */ - private function _resolveArgs(array $args) + private function resolveArgs(array $args) { $resolved = array(); foreach ($args as $argDefinition) { switch ($argDefinition['type']) { case 'lookup': - $resolved[] = $this->_lookupRecursive($argDefinition['item']); + $resolved[] = $this->lookupRecursive($argDefinition['item']); break; case 'value': $resolved[] = $argDefinition['item']; @@ -357,12 +357,12 @@ class Swift_DependencyContainer } /** Resolve a single dependency with an collections */ - private function _lookupRecursive($item) + private function lookupRecursive($item) { if (is_array($item)) { $collection = array(); foreach ($item as $k => $v) { - $collection[$k] = $this->_lookupRecursive($v); + $collection[$k] = $this->lookupRecursive($v); } return $collection; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php b/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php index d8c72ad4dfb..9755a88e176 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/EmbeddedFile.php @@ -39,20 +39,6 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile } } - /** - * Create a new EmbeddedFile. - * - * @param string|Swift_OutputByteStream $data - * @param string $filename - * @param string $contentType - * - * @return Swift_Mime_EmbeddedFile - */ - public static function newInstance($data = null, $filename = null, $contentType = null) - { - return new self($data, $filename, $contentType); - } - /** * Create a new EmbeddedFile from a filesystem path. * @@ -62,8 +48,6 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile */ public static function fromPath($path) { - return self::newInstance()->setFile( - new Swift_ByteStream_FileByteStream($path) - ); + return (new self())->setFile(new Swift_ByteStream_FileByteStream($path)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php index 8a81fe39709..b23b07702ef 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php @@ -13,7 +13,7 @@ * * Possibly the most accurate RFC 2045 QP implementation found in PHP. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Encoder_QpEncoder implements Swift_Encoder { @@ -22,21 +22,21 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder * * @var Swift_CharacterStream */ - protected $_charStream; + protected $charStream; /** * A filter used if input should be canonicalized. * * @var Swift_StreamFilter */ - protected $_filter; + protected $filter; /** * Pre-computed QP for HUGE optimization. * * @var string[] */ - protected static $_qpMap = array( + protected static $qpMap = array( 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', @@ -91,14 +91,14 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder 255 => '=FF', ); - protected static $_safeMapShare = array(); + protected static $safeMapShare = array(); /** * A map of non-encoded ascii characters. * * @var string[] */ - protected $_safeMap = array(); + protected $safeMap = array(); /** * Creates a new QpEncoder for the given CharacterStream. @@ -108,28 +108,28 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder */ public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null) { - $this->_charStream = $charStream; - if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { + $this->charStream = $charStream; + if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); - self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; + self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap; } else { - $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; + $this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()]; } - $this->_filter = $filter; + $this->filter = $filter; } public function __sleep() { - return array('_charStream', '_filter'); + return array('charStream', 'filter'); } public function __wakeup() { - if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { + if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); - self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; + self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap; } else { - $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; + $this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()]; } } @@ -142,7 +142,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder { foreach (array_merge( array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { - $this->_safeMap[$byte] = chr($byte); + $this->safeMap[$byte] = chr($byte); } } @@ -173,19 +173,19 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder $currentLine = &$lines[$lNo++]; $size = $lineLen = 0; - $this->_charStream->flushContents(); - $this->_charStream->importString($string); + $this->charStream->flushContents(); + $this->charStream->importString($string); // Fetching more than 4 chars at one is slower, as is fetching fewer bytes // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes - while (false !== $bytes = $this->_nextSequence()) { + while (false !== $bytes = $this->nextSequence()) { // If we're filtering the input - if (isset($this->_filter)) { + if (isset($this->filter)) { // If we can't filter because we need more bytes - while ($this->_filter->shouldBuffer($bytes)) { + while ($this->filter->shouldBuffer($bytes)) { // Then collect bytes into the buffer - if (false === $moreBytes = $this->_nextSequence(1)) { + if (false === $moreBytes = $this->nextSequence(1)) { break; } @@ -194,10 +194,10 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder } } // And filter them - $bytes = $this->_filter->filter($bytes); + $bytes = $this->filter->filter($bytes); } - $enc = $this->_encodeByteSequence($bytes, $size); + $enc = $this->encodeByteSequence($bytes, $size); $i = strpos($enc, '=0D=0A'); $newLineLength = $lineLen + ($i === false ? $size : $i); @@ -219,7 +219,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder } } - return $this->_standardize(implode("=\r\n", $lines)); + return $this->standardize(implode("=\r\n", $lines)); } /** @@ -229,27 +229,27 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder */ public function charsetChanged($charset) { - $this->_charStream->setCharacterSet($charset); + $this->charStream->setCharacterSet($charset); } /** * Encode the given byte array into a verbatim QP form. * - * @param integer[] $bytes - * @param int $size + * @param int[] $bytes + * @param int $size * * @return string */ - protected function _encodeByteSequence(array $bytes, &$size) + protected function encodeByteSequence(array $bytes, &$size) { $ret = ''; $size = 0; foreach ($bytes as $b) { - if (isset($this->_safeMap[$b])) { - $ret .= $this->_safeMap[$b]; + if (isset($this->safeMap[$b])) { + $ret .= $this->safeMap[$b]; ++$size; } else { - $ret .= self::$_qpMap[$b]; + $ret .= self::$qpMap[$b]; $size += 3; } } @@ -262,11 +262,11 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder * * @param int $size number of bytes to read * - * @return integer[] + * @return int[] */ - protected function _nextSequence($size = 4) + protected function nextSequence($size = 4) { - return $this->_charStream->readBytes($size); + return $this->charStream->readBytes($size); } /** @@ -276,7 +276,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder * * @return string */ - protected function _standardize($string) + protected function standardize($string) { $string = str_replace(array("\t=0D=0A", ' =0D=0A', '=0D=0A'), array("=09\r\n", "=20\r\n", "\r\n"), $string @@ -284,7 +284,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder switch ($end = ord(substr($string, -1))) { case 0x09: case 0x20: - $string = substr_replace($string, self::$_qpMap[$end], -1); + $string = substr_replace($string, self::$qpMap[$end], -1); } return $string; @@ -295,6 +295,6 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder */ public function __clone() { - $this->_charStream = clone $this->_charStream; + $this->charStream = clone $this->charStream; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php index b0215e88380..bebb13494bd 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php @@ -20,7 +20,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder * * @var Swift_CharacterStream */ - private $_charStream; + private $charStream; /** * Creates a new Rfc2231Encoder using the given character stream instance. @@ -29,7 +29,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder */ public function __construct(Swift_CharacterStream $charStream) { - $this->_charStream = $charStream; + $this->charStream = $charStream; } /** @@ -53,12 +53,12 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder $maxLineLength = 75; } - $this->_charStream->flushContents(); - $this->_charStream->importString($string); + $this->charStream->flushContents(); + $this->charStream->importString($string); $thisLineLength = $maxLineLength - $firstLineOffset; - while (false !== $char = $this->_charStream->read(4)) { + while (false !== $char = $this->charStream->read(4)) { $encodedChar = rawurlencode($char); if (0 != strlen($currentLine) && strlen($currentLine.$encodedChar) > $thisLineLength) { @@ -79,7 +79,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder */ public function charsetChanged($charset) { - $this->_charStream->setCharacterSet($charset); + $this->charStream->setCharacterSet($charset); } /** @@ -87,6 +87,6 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder */ public function __clone() { - $this->_charStream = clone $this->_charStream; + $this->charStream = clone $this->charStream; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php deleted file mode 100644 index 253977b608e..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Encoding.php +++ /dev/null @@ -1,64 +0,0 @@ -lookup($key); - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php index 7dc381d9844..9834aa95883 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/CommandEvent.php @@ -20,14 +20,14 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject * * @var string */ - private $_command; + private $command; /** * An array of codes which a successful response will contain. * - * @var integer[] + * @var int[] */ - private $_successCodes = array(); + private $successCodes = array(); /** * Create a new CommandEvent for $source with $command. @@ -39,8 +39,8 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject public function __construct(Swift_Transport $source, $command, $successCodes = array()) { parent::__construct($source); - $this->_command = $command; - $this->_successCodes = $successCodes; + $this->command = $command; + $this->successCodes = $successCodes; } /** @@ -50,16 +50,16 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject */ public function getCommand() { - return $this->_command; + return $this->command; } /** * Get the numeric response codes which indicate success for this command. * - * @return integer[] + * @return int[] */ public function getSuccessCodes() { - return $this->_successCodes; + return $this->successCodes; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php index aac36aaa768..f602608eeb6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php @@ -19,11 +19,11 @@ interface Swift_Events_EventDispatcher * Create a new SendEvent for $source and $message. * * @param Swift_Transport $source - * @param Swift_Mime_Message + * @param Swift_Mime_SimpleMessage * * @return Swift_Events_SendEvent */ - public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message); + public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message); /** * Create a new CommandEvent for $source and $command. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php index 90694a9a600..21e7c8127d6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/EventObject.php @@ -16,10 +16,10 @@ class Swift_Events_EventObject implements Swift_Events_Event { /** The source of this Event */ - private $_source; + private $source; /** The state of this Event (should it bubble up the stack?) */ - private $_bubbleCancelled = false; + private $bubbleCancelled = false; /** * Create a new EventObject originating at $source. @@ -28,7 +28,7 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function __construct($source) { - $this->_source = $source; + $this->source = $source; } /** @@ -38,7 +38,7 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function getSource() { - return $this->_source; + return $this->source; } /** @@ -48,7 +48,7 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function cancelBubble($cancel = true) { - $this->_bubbleCancelled = $cancel; + $this->bubbleCancelled = $cancel; } /** @@ -58,6 +58,6 @@ class Swift_Events_EventObject implements Swift_Events_Event */ public function bubbleCancelled() { - return $this->_bubbleCancelled; + return $this->bubbleCancelled; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php index 2e92ba9404f..5ae6c04b627 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php @@ -20,14 +20,14 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject * * @var bool */ - private $_valid; + private $valid; /** * The response received from the server. * * @var string */ - private $_response; + private $response; /** * Create a new ResponseEvent for $source and $response. @@ -39,8 +39,8 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject public function __construct(Swift_Transport $source, $response, $valid = false) { parent::__construct($source); - $this->_response = $response; - $this->_valid = $valid; + $this->response = $response; + $this->valid = $valid; } /** @@ -50,7 +50,7 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject */ public function getResponse() { - return $this->_response; + return $this->response; } /** @@ -60,6 +60,6 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject */ public function isValid() { - return $this->_valid; + return $this->valid; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php index 10da8080f09..5dc8efb1fd6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SendEvent.php @@ -33,35 +33,35 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject /** * The Message being sent. * - * @var Swift_Mime_Message + * @var Swift_Mime_SimpleMessage */ - private $_message; + private $message; /** * Any recipients which failed after sending. * * @var string[] */ - private $_failedRecipients = array(); + private $failedRecipients = array(); /** * The overall result as a bitmask from the class constants. * * @var int */ - private $_result; + private $result; /** * Create a new SendEvent for $source and $message. * - * @param Swift_Transport $source - * @param Swift_Mime_Message $message + * @param Swift_Transport $source + * @param Swift_Mime_SimpleMessage $message */ - public function __construct(Swift_Transport $source, Swift_Mime_Message $message) + public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $message) { parent::__construct($source); - $this->_message = $message; - $this->_result = self::RESULT_PENDING; + $this->message = $message; + $this->result = self::RESULT_PENDING; } /** @@ -77,11 +77,11 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject /** * Get the Message being sent. * - * @return Swift_Mime_Message + * @return Swift_Mime_SimpleMessage */ public function getMessage() { - return $this->_message; + return $this->message; } /** @@ -91,7 +91,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function setFailedRecipients($recipients) { - $this->_failedRecipients = $recipients; + $this->failedRecipients = $recipients; } /** @@ -101,7 +101,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function getFailedRecipients() { - return $this->_failedRecipients; + return $this->failedRecipients; } /** @@ -111,7 +111,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function setResult($result) { - $this->_result = $result; + $this->result = $result; } /** @@ -124,6 +124,6 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject */ public function getResult() { - return $this->_result; + return $this->result; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php index e8aca752f0d..815fa4d922b 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php @@ -16,20 +16,20 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher { /** A map of event types to their associated listener types */ - private $_eventMap = array(); + private $eventMap = array(); /** Event listeners bound to this dispatcher */ - private $_listeners = array(); + private $listeners = array(); /** Listeners queued to have an Event bubbled up the stack to them */ - private $_bubbleQueue = array(); + private $bubbleQueue = array(); /** * Create a new EventDispatcher. */ public function __construct() { - $this->_eventMap = array( + $this->eventMap = array( 'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener', 'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener', 'Swift_Events_SendEvent' => 'Swift_Events_SendListener', @@ -42,11 +42,11 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher * Create a new SendEvent for $source and $message. * * @param Swift_Transport $source - * @param Swift_Mime_Message + * @param Swift_Mime_SimpleMessage * * @return Swift_Events_SendEvent */ - public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message) + public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message) { return new Swift_Events_SendEvent($source, $message); } @@ -111,13 +111,13 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher */ public function bindEventListener(Swift_Events_EventListener $listener) { - foreach ($this->_listeners as $l) { + foreach ($this->listeners as $l) { // Already loaded if ($l === $listener) { return; } } - $this->_listeners[] = $listener; + $this->listeners[] = $listener; } /** @@ -128,29 +128,29 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher */ public function dispatchEvent(Swift_Events_EventObject $evt, $target) { - $this->_prepareBubbleQueue($evt); - $this->_bubble($evt, $target); + $this->prepareBubbleQueue($evt); + $this->bubble($evt, $target); } /** Queue listeners on a stack ready for $evt to be bubbled up it */ - private function _prepareBubbleQueue(Swift_Events_EventObject $evt) + private function prepareBubbleQueue(Swift_Events_EventObject $evt) { - $this->_bubbleQueue = array(); + $this->bubbleQueue = array(); $evtClass = get_class($evt); - foreach ($this->_listeners as $listener) { - if (array_key_exists($evtClass, $this->_eventMap) - && ($listener instanceof $this->_eventMap[$evtClass])) { - $this->_bubbleQueue[] = $listener; + foreach ($this->listeners as $listener) { + if (array_key_exists($evtClass, $this->eventMap) + && ($listener instanceof $this->eventMap[$evtClass])) { + $this->bubbleQueue[] = $listener; } } } /** Bubble $evt up the stack calling $target() on each listener */ - private function _bubble(Swift_Events_EventObject $evt, $target) + private function bubble(Swift_Events_EventObject $evt, $target) { - if (!$evt->bubbleCancelled() && $listener = array_shift($this->_bubbleQueue)) { + if (!$evt->bubbleCancelled() && $listener = array_shift($this->bubbleQueue)) { $listener->$target($evt); - $this->_bubble($evt, $target); + $this->bubble($evt, $target); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php index f87154fb9b0..77534e3e033 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php @@ -20,7 +20,7 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject * * @var Swift_TransportException */ - private $_exception; + private $exception; /** * Create a new TransportExceptionEvent for $transport. @@ -31,7 +31,7 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject public function __construct(Swift_Transport $transport, Swift_TransportException $ex) { parent::__construct($transport); - $this->_exception = $ex; + $this->exception = $ex; } /** @@ -41,6 +41,6 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject */ public function getException() { - return $this->_exception; + return $this->exception; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php index 53f277da0a2..dc2859f74a0 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/FailoverTransport.php @@ -30,16 +30,4 @@ class Swift_FailoverTransport extends Swift_Transport_FailoverTransport $this->setTransports($transports); } - - /** - * Create a new FailoverTransport instance. - * - * @param Swift_Transport[] $transports - * - * @return Swift_FailoverTransport - */ - public static function newInstance($transports = array()) - { - return new self($transports); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php index 220853989d3..b0b9eb064c5 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/FileSpool.php @@ -17,14 +17,14 @@ class Swift_FileSpool extends Swift_ConfigurableSpool { /** The spool directory */ - private $_path; + private $path; /** * File WriteRetry Limit. * * @var int */ - private $_retryLimit = 10; + private $retryLimit = 10; /** * Create a new FileSpool. @@ -35,11 +35,11 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function __construct($path) { - $this->_path = $path; + $this->path = $path; - if (!file_exists($this->_path)) { - if (!mkdir($this->_path, 0777, true)) { - throw new Swift_IoException('Unable to create Path ['.$this->_path.']'); + if (!file_exists($this->path)) { + if (!mkdir($this->path, 0777, true)) { + throw new Swift_IoException(sprintf('Unable to create path "%s".', $this->path)); } } } @@ -77,25 +77,25 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function setRetryLimit($limit) { - $this->_retryLimit = $limit; + $this->retryLimit = $limit; } /** * Queues a message. * - * @param Swift_Mime_Message $message The message to store + * @param Swift_Mime_SimpleMessage $message The message to store * * @throws Swift_IoException * * @return bool */ - public function queueMessage(Swift_Mime_Message $message) + public function queueMessage(Swift_Mime_SimpleMessage $message) { $ser = serialize($message); - $fileName = $this->_path.'/'.$this->getRandomString(10); - for ($i = 0; $i < $this->_retryLimit; ++$i) { + $fileName = $this->path.'/'.$this->getRandomString(10); + for ($i = 0; $i < $this->retryLimit; ++$i) { /* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */ - $fp = @fopen($fileName.'.message', 'x'); + $fp = @fopen($fileName.'.message', 'xb'); if (false !== $fp) { if (false === fwrite($fp, $ser)) { return false; @@ -108,7 +108,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool } } - throw new Swift_IoException('Unable to create a file for enqueuing Message'); + throw new Swift_IoException(sprintf('Unable to create a file for enqueuing Message in "%s".', $this->path)); } /** @@ -118,7 +118,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function recover($timeout = 900) { - foreach (new DirectoryIterator($this->_path) as $file) { + foreach (new DirectoryIterator($this->path) as $file) { $file = $file->getRealPath(); if (substr($file, -16) == '.message.sending') { @@ -140,7 +140,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool */ public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) { - $directoryIterator = new DirectoryIterator($this->_path); + $directoryIterator = new DirectoryIterator($this->path); /* Start the transport only if there are queued files to send */ if (!$transport->isStarted()) { @@ -200,7 +200,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool $ret = ''; $strlen = strlen($base); for ($i = 0; $i < $count; ++$i) { - $ret .= $base[((int) rand(0, $strlen - 1))]; + $ret .= $base[random_int(0, $strlen - 1)]; } return $ret; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php new file mode 100644 index 00000000000..c845d85e3bd --- /dev/null +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/IdGenerator.php @@ -0,0 +1,22 @@ +setFile( - new Swift_ByteStream_FileByteStream($path) - ); - - return $image; + return (new self())->setFile(new Swift_ByteStream_FileByteStream($path)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php index b37f07f74bd..cdd08503004 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php @@ -20,14 +20,14 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache * * @var array */ - private $_contents = array(); + private $contents = array(); /** * An InputStream for cloning. * * @var Swift_KeyCache_KeyCacheInputStream */ - private $_stream; + private $stream; /** * Create a new ArrayKeyCache with the given $stream for cloning to make @@ -37,7 +37,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function __construct(Swift_KeyCache_KeyCacheInputStream $stream) { - $this->_stream = $stream; + $this->stream = $stream; } /** @@ -52,16 +52,16 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function setString($nsKey, $itemKey, $string, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: - $this->_contents[$nsKey][$itemKey] = $string; + $this->contents[$nsKey][$itemKey] = $string; break; case self::MODE_APPEND: if (!$this->hasKey($nsKey, $itemKey)) { - $this->_contents[$nsKey][$itemKey] = ''; + $this->contents[$nsKey][$itemKey] = ''; } - $this->_contents[$nsKey][$itemKey] .= $string; + $this->contents[$nsKey][$itemKey] .= $string; break; default: throw new Swift_SwiftException( @@ -83,16 +83,16 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: $this->clearKey($nsKey, $itemKey); case self::MODE_APPEND: if (!$this->hasKey($nsKey, $itemKey)) { - $this->_contents[$nsKey][$itemKey] = ''; + $this->contents[$nsKey][$itemKey] = ''; } while (false !== $bytes = $os->read(8192)) { - $this->_contents[$nsKey][$itemKey] .= $bytes; + $this->contents[$nsKey][$itemKey] .= $bytes; } break; default: @@ -116,7 +116,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) { - $is = clone $this->_stream; + $is = clone $this->stream; $is->setKeyCache($this); $is->setNsKey($nsKey); $is->setItemKey($itemKey); @@ -137,9 +137,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function getString($nsKey, $itemKey) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); if ($this->hasKey($nsKey, $itemKey)) { - return $this->_contents[$nsKey][$itemKey]; + return $this->contents[$nsKey][$itemKey]; } } @@ -152,7 +152,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); $is->write($this->getString($nsKey, $itemKey)); } @@ -166,9 +166,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function hasKey($nsKey, $itemKey) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); - return array_key_exists($itemKey, $this->_contents[$nsKey]); + return array_key_exists($itemKey, $this->contents[$nsKey]); } /** @@ -179,7 +179,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function clearKey($nsKey, $itemKey) { - unset($this->_contents[$nsKey][$itemKey]); + unset($this->contents[$nsKey][$itemKey]); } /** @@ -189,7 +189,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache */ public function clearAll($nsKey) { - unset($this->_contents[$nsKey]); + unset($this->contents[$nsKey]); } /** @@ -197,10 +197,10 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache * * @param string $nsKey */ - private function _prepareCache($nsKey) + private function prepareCache($nsKey) { - if (!array_key_exists($nsKey, $this->_contents)) { - $this->_contents[$nsKey] = array(); + if (!array_key_exists($nsKey, $this->contents)) { + $this->contents[$nsKey] = array(); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php index 453f50a15db..d6a633a1512 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php @@ -29,28 +29,21 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache * * @var Swift_KeyCache_KeyCacheInputStream */ - private $_stream; + private $stream; /** * A path to write to. * * @var string */ - private $_path; + private $path; /** * Stored keys. * * @var array */ - private $_keys = array(); - - /** - * Will be true if magic_quotes_runtime is turned on. - * - * @var bool - */ - private $_quotes = false; + private $keys = array(); /** * Create a new DiskKeyCache with the given $stream for cloning to make @@ -61,12 +54,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path) { - $this->_stream = $stream; - $this->_path = $path; - - if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { - $this->_quotes = true; - } + $this->stream = $stream; + $this->path = $path; } /** @@ -83,13 +72,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function setString($nsKey, $itemKey, $string, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); break; case self::MODE_APPEND: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); break; default: throw new Swift_SwiftException( @@ -99,7 +88,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache break; } fwrite($fp, $string); - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); } /** @@ -116,13 +105,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); break; case self::MODE_APPEND: - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END); break; default: throw new Swift_SwiftException( @@ -134,7 +123,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache while (false !== $bytes = $os->read(8192)) { fwrite($fp, $bytes); } - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); } /** @@ -150,7 +139,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) { - $is = clone $this->_stream; + $is = clone $this->stream; $is->setKeyCache($this); $is->setNsKey($nsKey); $is->setItemKey($itemKey); @@ -173,20 +162,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function getString($nsKey, $itemKey) { - $this->_prepareCache($nsKey); + $this->prepareCache($nsKey); if ($this->hasKey($nsKey, $itemKey)) { - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 0); - } + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); $str = ''; while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { $str .= $bytes; } - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 1); - } - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); return $str; } @@ -202,17 +185,11 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) { if ($this->hasKey($nsKey, $itemKey)) { - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 0); - } + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START); while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { $is->write($bytes); } - if ($this->_quotes) { - ini_set('magic_quotes_runtime', 1); - } - $this->_freeHandle($nsKey, $itemKey); + $this->freeHandle($nsKey, $itemKey); } } @@ -226,7 +203,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function hasKey($nsKey, $itemKey) { - return is_file($this->_path.'/'.$nsKey.'/'.$itemKey); + return is_file($this->path.'/'.$nsKey.'/'.$itemKey); } /** @@ -238,8 +215,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache public function clearKey($nsKey, $itemKey) { if ($this->hasKey($nsKey, $itemKey)) { - $this->_freeHandle($nsKey, $itemKey); - unlink($this->_path.'/'.$nsKey.'/'.$itemKey); + $this->freeHandle($nsKey, $itemKey); + unlink($this->path.'/'.$nsKey.'/'.$itemKey); } } @@ -250,14 +227,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function clearAll($nsKey) { - if (array_key_exists($nsKey, $this->_keys)) { - foreach ($this->_keys[$nsKey] as $itemKey => $null) { + if (array_key_exists($nsKey, $this->keys)) { + foreach ($this->keys[$nsKey] as $itemKey => $null) { $this->clearKey($nsKey, $itemKey); } - if (is_dir($this->_path.'/'.$nsKey)) { - rmdir($this->_path.'/'.$nsKey); + if (is_dir($this->path.'/'.$nsKey)) { + rmdir($this->path.'/'.$nsKey); } - unset($this->_keys[$nsKey]); + unset($this->keys[$nsKey]); } } @@ -266,14 +243,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache * * @param string $nsKey */ - private function _prepareCache($nsKey) + private function prepareCache($nsKey) { - $cacheDir = $this->_path.'/'.$nsKey; + $cacheDir = $this->path.'/'.$nsKey; if (!is_dir($cacheDir)) { if (!mkdir($cacheDir)) { throw new Swift_IoException('Failed to create cache directory '.$cacheDir); } - $this->_keys[$nsKey] = array(); + $this->keys[$nsKey] = array(); } } @@ -286,27 +263,27 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache * * @return resource */ - private function _getHandle($nsKey, $itemKey, $position) + private function getHandle($nsKey, $itemKey, $position) { - if (!isset($this->_keys[$nsKey][$itemKey])) { + if (!isset($this->keys[$nsKey][$itemKey])) { $openMode = $this->hasKey($nsKey, $itemKey) ? 'r+b' : 'w+b'; - $fp = fopen($this->_path.'/'.$nsKey.'/'.$itemKey, $openMode); - $this->_keys[$nsKey][$itemKey] = $fp; + $fp = fopen($this->path.'/'.$nsKey.'/'.$itemKey, $openMode); + $this->keys[$nsKey][$itemKey] = $fp; } if (self::POSITION_START == $position) { - fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_SET); + fseek($this->keys[$nsKey][$itemKey], 0, SEEK_SET); } elseif (self::POSITION_END == $position) { - fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_END); + fseek($this->keys[$nsKey][$itemKey], 0, SEEK_END); } - return $this->_keys[$nsKey][$itemKey]; + return $this->keys[$nsKey][$itemKey]; } - private function _freeHandle($nsKey, $itemKey) + private function freeHandle($nsKey, $itemKey) { - $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_CURRENT); + $fp = $this->getHandle($nsKey, $itemKey, self::POSITION_CURRENT); fclose($fp); - $this->_keys[$nsKey][$itemKey] = null; + $this->keys[$nsKey][$itemKey] = null; } /** @@ -314,7 +291,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache */ public function __destruct() { - foreach ($this->_keys as $nsKey => $null) { + foreach ($this->keys as $nsKey => $null) { $this->clearAll($nsKey); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php index b00d458a6de..a74df434c46 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php @@ -16,16 +16,16 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCacheInputStream { /** The KeyCache being written to */ - private $_keyCache; + private $keyCache; /** The nsKey of the KeyCache being written to */ - private $_nsKey; + private $nsKey; /** The itemKey of the KeyCache being written to */ - private $_itemKey; + private $itemKey; /** A stream to write through on each write() */ - private $_writeThrough = null; + private $writeThrough = null; /** * Set the KeyCache to wrap. @@ -34,7 +34,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setKeyCache(Swift_KeyCache $keyCache) { - $this->_keyCache = $keyCache; + $this->keyCache = $keyCache; } /** @@ -44,7 +44,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setWriteThroughStream(Swift_InputByteStream $is) { - $this->_writeThrough = $is; + $this->writeThrough = $is; } /** @@ -55,14 +55,14 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function write($bytes, Swift_InputByteStream $is = null) { - $this->_keyCache->setString( - $this->_nsKey, $this->_itemKey, $bytes, Swift_KeyCache::MODE_APPEND + $this->keyCache->setString( + $this->nsKey, $this->itemKey, $bytes, Swift_KeyCache::MODE_APPEND ); if (isset($is)) { $is->write($bytes); } - if (isset($this->_writeThrough)) { - $this->_writeThrough->write($bytes); + if (isset($this->writeThrough)) { + $this->writeThrough->write($bytes); } } @@ -93,7 +93,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function flushBuffers() { - $this->_keyCache->clearKey($this->_nsKey, $this->_itemKey); + $this->keyCache->clearKey($this->nsKey, $this->itemKey); } /** @@ -103,7 +103,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setNsKey($nsKey) { - $this->_nsKey = $nsKey; + $this->nsKey = $nsKey; } /** @@ -113,7 +113,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function setItemKey($itemKey) { - $this->_itemKey = $itemKey; + $this->itemKey = $itemKey; } /** @@ -122,6 +122,6 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach */ public function __clone() { - $this->_writeThrough = null; + $this->writeThrough = null; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php index fdba9df50dc..03106e55d4e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php @@ -30,16 +30,4 @@ class Swift_LoadBalancedTransport extends Swift_Transport_LoadBalancedTransport $this->setTransports($transports); } - - /** - * Create a new LoadBalancedTransport instance. - * - * @param array $transports - * - * @return Swift_LoadBalancedTransport - */ - public static function newInstance($transports = array()) - { - return new self($transports); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php deleted file mode 100644 index 858ca814792..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/MailTransport.php +++ /dev/null @@ -1,45 +0,0 @@ -createDependenciesFor('transport.mail') - ); - - $this->setExtraParams($extraParams); - } - - /** - * Create a new MailTransport instance. - * - * @param string $extraParams To be passed to mail() - * - * @return Swift_MailTransport - */ - public static function newInstance($extraParams = '-f%s') - { - return new self($extraParams); - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php index 34a78d47b54..3561ec6e68e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer.php @@ -16,7 +16,7 @@ class Swift_Mailer { /** The Transport used to send messages */ - private $_transport; + private $transport; /** * Create a new Mailer using $transport for delivery. @@ -25,19 +25,7 @@ class Swift_Mailer */ public function __construct(Swift_Transport $transport) { - $this->_transport = $transport; - } - - /** - * Create a new Mailer instance. - * - * @param Swift_Transport $transport - * - * @return Swift_Mailer - */ - public static function newInstance(Swift_Transport $transport) - { - return new self($transport); + $this->transport = $transport; } /** @@ -66,23 +54,23 @@ class Swift_Mailer * The return value is the number of recipients who were accepted for * delivery. * - * @param Swift_Mime_Message $message - * @param array $failedRecipients An array of failures by-reference + * @param Swift_Mime_SimpleMessage $message + * @param array $failedRecipients An array of failures by-reference * - * @return int + * @return int The number of successful recipients. Can be 0 which indicates failure */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; - if (!$this->_transport->isStarted()) { - $this->_transport->start(); + if (!$this->transport->isStarted()) { + $this->transport->start(); } $sent = 0; try { - $sent = $this->_transport->send($message, $failedRecipients); + $sent = $this->transport->send($message, $failedRecipients); } catch (Swift_RfcComplianceException $e) { foreach ($message->getTo() as $address => $name) { $failedRecipients[] = $address; @@ -99,7 +87,7 @@ class Swift_Mailer */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_transport->registerPlugin($plugin); + $this->transport->registerPlugin($plugin); } /** @@ -109,6 +97,6 @@ class Swift_Mailer */ public function getTransport() { - return $this->_transport; + return $this->transport; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php index e3e6cad05bd..84dacb5f185 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php @@ -20,7 +20,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera * * @var array */ - private $_recipients = array(); + private $recipients = array(); /** * Create a new ArrayRecipientIterator from $recipients. @@ -29,7 +29,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera */ public function __construct(array $recipients) { - $this->_recipients = $recipients; + $this->recipients = $recipients; } /** @@ -39,7 +39,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera */ public function hasNext() { - return !empty($this->_recipients); + return !empty($this->recipients); } /** @@ -50,6 +50,6 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera */ public function nextRecipient() { - return array_splice($this->_recipients, 0, 1); + return array_splice($this->recipients, 0, 1); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php index 5b239694d81..9aa62835b32 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/MemorySpool.php @@ -16,6 +16,7 @@ class Swift_MemorySpool implements Swift_Spool { protected $messages = array(); + private $flushRetries = 3; /** * Tests if this Transport mechanism has started. @@ -41,14 +42,22 @@ class Swift_MemorySpool implements Swift_Spool { } + /** + * @param int $retries + */ + public function setFlushRetries($retries) + { + $this->flushRetries = $retries; + } + /** * Stores a message in the queue. * - * @param Swift_Mime_Message $message The message to store + * @param Swift_Mime_SimpleMessage $message The message to store * * @return bool Whether the operation has succeeded */ - public function queueMessage(Swift_Mime_Message $message) + public function queueMessage(Swift_Mime_SimpleMessage $message) { //clone the message to make sure it is not changed while in the queue $this->messages[] = clone $message; @@ -75,8 +84,25 @@ class Swift_MemorySpool implements Swift_Spool } $count = 0; - while ($message = array_pop($this->messages)) { - $count += $transport->send($message, $failedRecipients); + $retries = $this->flushRetries; + while ($retries--) { + try { + while ($message = array_pop($this->messages)) { + $count += $transport->send($message, $failedRecipients); + } + } catch (Swift_TransportException $exception) { + if ($retries) { + // re-queue the message at the end of the queue to give a chance + // to the other messages to be sent, in case the failure was due to + // this message and not just the transport failing + array_unshift($this->messages, $message); + + // wait half a second before we try again + usleep(500000); + } else { + throw $exception; + } + } } return $count; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php index 11aa5a9a06a..00f6e160027 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Message.php @@ -60,21 +60,6 @@ class Swift_Message extends Swift_Mime_SimpleMessage } } - /** - * Create a new Message. - * - * @param string $subject - * @param string $body - * @param string $contentType - * @param string $charset - * - * @return Swift_Message - */ - public static function newInstance($subject = null, $body = null, $contentType = null, $charset = null) - { - return new self($subject, $body, $contentType, $charset); - } - /** * Add a MimePart to this Message. * @@ -82,21 +67,19 @@ class Swift_Message extends Swift_Mime_SimpleMessage * @param string $contentType * @param string $charset * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addPart($body, $contentType = null, $charset = null) { - return $this->attach(Swift_MimePart::newInstance( - $body, $contentType, $charset - )); + return $this->attach((new Swift_MimePart($body, $contentType, $charset))->setEncoder($this->getEncoder())); } /** - * Attach a new signature handler to the message. + * Detach a signature handler from a message. * * @param Swift_Signer $signer * - * @return Swift_Message + * @return $this */ public function attachSigner(Swift_Signer $signer) { @@ -114,7 +97,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage * * @param Swift_Signer $signer * - * @return Swift_Message + * @return $this */ public function detachSigner(Swift_Signer $signer) { @@ -207,7 +190,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage $signer->setHeaders($this->getHeaders()); $signer->startBody(); - $this->_bodyToByteStream($signer); + $this->bodyToByteStream($signer); $signer->endBody(); $signer->addSignature($this->getHeaders()); @@ -223,7 +206,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage $this->savedMessage['body'] = $this->getBody(); $this->savedMessage['children'] = $this->getChildren(); if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') { - $this->setChildren(array_merge(array($this->_becomeMimePart()), $this->savedMessage['children'])); + $this->setChildren(array_merge(array($this->becomeMimePart()), $this->savedMessage['children'])); $this->setBody(''); } } @@ -281,11 +264,11 @@ class Swift_Message extends Swift_Mime_SimpleMessage { parent::__clone(); foreach ($this->bodySigners as $key => $bodySigner) { - $this->bodySigners[$key] = clone($bodySigner); + $this->bodySigners[$key] = clone $bodySigner; } foreach ($this->headerSigners as $key => $headerSigner) { - $this->headerSigners[$key] = clone($headerSigner); + $this->headerSigners[$key] = clone $headerSigner; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php index 46a5e8da946..a36ce7237cf 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Attachment.php @@ -16,23 +16,23 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity { /** Recognized MIME types */ - private $_mimeTypes = array(); + private $mimeTypes = array(); /** * Create a new Attachment with $headers, $encoder and $cache. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar - * @param array $mimeTypes optional + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator + * @param array $mimeTypes */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array()) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array()) { - parent::__construct($headers, $encoder, $cache, $grammar); + parent::__construct($headers, $encoder, $cache, $idGenerator); $this->setDisposition('attachment'); $this->setContentType('application/octet-stream'); - $this->_mimeTypes = $mimeTypes; + $this->mimeTypes = $mimeTypes; } /** @@ -56,7 +56,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity */ public function getDisposition() { - return $this->_getHeaderFieldModel('Content-Disposition'); + return $this->getHeaderFieldModel('Content-Disposition'); } /** @@ -64,11 +64,11 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * * @param string $disposition * - * @return Swift_Mime_Attachment + * @return $this */ public function setDisposition($disposition) { - if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition)) { + if (!$this->setHeaderFieldModel('Content-Disposition', $disposition)) { $this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition); } @@ -82,7 +82,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity */ public function getFilename() { - return $this->_getHeaderParameter('Content-Disposition', 'filename'); + return $this->getHeaderParameter('Content-Disposition', 'filename'); } /** @@ -90,12 +90,12 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * * @param string $filename * - * @return Swift_Mime_Attachment + * @return $this */ public function setFilename($filename) { - $this->_setHeaderParameter('Content-Disposition', 'filename', $filename); - $this->_setHeaderParameter('Content-Type', 'name', $filename); + $this->setHeaderParameter('Content-Disposition', 'filename', $filename); + $this->setHeaderParameter('Content-Type', 'name', $filename); return $this; } @@ -107,7 +107,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity */ public function getSize() { - return $this->_getHeaderParameter('Content-Disposition', 'size'); + return $this->getHeaderParameter('Content-Disposition', 'size'); } /** @@ -115,11 +115,11 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * * @param int $size * - * @return Swift_Mime_Attachment + * @return $this */ public function setSize($size) { - $this->_setHeaderParameter('Content-Disposition', 'size', $size); + $this->setHeaderParameter('Content-Disposition', 'size', $size); return $this; } @@ -130,7 +130,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity * @param Swift_FileStream $file * @param string $contentType optional * - * @return Swift_Mime_Attachment + * @return $this */ public function setFile(Swift_FileStream $file, $contentType = null) { @@ -139,8 +139,8 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity if (!isset($contentType)) { $extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1)); - if (array_key_exists($extension, $this->_mimeTypes)) { - $this->setContentType($this->_mimeTypes[$extension]); + if (array_key_exists($extension, $this->mimeTypes)) { + $this->setContentType($this->mimeTypes[$extension]); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php index 710b5ac9edc..34de4ef39a4 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php @@ -92,7 +92,7 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); } - return $this->_standardize(quoted_printable_encode($string)); + return $this->standardize(quoted_printable_encode($string)); } /** @@ -102,7 +102,7 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con * * @return string */ - protected function _standardize($string) + protected function standardize($string) { // transform CR or LF to CRLF $string = preg_replace('~=0D(?!=0A)|(?_name = $name; - $this->_canonical = $canonical; + $this->name = $name; + $this->canonical = $canonical; } /** @@ -52,11 +52,11 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { - if ($this->_canonical) { - $string = $this->_canonicalize($string); + if ($this->canonical) { + $string = $this->canonicalize($string); } - return $this->_safeWordWrap($string, $maxLineLength, "\r\n"); + return $this->safeWordwrap($string, $maxLineLength, "\r\n"); } /** @@ -72,10 +72,10 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten $leftOver = ''; while (false !== $bytes = $os->read(8192)) { $toencode = $leftOver.$bytes; - if ($this->_canonical) { - $toencode = $this->_canonicalize($toencode); + if ($this->canonical) { + $toencode = $this->canonicalize($toencode); } - $wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n"); + $wrapped = $this->safeWordwrap($toencode, $maxLineLength, "\r\n"); $lastLinePos = strrpos($wrapped, "\r\n"); $leftOver = substr($wrapped, $lastLinePos); $wrapped = substr($wrapped, 0, $lastLinePos); @@ -94,7 +94,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten */ public function getName() { - return $this->_name; + return $this->name; } /** @@ -113,7 +113,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten * * @return string */ - private function _safeWordwrap($string, $length = 75, $le = "\r\n") + private function safeWordwrap($string, $length = 75, $le = "\r\n") { if (0 >= $length) { return $string; @@ -151,7 +151,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten * * @return string */ - private function _canonicalize($string) + private function canonicalize($string) { return str_replace( array("\r\n", "\r", "\n"), diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php index 5cc907b8e7e..b3577dbe61f 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php @@ -11,11 +11,11 @@ /** * Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder { - protected $_dotEscape; + protected $dotEscape; /** * Creates a new QpContentEncoder for the given CharacterStream. @@ -26,26 +26,26 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder */ public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false) { - $this->_dotEscape = $dotEscape; + $this->dotEscape = $dotEscape; parent::__construct($charStream, $filter); } public function __sleep() { - return array('_charStream', '_filter', '_dotEscape'); + return array('charStream', 'filter', 'dotEscape'); } protected function getSafeMapShareId() { - return get_class($this).($this->_dotEscape ? '.dotEscape' : ''); + return get_class($this).($this->dotEscape ? '.dotEscape' : ''); } protected function initSafeMap() { parent::initSafeMap(); - if ($this->_dotEscape) { + if ($this->dotEscape) { /* Encode . as =2e for buggy remote servers */ - unset($this->_safeMap[0x2e]); + unset($this->safeMap[0x2e]); } } @@ -69,20 +69,20 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder $thisLineLength = $maxLineLength - $firstLineOffset; - $this->_charStream->flushContents(); - $this->_charStream->importByteStream($os); + $this->charStream->flushContents(); + $this->charStream->importByteStream($os); $currentLine = ''; $prepend = ''; $size = $lineLen = 0; - while (false !== $bytes = $this->_nextSequence()) { + while (false !== $bytes = $this->nextSequence()) { // If we're filtering the input - if (isset($this->_filter)) { + if (isset($this->filter)) { // If we can't filter because we need more bytes - while ($this->_filter->shouldBuffer($bytes)) { + while ($this->filter->shouldBuffer($bytes)) { // Then collect bytes into the buffer - if (false === $moreBytes = $this->_nextSequence(1)) { + if (false === $moreBytes = $this->nextSequence(1)) { break; } @@ -91,16 +91,16 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder } } // And filter them - $bytes = $this->_filter->filter($bytes); + $bytes = $this->filter->filter($bytes); } - $enc = $this->_encodeByteSequence($bytes, $size); + $enc = $this->encodeByteSequence($bytes, $size); $i = strpos($enc, '=0D=0A'); $newLineLength = $lineLen + ($i === false ? $size : $i); if ($currentLine && $newLineLength >= $thisLineLength) { - $is->write($prepend.$this->_standardize($currentLine)); + $is->write($prepend.$this->standardize($currentLine)); $currentLine = ''; $prepend = "=\r\n"; $thisLineLength = $maxLineLength; @@ -117,7 +117,7 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder } } if (strlen($currentLine)) { - $is->write($prepend.$this->_standardize($currentLine)); + $is->write($prepend.$this->standardize($currentLine)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php index 6af757124d3..7835a492873 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php @@ -18,15 +18,15 @@ class Swift_Mime_EmbeddedFile extends Swift_Mime_Attachment /** * Creates a new Attachment with $headers and $encoder. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar - * @param array $mimeTypes optional + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator + * @param array $mimeTypes optional */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array()) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array()) { - parent::__construct($headers, $encoder, $cache, $grammar, $mimeTypes); + parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes); $this->setDisposition('inline'); $this->setId($this->getId()); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php deleted file mode 100644 index a09f338315c..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Grammar.php +++ /dev/null @@ -1,176 +0,0 @@ -init(); - } - - public function __wakeup() - { - $this->init(); - } - - protected function init() - { - if (count(self::$_specials) > 0) { - return; - } - - self::$_specials = array( - '(', ')', '<', '>', '[', ']', - ':', ';', '@', ',', '.', '"', - ); - - /*** Refer to RFC 2822 for ABNF grammar ***/ - - // All basic building blocks - self::$_grammar['NO-WS-CTL'] = '[\x01-\x08\x0B\x0C\x0E-\x19\x7F]'; - self::$_grammar['WSP'] = '[ \t]'; - self::$_grammar['CRLF'] = '(?:\r\n)'; - self::$_grammar['FWS'] = '(?:(?:'.self::$_grammar['WSP'].'*'. - self::$_grammar['CRLF'].')?'.self::$_grammar['WSP'].')'; - self::$_grammar['text'] = '[\x00-\x08\x0B\x0C\x0E-\x7F]'; - self::$_grammar['quoted-pair'] = '(?:\\\\'.self::$_grammar['text'].')'; - self::$_grammar['ctext'] = '(?:'.self::$_grammar['NO-WS-CTL']. - '|[\x21-\x27\x2A-\x5B\x5D-\x7E])'; - // Uses recursive PCRE (?1) -- could be a weak point?? - self::$_grammar['ccontent'] = '(?:'.self::$_grammar['ctext'].'|'. - self::$_grammar['quoted-pair'].'|(?1))'; - self::$_grammar['comment'] = '(\((?:'.self::$_grammar['FWS'].'|'. - self::$_grammar['ccontent'].')*'.self::$_grammar['FWS'].'?\))'; - self::$_grammar['CFWS'] = '(?:(?:'.self::$_grammar['FWS'].'?'. - self::$_grammar['comment'].')*(?:(?:'.self::$_grammar['FWS'].'?'. - self::$_grammar['comment'].')|'.self::$_grammar['FWS'].'))'; - self::$_grammar['qtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. - '|[\x21\x23-\x5B\x5D-\x7E])'; - self::$_grammar['qcontent'] = '(?:'.self::$_grammar['qtext'].'|'. - self::$_grammar['quoted-pair'].')'; - self::$_grammar['quoted-string'] = '(?:'.self::$_grammar['CFWS'].'?"'. - '('.self::$_grammar['FWS'].'?'.self::$_grammar['qcontent'].')*'. - self::$_grammar['FWS'].'?"'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['atext'] = '[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]'; - self::$_grammar['atom'] = '(?:'.self::$_grammar['CFWS'].'?'. - self::$_grammar['atext'].'+'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['dot-atom-text'] = '(?:'.self::$_grammar['atext'].'+'. - '(\.'.self::$_grammar['atext'].'+)*)'; - self::$_grammar['dot-atom'] = '(?:'.self::$_grammar['CFWS'].'?'. - self::$_grammar['dot-atom-text'].'+'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['word'] = '(?:'.self::$_grammar['atom'].'|'. - self::$_grammar['quoted-string'].')'; - self::$_grammar['phrase'] = '(?:'.self::$_grammar['word'].'+?)'; - self::$_grammar['no-fold-quote'] = '(?:"(?:'.self::$_grammar['qtext']. - '|'.self::$_grammar['quoted-pair'].')*")'; - self::$_grammar['dtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. - '|[\x21-\x5A\x5E-\x7E])'; - self::$_grammar['no-fold-literal'] = '(?:\[(?:'.self::$_grammar['dtext']. - '|'.self::$_grammar['quoted-pair'].')*\])'; - - // Message IDs - self::$_grammar['id-left'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. - self::$_grammar['no-fold-quote'].')'; - self::$_grammar['id-right'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. - self::$_grammar['no-fold-literal'].')'; - - // Addresses, mailboxes and paths - self::$_grammar['local-part'] = '(?:'.self::$_grammar['dot-atom'].'|'. - self::$_grammar['quoted-string'].')'; - self::$_grammar['dcontent'] = '(?:'.self::$_grammar['dtext'].'|'. - self::$_grammar['quoted-pair'].')'; - self::$_grammar['domain-literal'] = '(?:'.self::$_grammar['CFWS'].'?\[('. - self::$_grammar['FWS'].'?'.self::$_grammar['dcontent'].')*?'. - self::$_grammar['FWS'].'?\]'.self::$_grammar['CFWS'].'?)'; - self::$_grammar['domain'] = '(?:'.self::$_grammar['dot-atom'].'|'. - self::$_grammar['domain-literal'].')'; - self::$_grammar['addr-spec'] = '(?:'.self::$_grammar['local-part'].'@'. - self::$_grammar['domain'].')'; - } - - /** - * Get the grammar defined for $name token. - * - * @param string $name exactly as written in the RFC - * - * @return string - */ - public function getDefinition($name) - { - if (array_key_exists($name, self::$_grammar)) { - return self::$_grammar[$name]; - } - - throw new Swift_RfcComplianceException( - "No such grammar '".$name."' defined." - ); - } - - /** - * Returns the tokens defined in RFC 2822 (and some related RFCs). - * - * @return array - */ - public function getGrammarDefinitions() - { - return self::$_grammar; - } - - /** - * Returns the current special characters used in the syntax which need to be escaped. - * - * @return array - */ - public function getSpecials() - { - return self::$_specials; - } - - /** - * Escape special characters in a string (convert to quoted-pairs). - * - * @param string $token - * @param string[] $include additional chars to escape - * @param string[] $exclude chars from escaping - * - * @return string - */ - public function escapeSpecials($token, $include = array(), $exclude = array()) - { - foreach (array_merge(array('\\'), array_diff(self::$_specials, $exclude), $include) as $char) { - $token = str_replace($char, '\\'.$char, $token); - } - - return $token; - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php index 510dd6637b3..062be7d7967 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php @@ -31,7 +31,7 @@ class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder i range(0x61, 0x7A), range(0x41, 0x5A), range(0x30, 0x39), array(0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F) ) as $byte) { - $this->_safeMap[$byte] = chr($byte); + $this->safeMap[$byte] = chr($byte); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php deleted file mode 100644 index c65f26d7213..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php +++ /dev/null @@ -1,78 +0,0 @@ -setGrammar($grammar); - } + private $cachedValue = null; /** * Set the character set used in this Header. @@ -81,10 +66,10 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setCharset($charset) { - $this->clearCachedValueIf($charset != $this->_charset); - $this->_charset = $charset; - if (isset($this->_encoder)) { - $this->_encoder->charsetChanged($charset); + $this->clearCachedValueIf($charset != $this->charset); + $this->charset = $charset; + if (isset($this->encoder)) { + $this->encoder->charsetChanged($charset); } } @@ -95,7 +80,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getCharset() { - return $this->_charset; + return $this->charset; } /** @@ -108,8 +93,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setLanguage($lang) { - $this->clearCachedValueIf($this->_lang != $lang); - $this->_lang = $lang; + $this->clearCachedValueIf($this->lang != $lang); + $this->lang = $lang; } /** @@ -119,7 +104,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getLanguage() { - return $this->_lang; + return $this->lang; } /** @@ -129,7 +114,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setEncoder(Swift_Mime_HeaderEncoder $encoder) { - $this->_encoder = $encoder; + $this->encoder = $encoder; $this->setCachedValue(null); } @@ -140,28 +125,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getEncoder() { - return $this->_encoder; - } - - /** - * Set the grammar used for the header. - * - * @param Swift_Mime_Grammar $grammar - */ - public function setGrammar(Swift_Mime_Grammar $grammar) - { - $this->_grammar = $grammar; - $this->setCachedValue(null); - } - - /** - * Get the grammar used for this Header. - * - * @return Swift_Mime_Grammar - */ - public function getGrammar() - { - return $this->_grammar; + return $this->encoder; } /** @@ -171,7 +135,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getFieldName() { - return $this->_name; + return $this->name; } /** @@ -181,8 +145,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function setMaxLineLength($lineLength) { - $this->clearCachedValueIf($this->_lineLength != $lineLength); - $this->_lineLength = $lineLength; + $this->clearCachedValueIf($this->lineLength != $lineLength); + $this->lineLength = $lineLength; } /** @@ -192,19 +156,19 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ public function getMaxLineLength() { - return $this->_lineLength; + return $this->lineLength; } /** * Get this Header rendered as a RFC 2822 compliant string. * - * @throws Swift_RfcComplianceException - * * @return string + * + * @throws Swift_RfcComplianceException */ public function toString() { - return $this->_tokensToString($this->toTokens()); + return $this->tokensToString($this->toTokens()); } /** @@ -219,8 +183,6 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header return $this->toString(); } - // -- Points of extension - /** * Set the name of this Header field. * @@ -228,7 +190,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function setFieldName($name) { - $this->_name = $name; + $this->name = $name; } /** @@ -247,13 +209,12 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header // Treat token as exactly what was given $phraseStr = $string; // If it's not valid - if (!preg_match('/^'.$this->getGrammar()->getDefinition('phrase').'$/D', $phraseStr)) { + + if (!preg_match('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) { // .. but it is just ascii text, try escaping some characters // and make it a quoted-string - if (preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $phraseStr)) { - $phraseStr = $this->getGrammar()->escapeSpecials( - $phraseStr, array('"'), $this->getGrammar()->getSpecials() - ); + if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) { + $phraseStr = $this->escapeSpecials($phraseStr, array('"')); $phraseStr = '"'.$phraseStr.'"'; } else { // ... otherwise it needs encoding @@ -270,6 +231,23 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header return $phraseStr; } + /** + * Escape special characters in a string (convert to quoted-pairs). + * + * @param string $token + * @param string[] $include additional chars to escape + * + * @return string + */ + private function escapeSpecials($token, $include = array()) + { + foreach (array_merge(array('\\'), $include) as $char) { + $token = str_replace($char, '\\'.$char, $token); + } + + return $token; + } + /** * Encode needed word tokens within a string of input. * @@ -365,12 +343,12 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header protected function getTokenAsEncodedWord($token, $firstLineOffset = 0) { // Adjust $firstLineOffset to account for space needed for syntax - $charsetDecl = $this->_charset; - if (isset($this->_lang)) { - $charsetDecl .= '*'.$this->_lang; + $charsetDecl = $this->charset; + if (isset($this->lang)) { + $charsetDecl .= '*'.$this->lang; } $encodingWrapperLength = strlen( - '=?'.$charsetDecl.'?'.$this->_encoder->getName().'??=' + '=?'.$charsetDecl.'?'.$this->encoder->getName().'??=' ); if ($firstLineOffset >= 75) { @@ -379,16 +357,16 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header } $encodedTextLines = explode("\r\n", - $this->_encoder->encodeString( - $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset + $this->encoder->encodeString( + $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset ) ); - if (strtolower($this->_charset) !== 'iso-2022-jp') { + if (strtolower($this->charset) !== 'iso-2022-jp') { // special encoding for iso-2022-jp using mb_encode_mimeheader foreach ($encodedTextLines as $lineNum => $line) { $encodedTextLines[$lineNum] = '=?'.$charsetDecl. - '?'.$this->_encoder->getName(). + '?'.$this->encoder->getName(). '?'.$line.'?='; } } @@ -415,7 +393,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function setCachedValue($value) { - $this->_cachedValue = $value; + $this->cachedValue = $value; } /** @@ -425,7 +403,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function getCachedValue() { - return $this->_cachedValue; + return $this->cachedValue; } /** @@ -449,7 +427,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header */ protected function toTokens($string = null) { - if (is_null($string)) { + if (null === $string) { $string = $this->getFieldBody(); } @@ -474,18 +452,18 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header * * @return string */ - private function _tokensToString(array $tokens) + private function tokensToString(array $tokens) { $lineCount = 0; $headerLines = array(); - $headerLines[] = $this->_name.': '; + $headerLines[] = $this->name.': '; $currentLine = &$headerLines[$lineCount++]; // Build all tokens back into compliant header foreach ($tokens as $i => $token) { // Line longer than specified maximum or token was just a new line if (("\r\n" == $token) || - ($i > 0 && strlen($currentLine.$token) > $this->_lineLength) + ($i > 0 && strlen($currentLine.$token) > $this->lineLength) && 0 < strlen($currentLine)) { $headerLines[] = ''; $currentLine = &$headerLines[$lineCount++]; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php index 4fd6674296e..6dcc92bfdd6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php @@ -16,29 +16,20 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader { /** - * The UNIX timestamp value of this Header. + * Date-time value of this Header. * - * @var int + * @var DateTimeImmutable */ - private $_timestamp; + private $dateTime; /** - * Creates a new DateHeader with $name and $timestamp. + * Creates a new DateHeader with $name. * - * Example: - * - * - * - * - * @param string $name of Header - * @param Swift_Mime_Grammar $grammar + * @param string $name of Header */ - public function __construct($name, Swift_Mime_Grammar $grammar) + public function __construct($name) { $this->setFieldName($name); - parent::__construct($grammar); } /** @@ -57,49 +48,48 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader /** * Set the model for the field body. * - * This method takes a UNIX timestamp. - * - * @param int $model + * @param DateTimeInterface $model */ public function setFieldBodyModel($model) { - $this->setTimestamp($model); + $this->setDateTime($model); } /** * Get the model for the field body. * - * This method returns a UNIX timestamp. - * - * @return mixed + * @return DateTimeImmutable */ public function getFieldBodyModel() { - return $this->getTimestamp(); + return $this->getDateTime(); } /** - * Get the UNIX timestamp of the Date in this Header. + * Get the date-time representing the Date in this Header. * - * @return int + * @return DateTimeImmutable */ - public function getTimestamp() + public function getDateTime() { - return $this->_timestamp; + return $this->dateTime; } /** - * Set the UNIX timestamp of the Date in this Header. + * Set the date-time of the Date in this Header. * - * @param int $timestamp + * If a DateTime instance is provided, it is converted to DateTimeImmutable. + * + * @param DateTimeInterface $dateTime */ - public function setTimestamp($timestamp) + public function setDateTime(DateTimeInterface $dateTime) { - if (!is_null($timestamp)) { - $timestamp = (int) $timestamp; + $this->clearCachedValueIf($this->getCachedValue() != $dateTime->format(DateTime::RFC2822)); + if ($dateTime instanceof DateTime) { + $immutable = new DateTimeImmutable('@'.$dateTime->getTimestamp()); + $dateTime = $immutable->setTimezone($dateTime->getTimezone()); } - $this->clearCachedValueIf($this->_timestamp != $timestamp); - $this->_timestamp = $timestamp; + $this->dateTime = $dateTime; } /** @@ -115,8 +105,8 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader public function getFieldBody() { if (!$this->getCachedValue()) { - if (isset($this->_timestamp)) { - $this->setCachedValue(date('r', $this->_timestamp)); + if (isset($this->dateTime)) { + $this->setCachedValue($this->dateTime->format(DateTime::RFC2822)); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php index b114506b4a4..acf794479b6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php @@ -8,6 +8,9 @@ * file that was distributed with this source code. */ +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + /** * An ID MIME Header for something like Message-ID or Content-ID. * @@ -22,18 +25,25 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac * * @var string[] */ - private $_ids = array(); + private $ids = array(); + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; /** * Creates a new IdentificationHeader with the given $name and $id. * - * @param string $name - * @param Swift_Mime_Grammar $grammar + * @param string $name + * @param EmailValidator $emailValidator */ - public function __construct($name, Swift_Mime_Grammar $grammar) + public function __construct($name, EmailValidator $emailValidator) { $this->setFieldName($name); - parent::__construct($grammar); + $this->emailValidator = $emailValidator; } /** @@ -96,8 +106,8 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac */ public function getId() { - if (count($this->_ids) > 0) { - return $this->_ids[0]; + if (count($this->ids) > 0) { + return $this->ids[0]; } } @@ -113,12 +123,12 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac $actualIds = array(); foreach ($ids as $id) { - $this->_assertValidId($id); + $this->assertValidId($id); $actualIds[] = $id; } - $this->clearCachedValueIf($this->_ids != $actualIds); - $this->_ids = $actualIds; + $this->clearCachedValueIf($this->ids != $actualIds); + $this->ids = $actualIds; } /** @@ -128,7 +138,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac */ public function getIds() { - return $this->_ids; + return $this->ids; } /** @@ -148,7 +158,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac if (!$this->getCachedValue()) { $angleAddrs = array(); - foreach ($this->_ids as $id) { + foreach ($this->ids as $id) { $angleAddrs[] = '<'.$id.'>'; } @@ -165,16 +175,10 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac * * @throws Swift_RfcComplianceException */ - private function _assertValidId($id) + private function assertValidId($id) { - if (!preg_match( - '/^'.$this->getGrammar()->getDefinition('id-left').'@'. - $this->getGrammar()->getDefinition('id-right').'$/D', - $id - )) { - throw new Swift_RfcComplianceException( - 'Invalid ID given <'.$id.'>' - ); + if (!$this->emailValidator->isValid($id, new RFCValidation())) { + throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>'); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php index 798e7f42ace..450e0f25b7e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php @@ -8,6 +8,9 @@ * file that was distributed with this source code. */ +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + /** * A Mailbox Address MIME Header for something like From or Sender. * @@ -20,20 +23,27 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader * * @var string[] */ - private $_mailboxes = array(); + private $mailboxes = array(); + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; /** * Creates a new MailboxHeader with $name. * - * @param string $name of Header + * @param string $name of Header * @param Swift_Mime_HeaderEncoder $encoder - * @param Swift_Mime_Grammar $grammar + * @param EmailValidator $emailValidator */ - public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Mime_Grammar $grammar) + public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator) { $this->setFieldName($name); $this->setEncoder($encoder); - parent::__construct($grammar); + $this->emailValidator = $emailValidator; } /** @@ -103,7 +113,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function setNameAddresses($mailboxes) { - $this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes); + $this->mailboxes = $this->normalizeMailboxes((array) $mailboxes); $this->setCachedValue(null); //Clear any cached value } @@ -134,7 +144,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function getNameAddressStrings() { - return $this->_createNameAddressStrings($this->getNameAddresses()); + return $this->createNameAddressStrings($this->getNameAddresses()); } /** @@ -163,7 +173,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function getNameAddresses() { - return $this->_mailboxes; + return $this->mailboxes; } /** @@ -200,7 +210,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ public function getAddresses() { - return array_keys($this->_mailboxes); + return array_keys($this->mailboxes); } /** @@ -212,7 +222,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader { $this->setCachedValue(null); foreach ((array) $addresses as $address) { - unset($this->_mailboxes[$address]); + unset($this->mailboxes[$address]); } } @@ -231,15 +241,13 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader public function getFieldBody() { // Compute the string value of the header only if needed - if (is_null($this->getCachedValue())) { - $this->setCachedValue($this->createMailboxListString($this->_mailboxes)); + if (null === $this->getCachedValue()) { + $this->setCachedValue($this->createMailboxListString($this->mailboxes)); } return $this->getCachedValue(); } - // -- Points of extension - /** * Normalizes a user-input list of mailboxes into consistent key=>value pairs. * @@ -260,7 +268,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader $address = $value; $name = null; } - $this->_assertValidAddress($address); + $this->assertValidAddress($address); $actualMailboxes[$address] = $name; } @@ -277,9 +285,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ protected function createDisplayNameString($displayName, $shorten = false) { - return $this->createPhrase($this, $displayName, - $this->getCharset(), $this->getEncoder(), $shorten - ); + return $this->createPhrase($this, $displayName, $this->getCharset(), $this->getEncoder(), $shorten); } /** @@ -293,14 +299,15 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ protected function createMailboxListString(array $mailboxes) { - return implode(', ', $this->_createNameAddressStrings($mailboxes)); + return implode(', ', $this->createNameAddressStrings($mailboxes)); } /** * Redefine the encoding requirements for mailboxes. * - * Commas and semicolons are used to separate - * multiple addresses, and should therefore be encoded + * All "specials" must be encoded as the full header value will not be quoted + * + * @see RFC 2822 3.2.1 * * @param string $token * @@ -308,7 +315,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader */ protected function tokenNeedsEncoding($token) { - return preg_match('/[,;]/', $token) || parent::tokenNeedsEncoding($token); + return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token); } /** @@ -318,13 +325,13 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader * * @return string[] */ - private function _createNameAddressStrings(array $mailboxes) + private function createNameAddressStrings(array $mailboxes) { $strings = array(); foreach ($mailboxes as $email => $name) { $mailboxStr = $email; - if (!is_null($name)) { + if (null !== $name) { $nameStr = $this->createDisplayNameString($name, empty($strings)); $mailboxStr = $nameStr.' <'.$mailboxStr.'>'; } @@ -341,14 +348,12 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader * * @throws Swift_RfcComplianceException If invalid. */ - private function _assertValidAddress($address) + private function assertValidAddress($address) { - if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', - $address)) { + if (!$this->emailValidator->isValid($address, new RFCValidation())) { throw new Swift_RfcComplianceException( - 'Address in mailbox given ['.$address. - '] does not comply with RFC 2822, 3.6.2.' - ); + 'Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.' + ); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php index b52b964b773..29277994c0a 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php @@ -20,25 +20,21 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header * * @var string */ - private $_value; + private $value; /** * The name of this Header. * * @var string */ - private $_fieldName; + private $fieldName; /** - * Creates a new SimpleHeader with $name. - * - * @param string $name - * @param Swift_Mime_HeaderEncoder $encoder - * @param Swift_Mime_Grammar $grammar + * @param string $name */ public function __construct($name) { - $this->_fieldName = $name; + $this->fieldName = $name; } /** @@ -85,7 +81,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function getValue() { - return $this->_value; + return $this->value; } /** @@ -95,7 +91,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function setValue($value) { - $this->_value = $value; + $this->value = $value; } /** @@ -105,7 +101,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function getFieldBody() { - return $this->_value; + return $this->value; } /** @@ -115,7 +111,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function toString() { - return $this->_fieldName.': '.$this->_value; + return $this->fieldName.': '.$this->value; } /** @@ -125,7 +121,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header */ public function getFieldName() { - return $this->_fieldName; + return $this->fieldName; } /** diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php index c506daec146..b4a0ddf1224 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php @@ -13,7 +13,7 @@ * * @author Chris Corbyn */ -class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader implements Swift_Mime_ParameterizedHeader +class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader { /** * RFC 2231's definition of a token. @@ -27,14 +27,14 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * * @var Swift_Encoder */ - private $_paramEncoder; + private $paramEncoder; /** * The parameters as an associative array. * * @var string[] */ - private $_params = array(); + private $params = array(); /** * Creates a new ParameterizedHeader with $name. @@ -42,12 +42,11 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * @param string $name * @param Swift_Mime_HeaderEncoder $encoder * @param Swift_Encoder $paramEncoder, optional - * @param Swift_Mime_Grammar $grammar */ - public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null, Swift_Mime_Grammar $grammar) + public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null) { - parent::__construct($name, $encoder, $grammar); - $this->_paramEncoder = $paramEncoder; + parent::__construct($name, $encoder); + $this->paramEncoder = $paramEncoder; } /** @@ -71,8 +70,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct public function setCharset($charset) { parent::setCharset($charset); - if (isset($this->_paramEncoder)) { - $this->_paramEncoder->charsetChanged($charset); + if (isset($this->paramEncoder)) { + $this->paramEncoder->charsetChanged($charset); } } @@ -98,7 +97,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct { $params = $this->getParameters(); - return array_key_exists($parameter, $params) ? $params[$parameter] : null; + return $params[$parameter] ?? null; } /** @@ -108,8 +107,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct */ public function setParameters(array $parameters) { - $this->clearCachedValueIf($this->_params != $parameters); - $this->_params = $parameters; + $this->clearCachedValueIf($this->params != $parameters); + $this->params = $parameters; } /** @@ -119,7 +118,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct */ public function getParameters() { - return $this->_params; + return $this->params; } /** @@ -130,10 +129,10 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct public function getFieldBody() //TODO: Check caching here { $body = parent::getFieldBody(); - foreach ($this->_params as $name => $value) { - if (!is_null($value)) { + foreach ($this->params as $name => $value) { + if (null !== $value) { // Add the parameter - $body .= '; '.$this->_createParameter($name, $value); + $body .= '; '.$this->createParameter($name, $value); } } @@ -155,12 +154,12 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct $tokens = parent::toTokens(parent::getFieldBody()); // Try creating any parameters - foreach ($this->_params as $name => $value) { - if (!is_null($value)) { + foreach ($this->params as $name => $value) { + if (null !== $value) { // Add the semi-colon separator $tokens[count($tokens) - 1] .= ';'; $tokens = array_merge($tokens, $this->generateTokenLines( - ' '.$this->_createParameter($name, $value) + ' '.$this->createParameter($name, $value) )); } } @@ -176,7 +175,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * * @return string */ - private function _createParameter($name, $value) + private function createParameter($name, $value) { $origValue = $value; @@ -189,7 +188,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { // TODO: text, or something else?? // ... and it's not ascii - if (!preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $value)) { + if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) { $encoded = true; // Allow space for the indices, charset and language $maxValueLength = $this->getMaxLineLength() - strlen($name.'*N*="";') - 1; @@ -201,8 +200,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct // Encode if we need to if ($encoded || strlen($value) > $maxValueLength) { - if (isset($this->_paramEncoder)) { - $value = $this->_paramEncoder->encodeString( + if (isset($this->paramEncoder)) { + $value = $this->paramEncoder->encodeString( $origValue, $firstLineOffset, $maxValueLength, $this->getCharset() ); } else { @@ -212,19 +211,19 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct } } - $valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value); + $valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : array($value); // Need to add indices if (count($valueLines) > 1) { $paramLines = array(); foreach ($valueLines as $i => $line) { $paramLines[] = $name.'*'.$i. - $this->_getEndOfParameterValue($line, true, $i == 0); + $this->getEndOfParameterValue($line, true, $i == 0); } return implode(";\r\n ", $paramLines); } else { - return $name.$this->_getEndOfParameterValue( + return $name.$this->getEndOfParameterValue( $valueLines[0], $encoded, true ); } @@ -239,7 +238,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct * * @return string */ - private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false) + private function getEndOfParameterValue($value, $encoded = false, $firstLine = false) { if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { $value = '"'.$value.'"'; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php index 2fffc7b4aac..f79e19fd8b3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php @@ -8,6 +8,9 @@ * file that was distributed with this source code. */ +use Egulias\EmailValidator\EmailValidator; +use Egulias\EmailValidator\Validation\RFCValidation; + /** * A Path Header in Swift Mailer, such a Return-Path. * @@ -20,18 +23,25 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader * * @var string */ - private $_address; + private $address; + + /** + * The strict EmailValidator. + * + * @var EmailValidator + */ + private $emailValidator; /** * Creates a new PathHeader with the given $name. * - * @param string $name - * @param Swift_Mime_Grammar $grammar + * @param string $name + * @param EmailValidator $emailValidator */ - public function __construct($name, Swift_Mime_Grammar $grammar) + public function __construct($name, EmailValidator $emailValidator) { $this->setFieldName($name); - parent::__construct($grammar); + $this->emailValidator = $emailValidator; } /** @@ -80,13 +90,13 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader */ public function setAddress($address) { - if (is_null($address)) { - $this->_address = null; + if (null === $address) { + $this->address = null; } elseif ('' == $address) { - $this->_address = ''; + $this->address = ''; } else { - $this->_assertValidAddress($address); - $this->_address = $address; + $this->assertValidAddress($address); + $this->address = $address; } $this->setCachedValue(null); } @@ -100,7 +110,7 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader */ public function getAddress() { - return $this->_address; + return $this->address; } /** @@ -116,8 +126,8 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader public function getFieldBody() { if (!$this->getCachedValue()) { - if (isset($this->_address)) { - $this->setCachedValue('<'.$this->_address.'>'); + if (isset($this->address)) { + $this->setCachedValue('<'.$this->address.'>'); } } @@ -131,13 +141,12 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader * * @throws Swift_RfcComplianceException If address is invalid */ - private function _assertValidAddress($address) + private function assertValidAddress($address) { - if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', - $address)) { + if (!$this->emailValidator->isValid($address, new RFCValidation())) { throw new Swift_RfcComplianceException( 'Address set in PathHeader does not comply with addr-spec of RFC 2822.' - ); + ); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php index 86177f14a1f..d9d9f5e25d3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php @@ -20,20 +20,18 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH * * @var string */ - private $_value; + private $value; /** * Creates a new SimpleHeader with $name. * * @param string $name * @param Swift_Mime_HeaderEncoder $encoder - * @param Swift_Mime_Grammar $grammar */ - public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Mime_Grammar $grammar) + public function __construct($name, Swift_Mime_HeaderEncoder $encoder) { $this->setFieldName($name); $this->setEncoder($encoder); - parent::__construct($grammar); } /** @@ -80,7 +78,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH */ public function getValue() { - return $this->_value; + return $this->value; } /** @@ -90,8 +88,8 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH */ public function setValue($value) { - $this->clearCachedValueIf($this->_value != $value); - $this->_value = $value; + $this->clearCachedValueIf($this->value != $value); + $this->value = $value; } /** @@ -103,7 +101,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH { if (!$this->getCachedValue()) { $this->setCachedValue( - $this->encodeWords($this, $this->_value) + $this->encodeWords($this, $this->value) ); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php new file mode 100644 index 00000000000..6e98ee8975d --- /dev/null +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/IdGenerator.php @@ -0,0 +1,53 @@ +idRight = $idRight; + } + + /** + * Returns the right-hand side of the "@" used in all generated IDs. + * + * @return string + */ + public function getIdRight() + { + return $this->idRight; + } + + /** + * Sets the right-hand side of the "@" to use in all generated IDs. + * + * @param string $idRight + */ + public function setIdRight($idRight) + { + $this->idRight = $idRight; + } + + /** + * @return string + */ + public function generateId() + { + $idLeft = bin2hex(random_bytes(16)); // set 32 hex values + + return $idLeft.'@'.$this->idRight; + } +} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php deleted file mode 100644 index 9b36d216271..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/Message.php +++ /dev/null @@ -1,223 +0,0 @@ - 'Real Name'). - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $address - * @param string $name optional - */ - public function setSender($address, $name = null); - - /** - * Get the sender address for this message. - * - * This has a higher significance than the From address. - * - * @return string - */ - public function getSender(); - - /** - * Set the From address of this message. - * - * It is permissible for multiple From addresses to be set using an array. - * - * If multiple From addresses are used, you SHOULD set the Sender address and - * according to RFC 2822, MUST set the sender address. - * - * An array can be used if display names are to be provided: i.e. - * array('email@address.com' => 'Real Name'). - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setFrom($addresses, $name = null); - - /** - * Get the From address(es) of this message. - * - * This method always returns an associative array where the keys are the - * addresses. - * - * @return string[] - */ - public function getFrom(); - - /** - * Set the Reply-To address(es). - * - * Any replies from the receiver will be sent to this address. - * - * It is permissible for multiple reply-to addresses to be set using an array. - * - * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setReplyTo($addresses, $name = null); - - /** - * Get the Reply-To addresses for this message. - * - * This method always returns an associative array where the keys provide the - * email addresses. - * - * @return string[] - */ - public function getReplyTo(); - - /** - * Set the To address(es). - * - * Recipients set in this field will receive a copy of this message. - * - * This method has the same synopsis as {@link setFrom()} and {@link setCc()}. - * - * If the second parameter is provided and the first is a string, then $name - * is associated with the address. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setTo($addresses, $name = null); - - /** - * Get the To addresses for this message. - * - * This method always returns an associative array, whereby the keys provide - * the actual email addresses. - * - * @return string[] - */ - public function getTo(); - - /** - * Set the Cc address(es). - * - * Recipients set in this field will receive a 'carbon-copy' of this message. - * - * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setCc($addresses, $name = null); - - /** - * Get the Cc addresses for this message. - * - * This method always returns an associative array, whereby the keys provide - * the actual email addresses. - * - * @return string[] - */ - public function getCc(); - - /** - * Set the Bcc address(es). - * - * Recipients set in this field will receive a 'blind-carbon-copy' of this - * message. - * - * In other words, they will get the message, but any other recipients of the - * message will have no such knowledge of their receipt of it. - * - * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. - * - * @param mixed $addresses - * @param string $name optional - */ - public function setBcc($addresses, $name = null); - - /** - * Get the Bcc addresses for this message. - * - * This method always returns an associative array, whereby the keys provide - * the actual email addresses. - * - * @return string[] - */ - public function getBcc(); -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php deleted file mode 100644 index 30f460cdcdb..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php +++ /dev/null @@ -1,117 +0,0 @@ -setContentType('text/plain'); - if (!is_null($charset)) { + if (null !== $charset) { $this->setCharset($charset); } } @@ -53,14 +53,14 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * @param string $contentType optional * @param string $charset optional * - * @return Swift_Mime_MimePart + * @return $this */ public function setBody($body, $contentType = null, $charset = null) { if (isset($charset)) { $this->setCharset($charset); } - $body = $this->_convertString($body); + $body = $this->convertString($body); parent::setBody($body, $contentType); @@ -74,7 +74,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getCharset() { - return $this->_getHeaderParameter('Content-Type', 'charset'); + return $this->getHeaderParameter('Content-Type', 'charset'); } /** @@ -82,15 +82,15 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * * @param string $charset * - * @return Swift_Mime_MimePart + * @return $this */ public function setCharset($charset) { - $this->_setHeaderParameter('Content-Type', 'charset', $charset); - if ($charset !== $this->_userCharset) { - $this->_clearCache(); + $this->setHeaderParameter('Content-Type', 'charset', $charset); + if ($charset !== $this->userCharset) { + $this->clearCache(); } - $this->_userCharset = $charset; + $this->userCharset = $charset; parent::charsetChanged($charset); return $this; @@ -103,7 +103,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getFormat() { - return $this->_getHeaderParameter('Content-Type', 'format'); + return $this->getHeaderParameter('Content-Type', 'format'); } /** @@ -111,12 +111,12 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * * @param string $format * - * @return Swift_Mime_MimePart + * @return $this */ public function setFormat($format) { - $this->_setHeaderParameter('Content-Type', 'format', $format); - $this->_userFormat = $format; + $this->setHeaderParameter('Content-Type', 'format', $format); + $this->userFormat = $format; return $this; } @@ -128,7 +128,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getDelSp() { - return 'yes' == $this->_getHeaderParameter('Content-Type', 'delsp') ? true : false; + return 'yes' === $this->getHeaderParameter('Content-Type', 'delsp'); } /** @@ -136,12 +136,12 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity * * @param bool $delsp * - * @return Swift_Mime_MimePart + * @return $this */ public function setDelSp($delsp = true) { - $this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); - $this->_userDelSp = $delsp; + $this->setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); + $this->userDelSp = $delsp; return $this; } @@ -155,7 +155,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity */ public function getNestingLevel() { - return $this->_nestingLevel; + return $this->nestingLevel; } /** @@ -170,31 +170,31 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity } /** Fix the content-type and encoding of this entity */ - protected function _fixHeaders() + protected function fixHeaders() { - parent::_fixHeaders(); + parent::fixHeaders(); if (count($this->getChildren())) { - $this->_setHeaderParameter('Content-Type', 'charset', null); - $this->_setHeaderParameter('Content-Type', 'format', null); - $this->_setHeaderParameter('Content-Type', 'delsp', null); + $this->setHeaderParameter('Content-Type', 'charset', null); + $this->setHeaderParameter('Content-Type', 'format', null); + $this->setHeaderParameter('Content-Type', 'delsp', null); } else { - $this->setCharset($this->_userCharset); - $this->setFormat($this->_userFormat); - $this->setDelSp($this->_userDelSp); + $this->setCharset($this->userCharset); + $this->setFormat($this->userFormat); + $this->setDelSp($this->userDelSp); } } /** Set the nesting level of this entity */ - protected function _setNestingLevel($level) + protected function setNestingLevel($level) { - $this->_nestingLevel = $level; + $this->nestingLevel = $level; } /** Encode charset when charset is not utf-8 */ - protected function _convertString($string) + protected function convertString($string) { $charset = strtolower($this->getCharset()); - if (!in_array($charset, array('utf-8', 'iso-8859-1', ''))) { + if (!in_array($charset, array('utf-8', 'iso-8859-1', 'iso-8859-15', ''))) { // mb_convert_encoding must be the first one to check, since iconv cannot convert some words. if (function_exists('mb_convert_encoding')) { $string = mb_convert_encoding($string, $charset, 'utf-8'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php deleted file mode 100644 index e15c6ef95b1..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php +++ /dev/null @@ -1,34 +0,0 @@ -_encoder = $encoder; - $this->_paramEncoder = $paramEncoder; - $this->_grammar = $grammar; - $this->_charset = $charset; + $this->encoder = $encoder; + $this->paramEncoder = $paramEncoder; + $this->emailValidator = $emailValidator; + $this->charset = $charset; } /** @@ -53,30 +58,30 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createMailboxHeader($name, $addresses = null) { - $header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar); + $header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator); if (isset($addresses)) { $header->setFieldBodyModel($addresses); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } /** - * Create a new Date header using $timestamp (UNIX time). + * Create a new Date header using $dateTime. * - * @param string $name - * @param int|null $timestamp + * @param string $name + * @param DateTimeInterface|null $dateTime * * @return Swift_Mime_Header */ - public function createDateHeader($name, $timestamp = null) + public function createDateHeader($name, DateTimeInterface $dateTime = null) { - $header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar); - if (isset($timestamp)) { - $header->setFieldBodyModel($timestamp); + $header = new Swift_Mime_Headers_DateHeader($name); + if (isset($dateTime)) { + $header->setFieldBodyModel($dateTime); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -91,11 +96,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createTextHeader($name, $value = null) { - $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder, $this->_grammar); + $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->encoder); if (isset($value)) { $header->setFieldBodyModel($value); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -107,19 +112,18 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory * @param string $value * @param array $params * - * @return Swift_Mime_ParameterizedHeader + * @return Swift_Mime_Headers_ParameterizedHeader */ - public function createParameterizedHeader($name, $value = null, - $params = array()) + public function createParameterizedHeader($name, $value = null, $params = array()) { - $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->_encoder, strtolower($name) == 'content-disposition' ? $this->_paramEncoder : null, $this->_grammar); + $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, (strtolower($name) == 'content-disposition') ? $this->paramEncoder : null); if (isset($value)) { $header->setFieldBodyModel($value); } foreach ($params as $k => $v) { $header->setParameter($k, $v); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -134,11 +138,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createIdHeader($name, $ids = null) { - $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar); + $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->emailValidator); if (isset($ids)) { $header->setFieldBodyModel($ids); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -153,11 +157,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function createPathHeader($name, $path = null) { - $header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar); + $header = new Swift_Mime_Headers_PathHeader($name, $this->emailValidator); if (isset($path)) { $header->setFieldBodyModel($path); } - $this->_setHeaderCharset($header); + $this->setHeaderCharset($header); return $header; } @@ -169,9 +173,9 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function charsetChanged($charset) { - $this->_charset = $charset; - $this->_encoder->charsetChanged($charset); - $this->_paramEncoder->charsetChanged($charset); + $this->charset = $charset; + $this->encoder->charsetChanged($charset); + $this->paramEncoder->charsetChanged($charset); } /** @@ -179,15 +183,15 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory */ public function __clone() { - $this->_encoder = clone $this->_encoder; - $this->_paramEncoder = clone $this->_paramEncoder; + $this->encoder = clone $this->encoder; + $this->paramEncoder = clone $this->paramEncoder; } /** Apply the charset to the Header */ - private function _setHeaderCharset(Swift_Mime_Header $header) + private function setHeaderCharset(Swift_Mime_Header $header) { - if (isset($this->_charset)) { - $header->setCharset($this->_charset); + if (isset($this->charset)) { + $header->setCharset($this->charset); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php index cf8bf14a750..6f71fcac132 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php @@ -13,37 +13,42 @@ * * @author Chris Corbyn */ -class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet +class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver { /** HeaderFactory */ - private $_factory; + private $factory; /** Collection of set Headers */ - private $_headers = array(); + private $headers = array(); /** Field ordering details */ - private $_order = array(); + private $order = array(); /** List of fields which are required to be displayed */ - private $_required = array(); + private $required = array(); /** The charset used by Headers */ - private $_charset; + private $charset; /** * Create a new SimpleHeaderSet with the given $factory. * - * @param Swift_Mime_HeaderFactory $factory - * @param string $charset + * @param Swift_Mime_SimpleHeaderFactory $factory + * @param string $charset */ - public function __construct(Swift_Mime_HeaderFactory $factory, $charset = null) + public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null) { - $this->_factory = $factory; + $this->factory = $factory; if (isset($charset)) { $this->setCharset($charset); } } + public function newInstance() + { + return new self($this->factory); + } + /** * Set the charset used by these headers. * @@ -51,9 +56,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function setCharset($charset) { - $this->_charset = $charset; - $this->_factory->charsetChanged($charset); - $this->_notifyHeadersOfCharset($charset); + $this->charset = $charset; + $this->factory->charsetChanged($charset); + $this->notifyHeadersOfCharset($charset); } /** @@ -64,20 +69,20 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addMailboxHeader($name, $addresses = null) { - $this->_storeHeader($name, - $this->_factory->createMailboxHeader($name, $addresses)); + $this->storeHeader($name, + $this->factory->createMailboxHeader($name, $addresses)); } /** - * Add a new Date header using $timestamp (UNIX time). + * Add a new Date header using $dateTime. * - * @param string $name - * @param int $timestamp + * @param string $name + * @param DateTimeInterface $dateTime */ - public function addDateHeader($name, $timestamp = null) + public function addDateHeader($name, DateTimeInterface $dateTime = null) { - $this->_storeHeader($name, - $this->_factory->createDateHeader($name, $timestamp)); + $this->storeHeader($name, + $this->factory->createDateHeader($name, $dateTime)); } /** @@ -88,8 +93,8 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addTextHeader($name, $value = null) { - $this->_storeHeader($name, - $this->_factory->createTextHeader($name, $value)); + $this->storeHeader($name, + $this->factory->createTextHeader($name, $value)); } /** @@ -101,7 +106,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addParameterizedHeader($name, $value = null, $params = array()) { - $this->_storeHeader($name, $this->_factory->createParameterizedHeader($name, $value, $params)); + $this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params)); } /** @@ -112,7 +117,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addIdHeader($name, $ids = null) { - $this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids)); + $this->storeHeader($name, $this->factory->createIdHeader($name, $ids)); } /** @@ -123,7 +128,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function addPathHeader($name, $path = null) { - $this->_storeHeader($name, $this->_factory->createPathHeader($name, $path)); + $this->storeHeader($name, $this->factory->createPathHeader($name, $path)); } /** @@ -140,7 +145,16 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet { $lowerName = strtolower($name); - return array_key_exists($lowerName, $this->_headers) && array_key_exists($index, $this->_headers[$lowerName]); + if (!array_key_exists($lowerName, $this->headers)) { + return false; + } + + if (func_num_args() < 2) { + // index was not specified, so we only need to check that there is at least one header value set + return (bool) count($this->headers[$lowerName]); + } + + return array_key_exists($index, $this->headers[$lowerName]); } /** @@ -157,7 +171,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function set(Swift_Mime_Header $header, $index = 0) { - $this->_storeHeader($header->getFieldName(), $header, $index); + $this->storeHeader($header->getFieldName(), $header, $index); } /** @@ -173,10 +187,18 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function get($name, $index = 0) { - if ($this->has($name, $index)) { - $lowerName = strtolower($name); + $name = strtolower($name); - return $this->_headers[$lowerName][$index]; + if (func_num_args() < 2) { + if ($this->has($name)) { + $values = array_values($this->headers[$name]); + + return array_shift($values); + } + } else { + if ($this->has($name, $index)) { + return $this->headers[$name][$index]; + } } } @@ -191,7 +213,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet { if (!isset($name)) { $headers = array(); - foreach ($this->_headers as $collection) { + foreach ($this->headers as $collection) { $headers = array_merge($headers, $collection); } @@ -199,11 +221,11 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet } $lowerName = strtolower($name); - if (!array_key_exists($lowerName, $this->_headers)) { + if (!array_key_exists($lowerName, $this->headers)) { return array(); } - return $this->_headers[$lowerName]; + return $this->headers[$lowerName]; } /** @@ -213,9 +235,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function listAll() { - $headers = $this->_headers; - if ($this->_canSort()) { - uksort($headers, array($this, '_sortHeaders')); + $headers = $this->headers; + if ($this->canSort()) { + uksort($headers, array($this, 'sortHeaders')); } return array_keys($headers); @@ -232,7 +254,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet public function remove($name, $index = 0) { $lowerName = strtolower($name); - unset($this->_headers[$lowerName][$index]); + unset($this->headers[$lowerName][$index]); } /** @@ -243,17 +265,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet public function removeAll($name) { $lowerName = strtolower($name); - unset($this->_headers[$lowerName]); - } - - /** - * Create a new instance of this HeaderSet. - * - * @return Swift_Mime_HeaderSet - */ - public function newInstance() - { - return new self($this->_factory); + unset($this->headers[$lowerName]); } /** @@ -265,7 +277,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function defineOrdering(array $sequence) { - $this->_order = array_flip(array_map('strtolower', $sequence)); + $this->order = array_flip(array_map('strtolower', $sequence)); } /** @@ -277,7 +289,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function setAlwaysDisplayed(array $names) { - $this->_required = array_flip(array_map('strtolower', $names)); + $this->required = array_flip(array_map('strtolower', $names)); } /** @@ -298,13 +310,13 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet public function toString() { $string = ''; - $headers = $this->_headers; - if ($this->_canSort()) { - uksort($headers, array($this, '_sortHeaders')); + $headers = $this->headers; + if ($this->canSort()) { + uksort($headers, array($this, 'sortHeaders')); } foreach ($headers as $collection) { foreach ($collection as $header) { - if ($this->_isDisplayed($header) || $header->getFieldBody() != '') { + if ($this->isDisplayed($header) || $header->getFieldBody() != '') { $string .= $header->toString(); } } @@ -326,31 +338,31 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet } /** Save a Header to the internal collection */ - private function _storeHeader($name, Swift_Mime_Header $header, $offset = null) + private function storeHeader($name, Swift_Mime_Header $header, $offset = null) { - if (!isset($this->_headers[strtolower($name)])) { - $this->_headers[strtolower($name)] = array(); + if (!isset($this->headers[strtolower($name)])) { + $this->headers[strtolower($name)] = array(); } if (!isset($offset)) { - $this->_headers[strtolower($name)][] = $header; + $this->headers[strtolower($name)][] = $header; } else { - $this->_headers[strtolower($name)][$offset] = $header; + $this->headers[strtolower($name)][$offset] = $header; } } /** Test if the headers can be sorted */ - private function _canSort() + private function canSort() { - return count($this->_order) > 0; + return count($this->order) > 0; } /** uksort() algorithm for Header ordering */ - private function _sortHeaders($a, $b) + private function sortHeaders($a, $b) { $lowerA = strtolower($a); $lowerB = strtolower($b); - $aPos = array_key_exists($lowerA, $this->_order) ? $this->_order[$lowerA] : -1; - $bPos = array_key_exists($lowerB, $this->_order) ? $this->_order[$lowerB] : -1; + $aPos = array_key_exists($lowerA, $this->order) ? $this->order[$lowerA] : -1; + $bPos = array_key_exists($lowerB, $this->order) ? $this->order[$lowerB] : -1; if (-1 === $aPos && -1 === $bPos) { // just be sure to be determinist here @@ -367,15 +379,15 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet } /** Test if the given Header is always displayed */ - private function _isDisplayed(Swift_Mime_Header $header) + private function isDisplayed(Swift_Mime_Header $header) { - return array_key_exists(strtolower($header->getFieldName()), $this->_required); + return array_key_exists(strtolower($header->getFieldName()), $this->required); } /** Notify all Headers of the new charset */ - private function _notifyHeadersOfCharset($charset) + private function notifyHeadersOfCharset($charset) { - foreach ($this->_headers as $headerGroup) { + foreach ($this->headers as $headerGroup) { foreach ($headerGroup as $header) { $header->setCharset($charset); } @@ -387,10 +399,10 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet */ public function __clone() { - $this->_factory = clone $this->_factory; - foreach ($this->_headers as $groupKey => $headerGroup) { + $this->factory = clone $this->factory; + foreach ($this->headers as $groupKey => $headerGroup) { foreach ($headerGroup as $key => $header) { - $this->_headers[$groupKey][$key] = clone $header; + $this->headers[$groupKey][$key] = clone $header; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php index 124644b5a93..768de07f812 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php @@ -13,20 +13,26 @@ * * @author Chris Corbyn */ -class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime_Message +class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart { + const PRIORITY_HIGHEST = 1; + const PRIORITY_HIGH = 2; + const PRIORITY_NORMAL = 3; + const PRIORITY_LOW = 4; + const PRIORITY_LOWEST = 5; + /** * Create a new SimpleMessage with $headers, $encoder and $cache. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar - * @param string $charset + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator + * @param string $charset */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $charset = null) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null) { - parent::__construct($headers, $encoder, $cache, $grammar, $charset); + parent::__construct($headers, $encoder, $cache, $idGenerator, $charset); $this->getHeaders()->defineOrdering(array( 'Return-Path', 'Received', @@ -47,7 +53,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime )); $this->getHeaders()->setAlwaysDisplayed(array('Date', 'Message-ID', 'From')); $this->getHeaders()->addTextHeader('MIME-Version', '1.0'); - $this->setDate(time()); + $this->setDate(new DateTimeImmutable()); $this->setId($this->getId()); $this->getHeaders()->addMailboxHeader('From'); } @@ -67,11 +73,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param string $subject * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setSubject($subject) { - if (!$this->_setHeaderFieldModel('Subject', $subject)) { + if (!$this->setHeaderFieldModel('Subject', $subject)) { $this->getHeaders()->addTextHeader('Subject', $subject); } @@ -85,20 +91,20 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getSubject() { - return $this->_getHeaderFieldModel('Subject'); + return $this->getHeaderFieldModel('Subject'); } /** * Set the date at which this message was created. * - * @param int $date + * @param DateTimeInterface $dateTime * - * @return Swift_Mime_SimpleMessage + * @return $this */ - public function setDate($date) + public function setDate(DateTimeInterface $dateTime) { - if (!$this->_setHeaderFieldModel('Date', $date)) { - $this->getHeaders()->addDateHeader('Date', $date); + if (!$this->setHeaderFieldModel('Date', $dateTime)) { + $this->getHeaders()->addDateHeader('Date', $dateTime); } return $this; @@ -107,11 +113,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime /** * Get the date at which this message was created. * - * @return int + * @return DateTimeInterface */ public function getDate() { - return $this->_getHeaderFieldModel('Date'); + return $this->getHeaderFieldModel('Date'); } /** @@ -119,11 +125,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param string $address * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setReturnPath($address) { - if (!$this->_setHeaderFieldModel('Return-Path', $address)) { + if (!$this->setHeaderFieldModel('Return-Path', $address)) { $this->getHeaders()->addPathHeader('Return-Path', $address); } @@ -137,7 +143,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getReturnPath() { - return $this->_getHeaderFieldModel('Return-Path'); + return $this->getHeaderFieldModel('Return-Path'); } /** @@ -148,7 +154,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setSender($address, $name = null) { @@ -156,7 +162,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $address = array($address => $name); } - if (!$this->_setHeaderFieldModel('Sender', (array) $address)) { + if (!$this->setHeaderFieldModel('Sender', (array) $address)) { $this->getHeaders()->addMailboxHeader('Sender', (array) $address); } @@ -170,7 +176,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getSender() { - return $this->_getHeaderFieldModel('Sender'); + return $this->getHeaderFieldModel('Sender'); } /** @@ -181,7 +187,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addFrom($address, $name = null) { @@ -202,7 +208,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string|array $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setFrom($addresses, $name = null) { @@ -210,7 +216,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('From', (array) $addresses)) { + if (!$this->setHeaderFieldModel('From', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('From', (array) $addresses); } @@ -224,7 +230,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getFrom() { - return $this->_getHeaderFieldModel('From'); + return $this->getHeaderFieldModel('From'); } /** @@ -235,7 +241,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addReplyTo($address, $name = null) { @@ -256,7 +262,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setReplyTo($addresses, $name = null) { @@ -264,7 +270,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses)) { + if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses); } @@ -278,7 +284,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getReplyTo() { - return $this->_getHeaderFieldModel('Reply-To'); + return $this->getHeaderFieldModel('Reply-To'); } /** @@ -289,7 +295,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addTo($address, $name = null) { @@ -311,7 +317,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setTo($addresses, $name = null) { @@ -319,7 +325,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('To', (array) $addresses)) { + if (!$this->setHeaderFieldModel('To', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('To', (array) $addresses); } @@ -333,7 +339,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getTo() { - return $this->_getHeaderFieldModel('To'); + return $this->getHeaderFieldModel('To'); } /** @@ -344,7 +350,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addCc($address, $name = null) { @@ -363,7 +369,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setCc($addresses, $name = null) { @@ -371,7 +377,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('Cc', (array) $addresses)) { + if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Cc', (array) $addresses); } @@ -385,7 +391,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getCc() { - return $this->_getHeaderFieldModel('Cc'); + return $this->getHeaderFieldModel('Cc'); } /** @@ -396,7 +402,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param string $address * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function addBcc($address, $name = null) { @@ -415,7 +421,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * @param mixed $addresses * @param string $name optional * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setBcc($addresses, $name = null) { @@ -423,7 +429,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime $addresses = array($addresses => $name); } - if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses)) { + if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses); } @@ -437,7 +443,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getBcc() { - return $this->_getHeaderFieldModel('Bcc'); + return $this->getHeaderFieldModel('Bcc'); } /** @@ -447,16 +453,16 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param int $priority * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setPriority($priority) { $priorityMap = array( - 1 => 'Highest', - 2 => 'High', - 3 => 'Normal', - 4 => 'Low', - 5 => 'Lowest', + self::PRIORITY_HIGHEST => 'Highest', + self::PRIORITY_HIGH => 'High', + self::PRIORITY_NORMAL => 'Normal', + self::PRIORITY_LOW => 'Low', + self::PRIORITY_LOWEST => 'Lowest', ); $pMapKeys = array_keys($priorityMap); if ($priority > max($pMapKeys)) { @@ -464,7 +470,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime } elseif ($priority < min($pMapKeys)) { $priority = min($pMapKeys); } - if (!$this->_setHeaderFieldModel('X-Priority', + if (!$this->setHeaderFieldModel('X-Priority', sprintf('%d (%s)', $priority, $priorityMap[$priority]))) { $this->getHeaders()->addTextHeader('X-Priority', sprintf('%d (%s)', $priority, $priorityMap[$priority])); @@ -483,11 +489,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getPriority() { - list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'), + list($priority) = sscanf($this->getHeaderFieldModel('X-Priority'), '%[1-5]' ); - return isset($priority) ? $priority : 3; + return $priority ?? 3; } /** @@ -495,11 +501,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime * * @param array $addresses * - * @return Swift_Mime_SimpleMessage + * @return $this */ public function setReadReceiptTo($addresses) { - if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses)) { + if (!$this->setHeaderFieldModel('Disposition-Notification-To', $addresses)) { $this->getHeaders() ->addMailboxHeader('Disposition-Notification-To', $addresses); } @@ -514,17 +520,17 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime */ public function getReadReceiptTo() { - return $this->_getHeaderFieldModel('Disposition-Notification-To'); + return $this->getHeaderFieldModel('Disposition-Notification-To'); } /** - * Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart. + * Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart. * - * @param Swift_Mime_MimeEntity $entity + * @param Swift_Mime_SimpleMimeEntity $entity * - * @return Swift_Mime_SimpleMessage + * @return $this */ - public function attach(Swift_Mime_MimeEntity $entity) + public function attach(Swift_Mime_SimpleMimeEntity $entity) { $this->setChildren(array_merge($this->getChildren(), array($entity))); @@ -534,11 +540,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime /** * Remove an already attached entity. * - * @param Swift_Mime_MimeEntity $entity + * @param Swift_Mime_SimpleMimeEntity $entity * - * @return Swift_Mime_SimpleMessage + * @return $this */ - public function detach(Swift_Mime_MimeEntity $entity) + public function detach(Swift_Mime_SimpleMimeEntity $entity) { $newChildren = array(); foreach ($this->getChildren() as $child) { @@ -552,14 +558,14 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime } /** - * Attach a {@link Swift_Mime_MimeEntity} and return it's CID source. + * Attach a {@link Swift_Mime_SimpleMimeEntity} and return it's CID source. * This method should be used when embedding images or other data in a message. * - * @param Swift_Mime_MimeEntity $entity + * @param Swift_Mime_SimpleMimeEntity $entity * * @return string */ - public function embed(Swift_Mime_MimeEntity $entity) + public function embed(Swift_Mime_SimpleMimeEntity $entity) { $this->attach($entity); @@ -574,7 +580,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime public function toString() { if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { - $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); + $this->setChildren(array_merge(array($this->becomeMimePart()), $children)); $string = parent::toString(); $this->setChildren($children); } else { @@ -604,7 +610,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime public function toByteStream(Swift_InputByteStream $is) { if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { - $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); + $this->setChildren(array_merge(array($this->becomeMimePart()), $children)); parent::toByteStream($is); $this->setChildren($children); } else { @@ -612,29 +618,29 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime } } - /** @see Swift_Mime_SimpleMimeEntity::_getIdField() */ - protected function _getIdField() + /** @see Swift_Mime_SimpleMimeEntity::getIdField() */ + protected function getIdField() { return 'Message-ID'; } /** Turn the body of this message into a child of itself if needed */ - protected function _becomeMimePart() + protected function becomeMimePart() { $part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(), - $this->_getCache(), $this->_getGrammar(), $this->_userCharset + $this->getCache(), $this->getIdGenerator(), $this->userCharset ); - $part->setContentType($this->_userContentType); + $part->setContentType($this->userContentType); $part->setBody($this->getBody()); - $part->setFormat($this->_userFormat); - $part->setDelSp($this->_userDelSp); - $part->_setNestingLevel($this->_getTopNestingLevel()); + $part->setFormat($this->userFormat); + $part->setDelSp($this->userDelSp); + $part->setNestingLevel($this->getTopNestingLevel()); return $part; } /** Get the highest nesting level nested inside this message */ - private function _getTopNestingLevel() + private function getTopNestingLevel() { $highestLevel = $this->getNestingLevel(); foreach ($this->getChildren() as $child) { diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php index 6b91718fb85..2d1a9b47d56 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php @@ -13,79 +13,91 @@ * * @author Chris Corbyn */ -class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity +class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_Mime_EncodingObserver { + /** Main message document; there can only be one of these */ + const LEVEL_TOP = 16; + + /** An entity which nests with the same precedence as an attachment */ + const LEVEL_MIXED = 256; + + /** An entity which nests with the same precedence as a mime part */ + const LEVEL_ALTERNATIVE = 4096; + + /** An entity which nests with the same precedence as embedded content */ + const LEVEL_RELATED = 65536; + /** A collection of Headers for this mime entity */ - private $_headers; + private $headers; /** The body as a string, or a stream */ - private $_body; + private $body; /** The encoder that encodes the body into a streamable format */ - private $_encoder; + private $encoder; - /** The grammar to use for id validation */ - private $_grammar; + /** Message ID generator */ + private $idGenerator; /** A mime boundary, if any is used */ - private $_boundary; + private $boundary; /** Mime types to be used based on the nesting level */ - private $_compositeRanges = array( + private $compositeRanges = array( 'multipart/mixed' => array(self::LEVEL_TOP, self::LEVEL_MIXED), 'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE), 'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED), ); /** A set of filter rules to define what level an entity should be nested at */ - private $_compoundLevelFilters = array(); + private $compoundLevelFilters = array(); /** The nesting level of this entity */ - private $_nestingLevel = self::LEVEL_ALTERNATIVE; + private $nestingLevel = self::LEVEL_ALTERNATIVE; /** A KeyCache instance used during encoding and streaming */ - private $_cache; + private $cache; /** Direct descendants of this entity */ - private $_immediateChildren = array(); + private $immediateChildren = array(); /** All descendants of this entity */ - private $_children = array(); + private $children = array(); /** The maximum line length of the body of this entity */ - private $_maxLineLength = 78; + private $maxLineLength = 78; /** The order in which alternative mime types should appear */ - private $_alternativePartOrder = array( + private $alternativePartOrder = array( 'text/plain' => 1, 'text/html' => 2, 'multipart/related' => 3, ); /** The CID of this entity */ - private $_id; + private $id; /** The key used for accessing the cache */ - private $_cacheKey; + private $cacheKey; - protected $_userContentType; + protected $userContentType; /** * Create a new SimpleMimeEntity with $headers, $encoder and $cache. * - * @param Swift_Mime_HeaderSet $headers - * @param Swift_Mime_ContentEncoder $encoder - * @param Swift_KeyCache $cache - * @param Swift_Mime_Grammar $grammar + * @param Swift_Mime_SimpleHeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_IdGenerator $idGenerator */ - public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar) + public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator) { - $this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true)); - $this->_cache = $cache; - $this->_headers = $headers; - $this->_grammar = $grammar; + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values + $this->cache = $cache; + $this->headers = $headers; + $this->idGenerator = $idGenerator; $this->setEncoder($encoder); - $this->_headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); + $this->headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); // This array specifies that, when the entire MIME document contains // $compoundLevel, then for each child within $level, if its Content-Type @@ -100,7 +112,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity // ) // ) - $this->_compoundLevelFilters = array( + $this->compoundLevelFilters = array( (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array( self::LEVEL_ALTERNATIVE => array( 'text/plain' => self::LEVEL_ALTERNATIVE, @@ -109,7 +121,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity ), ); - $this->_id = $this->getRandomId(); + $this->id = $this->idGenerator->generateId(); } /** @@ -119,19 +131,19 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function generateId() { - $this->setId($this->getRandomId()); + $this->setId($this->idGenerator->generateId()); - return $this->_id; + return $this->id; } /** - * Get the {@link Swift_Mime_HeaderSet} for this entity. + * Get the {@link Swift_Mime_SimpleHeaderSet} for this entity. * - * @return Swift_Mime_HeaderSet + * @return Swift_Mime_SimpleHeaderSet */ public function getHeaders() { - return $this->_headers; + return $this->headers; } /** @@ -143,7 +155,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getNestingLevel() { - return $this->_nestingLevel; + return $this->nestingLevel; } /** @@ -153,7 +165,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getContentType() { - return $this->_getHeaderFieldModel('Content-Type'); + return $this->getHeaderFieldModel('Content-Type'); } /** @@ -161,14 +173,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param string $type * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setContentType($type) { - $this->_setContentTypeInHeaders($type); + $this->setContentTypeInHeaders($type); // Keep track of the value so that if the content-type changes automatically // due to added child entities, it can be restored if they are later removed - $this->_userContentType = $type; + $this->userContentType = $type; return $this; } @@ -182,9 +194,9 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getId() { - $tmp = (array) $this->_getHeaderFieldModel($this->_getIdField()); + $tmp = (array) $this->getHeaderFieldModel($this->getIdField()); - return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id; + return $this->headers->has($this->getIdField()) ? current($tmp) : $this->id; } /** @@ -192,14 +204,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param string $id * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setId($id) { - if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) { - $this->_headers->addIdHeader($this->_getIdField(), $id); + if (!$this->setHeaderFieldModel($this->getIdField(), $id)) { + $this->headers->addIdHeader($this->getIdField(), $id); } - $this->_id = $id; + $this->id = $id; return $this; } @@ -213,7 +225,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getDescription() { - return $this->_getHeaderFieldModel('Content-Description'); + return $this->getHeaderFieldModel('Content-Description'); } /** @@ -223,12 +235,12 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param string $description * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setDescription($description) { - if (!$this->_setHeaderFieldModel('Content-Description', $description)) { - $this->_headers->addTextHeader('Content-Description', $description); + if (!$this->setHeaderFieldModel('Content-Description', $description)) { + $this->headers->addTextHeader('Content-Description', $description); } return $this; @@ -241,7 +253,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getMaxLineLength() { - return $this->_maxLineLength; + return $this->maxLineLength; } /** @@ -251,11 +263,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param int $length * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setMaxLineLength($length) { - $this->_maxLineLength = $length; + $this->maxLineLength = $length; return $this; } @@ -263,37 +275,36 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get all children added to this entity. * - * @return Swift_Mime_MimeEntity[] + * @return Swift_Mime_SimpleMimeEntity[] */ public function getChildren() { - return $this->_children; + return $this->children; } /** * Set all children of this entity. * - * @param Swift_Mime_MimeEntity[] $children - * @param int $compoundLevel For internal use only + * @param Swift_Mime_SimpleMimeEntity[] $children + * @param int $compoundLevel For internal use only * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setChildren(array $children, $compoundLevel = null) { // TODO: Try to refactor this logic - - $compoundLevel = isset($compoundLevel) ? $compoundLevel : $this->_getCompoundLevel($children); + $compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children); $immediateChildren = array(); $grandchildren = array(); - $newContentType = $this->_userContentType; + $newContentType = $this->userContentType; foreach ($children as $child) { - $level = $this->_getNeededChildLevel($child, $compoundLevel); + $level = $this->getNeededChildLevel($child, $compoundLevel); if (empty($immediateChildren)) { //first iteration $immediateChildren = array($child); } else { - $nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); + $nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); if ($nextLevel == $level) { $immediateChildren[] = $child; } elseif ($level < $nextLevel) { @@ -308,11 +319,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity } if ($immediateChildren) { - $lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); + $lowestLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel); // Determine which composite media type is needed to accommodate the // immediate children - foreach ($this->_compositeRanges as $mediaType => $range) { + foreach ($this->compositeRanges as $mediaType => $range) { if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) { $newContentType = $mediaType; @@ -322,18 +333,18 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity // Put any grandchildren in a subpart if (!empty($grandchildren)) { - $subentity = $this->_createChild(); - $subentity->_setNestingLevel($lowestLevel); + $subentity = $this->createChild(); + $subentity->setNestingLevel($lowestLevel); $subentity->setChildren($grandchildren, $compoundLevel); array_unshift($immediateChildren, $subentity); } } - $this->_immediateChildren = $immediateChildren; - $this->_children = $children; - $this->_setContentTypeInHeaders($newContentType); - $this->_fixHeaders(); - $this->_sortChildren(); + $this->immediateChildren = $immediateChildren; + $this->children = $children; + $this->setContentTypeInHeaders($newContentType); + $this->fixHeaders(); + $this->sortChildren(); return $this; } @@ -345,7 +356,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getBody() { - return $this->_body instanceof Swift_OutputByteStream ? $this->_readStream($this->_body) : $this->_body; + return $this->body instanceof Swift_OutputByteStream ? $this->readStream($this->body) : $this->body; } /** @@ -355,15 +366,15 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * @param mixed $body * @param string $contentType optional * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setBody($body, $contentType = null) { - if ($body !== $this->_body) { - $this->_clearCache(); + if ($body !== $this->body) { + $this->clearCache(); } - $this->_body = $body; + $this->body = $body; if (isset($contentType)) { $this->setContentType($contentType); } @@ -378,7 +389,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getEncoder() { - return $this->_encoder; + return $this->encoder; } /** @@ -386,17 +397,17 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param Swift_Mime_ContentEncoder $encoder * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setEncoder(Swift_Mime_ContentEncoder $encoder) { - if ($encoder !== $this->_encoder) { - $this->_clearCache(); + if ($encoder !== $this->encoder) { + $this->clearCache(); } - $this->_encoder = $encoder; - $this->_setEncoding($encoder->getName()); - $this->_notifyEncoderChanged($encoder); + $this->encoder = $encoder; + $this->setEncoding($encoder->getName()); + $this->notifyEncoderChanged($encoder); return $this; } @@ -408,11 +419,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function getBoundary() { - if (!isset($this->_boundary)) { - $this->_boundary = '_=_swift_v4_'.time().'_'.md5(getmypid().mt_rand().uniqid('', true)).'_=_'; + if (!isset($this->boundary)) { + $this->boundary = '_=_swift_'.time().'_'.bin2hex(random_bytes(16)).'_=_'; } - return $this->_boundary; + return $this->boundary; } /** @@ -422,12 +433,12 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @throws Swift_RfcComplianceException * - * @return Swift_Mime_SimpleMimeEntity + * @return $this */ public function setBoundary($boundary) { - $this->_assertValidBoundary($boundary); - $this->_boundary = $boundary; + $this->assertValidBoundary($boundary); + $this->boundary = $boundary; return $this; } @@ -440,7 +451,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function charsetChanged($charset) { - $this->_notifyCharsetChanged($charset); + $this->notifyCharsetChanged($charset); } /** @@ -451,7 +462,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function encoderChanged(Swift_Mime_ContentEncoder $encoder) { - $this->_notifyEncoderChanged($encoder); + $this->notifyEncoderChanged($encoder); } /** @@ -461,8 +472,8 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function toString() { - $string = $this->_headers->toString(); - $string .= $this->_bodyToString(); + $string = $this->headers->toString(); + $string .= $this->bodyToString(); return $string; } @@ -472,22 +483,22 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @return string */ - protected function _bodyToString() + protected function bodyToString() { $string = ''; - if (isset($this->_body) && empty($this->_immediateChildren)) { - if ($this->_cache->hasKey($this->_cacheKey, 'body')) { - $body = $this->_cache->getString($this->_cacheKey, 'body'); + if (isset($this->body) && empty($this->immediateChildren)) { + if ($this->cache->hasKey($this->cacheKey, 'body')) { + $body = $this->cache->getString($this->cacheKey, 'body'); } else { - $body = "\r\n".$this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()); - $this->_cache->setString($this->_cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE); + $body = "\r\n".$this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()); + $this->cache->setString($this->cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE); } $string .= $body; } - if (!empty($this->_immediateChildren)) { - foreach ($this->_immediateChildren as $child) { + if (!empty($this->immediateChildren)) { + foreach ($this->immediateChildren as $child) { $string .= "\r\n\r\n--".$this->getBoundary()."\r\n"; $string .= $child->toString(); } @@ -516,10 +527,10 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function toByteStream(Swift_InputByteStream $is) { - $is->write($this->_headers->toString()); + $is->write($this->headers->toString()); $is->commit(); - $this->_bodyToByteStream($is); + $this->bodyToByteStream($is); } /** @@ -527,26 +538,26 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @param Swift_InputByteStream */ - protected function _bodyToByteStream(Swift_InputByteStream $is) + protected function bodyToByteStream(Swift_InputByteStream $is) { - if (empty($this->_immediateChildren)) { - if (isset($this->_body)) { - if ($this->_cache->hasKey($this->_cacheKey, 'body')) { - $this->_cache->exportToByteStream($this->_cacheKey, 'body', $is); + if (empty($this->immediateChildren)) { + if (isset($this->body)) { + if ($this->cache->hasKey($this->cacheKey, 'body')) { + $this->cache->exportToByteStream($this->cacheKey, 'body', $is); } else { - $cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body'); + $cacheIs = $this->cache->getInputByteStream($this->cacheKey, 'body'); if ($cacheIs) { $is->bind($cacheIs); } $is->write("\r\n"); - if ($this->_body instanceof Swift_OutputByteStream) { - $this->_body->setReadPointer(0); + if ($this->body instanceof Swift_OutputByteStream) { + $this->body->setReadPointer(0); - $this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength()); + $this->encoder->encodeByteStream($this->body, $is, 0, $this->getMaxLineLength()); } else { - $is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); + $is->write($this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); } if ($cacheIs) { @@ -556,8 +567,8 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity } } - if (!empty($this->_immediateChildren)) { - foreach ($this->_immediateChildren as $child) { + if (!empty($this->immediateChildren)) { + foreach ($this->immediateChildren as $child) { $is->write("\r\n\r\n--".$this->getBoundary()."\r\n"); $child->toByteStream($is); } @@ -568,7 +579,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get the name of the header that provides the ID of this entity. */ - protected function _getIdField() + protected function getIdField() { return 'Content-ID'; } @@ -576,20 +587,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get the model data (usually an array or a string) for $field. */ - protected function _getHeaderFieldModel($field) + protected function getHeaderFieldModel($field) { - if ($this->_headers->has($field)) { - return $this->_headers->get($field)->getFieldBodyModel(); + if ($this->headers->has($field)) { + return $this->headers->get($field)->getFieldBodyModel(); } } /** * Set the model data for $field. */ - protected function _setHeaderFieldModel($field, $model) + protected function setHeaderFieldModel($field, $model) { - if ($this->_headers->has($field)) { - $this->_headers->get($field)->setFieldBodyModel($model); + if ($this->headers->has($field)) { + $this->headers->get($field)->setFieldBodyModel($model); return true; } @@ -600,20 +611,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Get the parameter value of $parameter on $field header. */ - protected function _getHeaderParameter($field, $parameter) + protected function getHeaderParameter($field, $parameter) { - if ($this->_headers->has($field)) { - return $this->_headers->get($field)->getParameter($parameter); + if ($this->headers->has($field)) { + return $this->headers->get($field)->getParameter($parameter); } } /** * Set the parameter value of $parameter on $field header. */ - protected function _setHeaderParameter($field, $parameter, $value) + protected function setHeaderParameter($field, $parameter, $value) { - if ($this->_headers->has($field)) { - $this->_headers->get($field)->setParameter($parameter, $value); + if ($this->headers->has($field)) { + $this->headers->get($field)->setParameter($parameter, $value); return true; } @@ -624,16 +635,16 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity /** * Re-evaluate what content type and encoding should be used on this entity. */ - protected function _fixHeaders() + protected function fixHeaders() { - if (count($this->_immediateChildren)) { - $this->_setHeaderParameter('Content-Type', 'boundary', + if (count($this->immediateChildren)) { + $this->setHeaderParameter('Content-Type', 'boundary', $this->getBoundary() ); - $this->_headers->remove('Content-Transfer-Encoding'); + $this->headers->remove('Content-Transfer-Encoding'); } else { - $this->_setHeaderParameter('Content-Type', 'boundary', null); - $this->_setEncoding($this->_encoder->getName()); + $this->setHeaderParameter('Content-Type', 'boundary', null); + $this->setEncoding($this->encoder->getName()); } } @@ -642,50 +653,30 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity * * @return Swift_KeyCache */ - protected function _getCache() + protected function getCache() { - return $this->_cache; + return $this->cache; } /** - * Get the grammar used for validation. + * Get the ID generator. * - * @return Swift_Mime_Grammar + * @return Swift_IdGenerator */ - protected function _getGrammar() + protected function getIdGenerator() { - return $this->_grammar; + return $this->idGenerator; } /** * Empty the KeyCache for this entity. */ - protected function _clearCache() + protected function clearCache() { - $this->_cache->clearKey($this->_cacheKey, 'body'); + $this->cache->clearKey($this->cacheKey, 'body'); } - /** - * Returns a random Content-ID or Message-ID. - * - * @return string - */ - protected function getRandomId() - { - $idLeft = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); - $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated'; - $id = $idLeft.'@'.$idRight; - - try { - $this->_assertValidId($id); - } catch (Swift_RfcComplianceException $e) { - $id = $idLeft.'@swift.generated'; - } - - return $id; - } - - private function _readStream(Swift_OutputByteStream $os) + private function readStream(Swift_OutputByteStream $os) { $string = ''; while (false !== $bytes = $os->read(8192)) { @@ -697,33 +688,33 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity return $string; } - private function _setEncoding($encoding) + private function setEncoding($encoding) { - if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { - $this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding); + if (!$this->setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { + $this->headers->addTextHeader('Content-Transfer-Encoding', $encoding); } } - private function _assertValidBoundary($boundary) + private function assertValidBoundary($boundary) { if (!preg_match('/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', $boundary)) { throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.'); } } - private function _setContentTypeInHeaders($type) + private function setContentTypeInHeaders($type) { - if (!$this->_setHeaderFieldModel('Content-Type', $type)) { - $this->_headers->addParameterizedHeader('Content-Type', $type); + if (!$this->setHeaderFieldModel('Content-Type', $type)) { + $this->headers->addParameterizedHeader('Content-Type', $type); } } - private function _setNestingLevel($level) + private function setNestingLevel($level) { - $this->_nestingLevel = $level; + $this->nestingLevel = $level; } - private function _getCompoundLevel($children) + private function getCompoundLevel($children) { $level = 0; foreach ($children as $child) { @@ -733,10 +724,10 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity return $level; } - private function _getNeededChildLevel($child, $compoundLevel) + private function getNeededChildLevel($child, $compoundLevel) { $filter = array(); - foreach ($this->_compoundLevelFilters as $bitmask => $rules) { + foreach ($this->compoundLevelFilters as $bitmask => $rules) { if (($compoundLevel & $bitmask) === $bitmask) { $filter = $rules + $filter; } @@ -752,31 +743,31 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity return $realLevel; } - private function _createChild() + private function createChild() { - return new self($this->_headers->newInstance(), $this->_encoder, $this->_cache, $this->_grammar); + return new self($this->headers->newInstance(), $this->encoder, $this->cache, $this->idGenerator); } - private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) + private function notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) { - foreach ($this->_immediateChildren as $child) { + foreach ($this->immediateChildren as $child) { $child->encoderChanged($encoder); } } - private function _notifyCharsetChanged($charset) + private function notifyCharsetChanged($charset) { - $this->_encoder->charsetChanged($charset); - $this->_headers->charsetChanged($charset); - foreach ($this->_immediateChildren as $child) { + $this->encoder->charsetChanged($charset); + $this->headers->charsetChanged($charset); + foreach ($this->immediateChildren as $child) { $child->charsetChanged($charset); } } - private function _sortChildren() + private function sortChildren() { $shouldSort = false; - foreach ($this->_immediateChildren as $child) { + foreach ($this->immediateChildren as $child) { // NOTE: This include alternative parts moved into a related part if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) { $shouldSort = true; @@ -786,43 +777,32 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity // Sort in order of preference, if there is one if ($shouldSort) { - usort($this->_immediateChildren, array($this, '_childSortAlgorithm')); + // Group the messages by order of preference + $sorted = array(); + foreach ($this->immediateChildren as $child) { + $type = $child->getContentType(); + $level = array_key_exists($type, $this->alternativePartOrder) ? $this->alternativePartOrder[$type] : max($this->alternativePartOrder) + 1; + + if (empty($sorted[$level])) { + $sorted[$level] = array(); + } + + $sorted[$level][] = $child; + } + + ksort($sorted); + + $this->immediateChildren = array_reduce($sorted, 'array_merge', array()); } } - private function _childSortAlgorithm($a, $b) - { - $typePrefs = array(); - $types = array(strtolower($a->getContentType()), strtolower($b->getContentType())); - - foreach ($types as $type) { - $typePrefs[] = array_key_exists($type, $this->_alternativePartOrder) ? $this->_alternativePartOrder[$type] : max($this->_alternativePartOrder) + 1; - } - - return $typePrefs[0] >= $typePrefs[1] ? 1 : -1; - } - - // -- Destructor - /** * Empties it's own contents from the cache. */ public function __destruct() { - $this->_cache->clearAll($this->_cacheKey); - } - - /** - * Throws an Exception if the id passed does not comply with RFC 2822. - * - * @param string $id - * - * @throws Swift_RfcComplianceException - */ - private function _assertValidId($id) - { - if (!preg_match('/^'.$this->_grammar->getDefinition('id-left').'@'.$this->_grammar->getDefinition('id-right').'$/D', $id)) { - throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>'); + if ($this->cache instanceof Swift_KeyCache) { + $this->cache->clearAll($this->cacheKey); } } @@ -831,11 +811,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity */ public function __clone() { - $this->_headers = clone $this->_headers; - $this->_encoder = clone $this->_encoder; - $this->_cacheKey = uniqid(); + $this->headers = clone $this->headers; + $this->encoder = clone $this->encoder; + $this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values $children = array(); - foreach ($this->_children as $pos => $child) { + foreach ($this->children as $pos => $child) { $children[$pos] = clone $child; } $this->setChildren($children); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php b/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php index 215f8db348a..8fa0cbebcd2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/MimePart.php @@ -42,18 +42,4 @@ class Swift_MimePart extends Swift_Mime_MimePart $this->setContentType($contentType); } } - - /** - * Create a new MimePart. - * - * @param string $body - * @param string $contentType - * @param string $charset - * - * @return Swift_Mime_MimePart - */ - public static function newInstance($body = null, $contentType = null, $charset = null) - { - return new self($body, $contentType, $charset); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php index b38e1cf7697..a580dfbefb6 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/NullTransport.php @@ -15,9 +15,6 @@ */ class Swift_NullTransport extends Swift_Transport_NullTransport { - /** - * Create a new NullTransport. - */ public function __construct() { call_user_func_array( @@ -26,14 +23,4 @@ class Swift_NullTransport extends Swift_Transport_NullTransport ->createDependenciesFor('transport.null') ); } - - /** - * Create a new NullTransport instance. - * - * @return Swift_NullTransport - */ - public static function newInstance() - { - return new self(); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php index a2ec2abcd50..06b3109e62c 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php @@ -20,28 +20,28 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ * * @var int */ - private $_threshold; + private $threshold; /** * The number of seconds to sleep for during a restart. * * @var int */ - private $_sleep; + private $sleep; /** * The internal counter. * * @var int */ - private $_counter = 0; + private $counter = 0; /** * The Sleeper instance for sleeping. * * @var Swift_Plugins_Sleeper */ - private $_sleeper; + private $sleeper; /** * Create a new AntiFloodPlugin with $threshold and $sleep time. @@ -54,7 +54,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ { $this->setThreshold($threshold); $this->setSleepTime($sleep); - $this->_sleeper = $sleeper; + $this->sleeper = $sleeper; } /** @@ -64,7 +64,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function setThreshold($threshold) { - $this->_threshold = $threshold; + $this->threshold = $threshold; } /** @@ -74,7 +74,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function getThreshold() { - return $this->_threshold; + return $this->threshold; } /** @@ -84,7 +84,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function setSleepTime($sleep) { - $this->_sleep = $sleep; + $this->sleep = $sleep; } /** @@ -94,7 +94,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function getSleepTime() { - return $this->_sleep; + return $this->sleep; } /** @@ -113,15 +113,15 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function sendPerformed(Swift_Events_SendEvent $evt) { - ++$this->_counter; - if ($this->_counter >= $this->_threshold) { + ++$this->counter; + if ($this->counter >= $this->threshold) { $transport = $evt->getTransport(); $transport->stop(); - if ($this->_sleep) { - $this->sleep($this->_sleep); + if ($this->sleep) { + $this->sleep($this->sleep); } $transport->start(); - $this->_counter = 0; + $this->counter = 0; } } @@ -132,8 +132,8 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_ */ public function sleep($seconds) { - if (isset($this->_sleeper)) { - $this->_sleeper->sleep($seconds); + if (isset($this->sleeper)) { + $this->sleeper->sleep($seconds); } else { sleep($seconds); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php index f7e18d0ebea..af060a99cc3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php @@ -20,17 +20,17 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, * * @var int */ - private $_out = 0; + private $out = 0; /** * The incoming traffic counter. * * @var int */ - private $_in = 0; + private $in = 0; /** Bound byte streams */ - private $_mirrors = array(); + private $mirrors = array(); /** * Not used. @@ -58,7 +58,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, public function commandSent(Swift_Events_CommandEvent $evt) { $command = $evt->getCommand(); - $this->_out += strlen($command); + $this->out += strlen($command); } /** @@ -69,7 +69,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, public function responseReceived(Swift_Events_ResponseEvent $evt) { $response = $evt->getResponse(); - $this->_in += strlen($response); + $this->in += strlen($response); } /** @@ -79,8 +79,8 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function write($bytes) { - $this->_out += strlen($bytes); - foreach ($this->_mirrors as $stream) { + $this->out += strlen($bytes); + foreach ($this->mirrors as $stream) { $stream->write($bytes); } } @@ -102,7 +102,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function bind(Swift_InputByteStream $is) { - $this->_mirrors[] = $is; + $this->mirrors[] = $is; } /** @@ -116,9 +116,9 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function unbind(Swift_InputByteStream $is) { - foreach ($this->_mirrors as $k => $stream) { + foreach ($this->mirrors as $k => $stream) { if ($is === $stream) { - unset($this->_mirrors[$k]); + unset($this->mirrors[$k]); } } } @@ -128,7 +128,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function flushBuffers() { - foreach ($this->_mirrors as $stream) { + foreach ($this->mirrors as $stream) { $stream->flushBuffers(); } } @@ -140,7 +140,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function getBytesOut() { - return $this->_out; + return $this->out; } /** @@ -150,7 +150,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function getBytesIn() { - return $this->_in; + return $this->in; } /** @@ -158,7 +158,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener, */ public function reset() { - $this->_out = 0; - $this->_in = 0; + $this->out = 0; + $this->in = 0; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php index 0762b36d218..9d5feefb92c 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php @@ -17,19 +17,19 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_Plugins_Decorator_Replacements { /** The replacement map */ - private $_replacements; + private $replacements; /** The body as it was before replacements */ - private $_originalBody; + private $originalBody; /** The original headers of the message, before replacements */ - private $_originalHeaders = array(); + private $originalHeaders = array(); /** Bodies of children before they are replaced */ - private $_originalChildBodies = array(); + private $originalChildBodies = array(); /** The Message that was last replaced */ - private $_lastMessage; + private $lastMessage; /** * Create a new DecoratorPlugin with $replacements. @@ -66,9 +66,9 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ public function setReplacements($replacements) { if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) { - $this->_replacements = (array) $replacements; + $this->replacements = (array) $replacements; } else { - $this->_replacements = $replacements; + $this->replacements = $replacements; } } @@ -80,7 +80,7 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); - $this->_restoreMessage($message); + $this->restoreMessage($message); $to = array_keys($message->getTo()); $address = array_shift($to); if ($replacements = $this->getReplacementsFor($address)) { @@ -91,7 +91,7 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ $search, $replace, $body ); if ($body != $bodyReplaced) { - $this->_originalBody = $body; + $this->originalBody = $body; $message->setBody($bodyReplaced); } @@ -111,12 +111,12 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ $count = 1; } } - } else { + } elseif (is_string($body)) { $bodyReplaced = str_replace($search, $replace, $body, $count); } if ($count) { - $this->_originalHeaders[$header->getFieldName()] = $body; + $this->originalHeaders[$header->getFieldName()] = $body; $header->setFieldBodyModel($bodyReplaced); } } @@ -131,11 +131,11 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ ); if ($body != $bodyReplaced) { $child->setBody($bodyReplaced); - $this->_originalChildBodies[$child->getId()] = $body; + $this->originalChildBodies[$child->getId()] = $body; } } } - $this->_lastMessage = $message; + $this->lastMessage = $message; } } @@ -155,11 +155,11 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ */ public function getReplacementsFor($address) { - if ($this->_replacements instanceof Swift_Plugins_Decorator_Replacements) { - return $this->_replacements->getReplacementsFor($address); + if ($this->replacements instanceof Swift_Plugins_Decorator_Replacements) { + return $this->replacements->getReplacementsFor($address); } - return isset($this->_replacements[$address]) ? $this->_replacements[$address] : null; + return $this->replacements[$address] ?? null; } /** @@ -169,36 +169,36 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_ */ public function sendPerformed(Swift_Events_SendEvent $evt) { - $this->_restoreMessage($evt->getMessage()); + $this->restoreMessage($evt->getMessage()); } /** Restore a changed message back to its original state */ - private function _restoreMessage(Swift_Mime_Message $message) + private function restoreMessage(Swift_Mime_SimpleMessage $message) { - if ($this->_lastMessage === $message) { - if (isset($this->_originalBody)) { - $message->setBody($this->_originalBody); - $this->_originalBody = null; + if ($this->lastMessage === $message) { + if (isset($this->originalBody)) { + $message->setBody($this->originalBody); + $this->originalBody = null; } - if (!empty($this->_originalHeaders)) { + if (!empty($this->originalHeaders)) { foreach ($message->getHeaders()->getAll() as $header) { - if (array_key_exists($header->getFieldName(), $this->_originalHeaders)) { - $header->setFieldBodyModel($this->_originalHeaders[$header->getFieldName()]); + if (array_key_exists($header->getFieldName(), $this->originalHeaders)) { + $header->setFieldBodyModel($this->originalHeaders[$header->getFieldName()]); } } - $this->_originalHeaders = array(); + $this->originalHeaders = array(); } - if (!empty($this->_originalChildBodies)) { + if (!empty($this->originalChildBodies)) { $children = (array) $message->getChildren(); foreach ($children as $child) { $id = $child->getId(); - if (array_key_exists($id, $this->_originalChildBodies)) { - $child->setBody($this->_originalChildBodies[$id]); + if (array_key_exists($id, $this->originalChildBodies)) { + $child->setBody($this->originalChildBodies[$id]); } } - $this->_originalChildBodies = array(); + $this->originalChildBodies = array(); } - $this->_lastMessage = null; + $this->lastMessage = null; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php index 7552b67a2f7..b975d36b858 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php @@ -18,9 +18,9 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener /** * The sender to impersonate. * - * @var String + * @var string */ - private $_sender; + private $sender; /** * Create a new ImpersonatePlugin to impersonate $sender. @@ -29,7 +29,7 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener */ public function __construct($sender) { - $this->_sender = $sender; + $this->sender = $sender; } /** @@ -46,7 +46,7 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener $headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath()); // replace them with the one to send to - $message->setReturnPath($this->_sender); + $message->setReturnPath($this->sender); } /** diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php index 64db4384648..7ddf1fd16db 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php @@ -11,12 +11,12 @@ /** * Does real time logging of Transport level information. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_Events_ResponseListener, Swift_Events_TransportChangeListener, Swift_Events_TransportExceptionListener, Swift_Plugins_Logger { /** The logger which is delegated to */ - private $_logger; + private $logger; /** * Create a new LoggerPlugin using $logger. @@ -25,7 +25,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function __construct(Swift_Plugins_Logger $logger) { - $this->_logger = $logger; + $this->logger = $logger; } /** @@ -35,7 +35,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function add($entry) { - $this->_logger->add($entry); + $this->logger->add($entry); } /** @@ -43,7 +43,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function clear() { - $this->_logger->clear(); + $this->logger->clear(); } /** @@ -53,7 +53,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ */ public function dump() { - return $this->_logger->dump(); + return $this->logger->dump(); } /** @@ -64,7 +64,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function commandSent(Swift_Events_CommandEvent $evt) { $command = $evt->getCommand(); - $this->_logger->add(sprintf('>> %s', $command)); + $this->logger->add(sprintf('>> %s', $command)); } /** @@ -75,7 +75,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function responseReceived(Swift_Events_ResponseEvent $evt) { $response = $evt->getResponse(); - $this->_logger->add(sprintf('<< %s', $response)); + $this->logger->add(sprintf('<< %s', $response)); } /** @@ -86,7 +86,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ Starting %s', $transportName)); + $this->logger->add(sprintf('++ Starting %s', $transportName)); } /** @@ -97,7 +97,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function transportStarted(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ %s started', $transportName)); + $this->logger->add(sprintf('++ %s started', $transportName)); } /** @@ -108,7 +108,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ Stopping %s', $transportName)); + $this->logger->add(sprintf('++ Stopping %s', $transportName)); } /** @@ -119,7 +119,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ public function transportStopped(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); - $this->_logger->add(sprintf('++ %s stopped', $transportName)); + $this->logger->add(sprintf('++ %s stopped', $transportName)); } /** @@ -132,10 +132,10 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_ $e = $evt->getException(); $message = $e->getMessage(); $code = $e->getCode(); - $this->_logger->add(sprintf('!! %s (code: %s)', $message, $code)); + $this->logger->add(sprintf('!! %s (code: %s)', $message, $code)); $message .= PHP_EOL; $message .= 'Log data:'.PHP_EOL; - $message .= $this->_logger->dump(); + $message .= $this->logger->dump(); $evt->cancelBubble(); throw new Swift_TransportException($message, $code, $e->getPrevious()); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php index 865bb0aa3b9..186b6b41bcd 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php @@ -20,14 +20,14 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger * * @var array */ - private $_log = array(); + private $log = array(); /** * Max size of the log. * * @var int */ - private $_size = 0; + private $size = 0; /** * Create a new ArrayLogger with a maximum of $size entries. @@ -36,7 +36,7 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function __construct($size = 50) { - $this->_size = $size; + $this->size = $size; } /** @@ -46,9 +46,9 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function add($entry) { - $this->_log[] = $entry; - while (count($this->_log) > $this->_size) { - array_shift($this->_log); + $this->log[] = $entry; + while (count($this->log) > $this->size) { + array_shift($this->log); } } @@ -57,7 +57,7 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function clear() { - $this->_log = array(); + $this->log = array(); } /** @@ -67,6 +67,6 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger */ public function dump() { - return implode(PHP_EOL, $this->_log); + return implode(PHP_EOL, $this->log); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php index 3583297ab10..40a53d2bba2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php @@ -16,7 +16,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger { /** Whether or not HTML should be output */ - private $_isHtml; + private $isHtml; /** * Create a new EchoLogger. @@ -25,7 +25,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger */ public function __construct($isHtml = true) { - $this->_isHtml = $isHtml; + $this->isHtml = $isHtml; } /** @@ -35,7 +35,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger */ public function add($entry) { - if ($this->_isHtml) { + if ($this->isHtml) { printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), '
', PHP_EOL); } else { printf('%s%s', $entry, PHP_EOL); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php index e622cb37d16..5ff1d9321c0 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php @@ -16,7 +16,7 @@ class Swift_Plugins_MessageLogger implements Swift_Events_SendListener { /** - * @var array + * @var Swift_Mime_Message[] */ private $messages; @@ -28,7 +28,7 @@ class Swift_Plugins_MessageLogger implements Swift_Events_SendListener /** * Get the message list. * - * @return array + * @return Swift_Mime_Message[] */ public function getMessages() { diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php index 18abb770632..c19403aec61 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php @@ -11,36 +11,36 @@ /** * Makes sure a connection to a POP3 host has been established prior to connecting to SMTP. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeListener, Swift_Plugins_Pop_Pop3Connection { /** A delegate connection to use (mostly a test hook) */ - private $_connection; + private $connection; /** Hostname of the POP3 server */ - private $_host; + private $host; /** Port number to connect on */ - private $_port; + private $port; /** Encryption type to use (if any) */ - private $_crypto; + private $crypto; /** Username to use (if any) */ - private $_username; + private $username; /** Password to use (if any) */ - private $_password; + private $password; /** Established connection via TCP socket */ - private $_socket; + private $socket; /** Connect timeout in seconds */ - private $_timeout = 10; + private $timeout = 10; /** SMTP Transport to bind to */ - private $_transport; + private $transport; /** * Create a new PopBeforeSmtpPlugin for $host and $port. @@ -51,23 +51,9 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function __construct($host, $port = 110, $crypto = null) { - $this->_host = $host; - $this->_port = $port; - $this->_crypto = $crypto; - } - - /** - * Create a new PopBeforeSmtpPlugin for $host and $port. - * - * @param string $host - * @param int $port - * @param string $crypto as "tls" or "ssl" - * - * @return Swift_Plugins_PopBeforeSmtpPlugin - */ - public static function newInstance($host, $port = 110, $crypto = null) - { - return new self($host, $port, $crypto); + $this->host = $host; + $this->port = $port; + $this->crypto = $crypto; } /** @@ -75,11 +61,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param Swift_Plugins_Pop_Pop3Connection $connection * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setConnection(Swift_Plugins_Pop_Pop3Connection $connection) { - $this->_connection = $connection; + $this->connection = $connection; return $this; } @@ -91,7 +77,7 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function bindSmtp(Swift_Transport $smtp) { - $this->_transport = $smtp; + $this->transport = $smtp; } /** @@ -99,11 +85,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param int $timeout * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setTimeout($timeout) { - $this->_timeout = (int) $timeout; + $this->timeout = (int) $timeout; return $this; } @@ -113,11 +99,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param string $username * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setUsername($username) { - $this->_username = $username; + $this->username = $username; return $this; } @@ -127,11 +113,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL * * @param string $password * - * @return Swift_Plugins_PopBeforeSmtpPlugin + * @return $this */ public function setPassword($password) { - $this->_password = $password; + $this->password = $password; return $this; } @@ -143,29 +129,29 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function connect() { - if (isset($this->_connection)) { - $this->_connection->connect(); + if (isset($this->connection)) { + $this->connection->connect(); } else { - if (!isset($this->_socket)) { + if (!isset($this->socket)) { if (!$socket = fsockopen( - $this->_getHostString(), $this->_port, $errno, $errstr, $this->_timeout)) { + $this->getHostString(), $this->port, $errno, $errstr, $this->timeout)) { throw new Swift_Plugins_Pop_Pop3Exception( - sprintf('Failed to connect to POP3 host [%s]: %s', $this->_host, $errstr) + sprintf('Failed to connect to POP3 host [%s]: %s', $this->host, $errstr) ); } - $this->_socket = $socket; + $this->socket = $socket; - if (false === $greeting = fgets($this->_socket)) { + if (false === $greeting = fgets($this->socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to connect to POP3 host [%s]', trim($greeting)) ); } - $this->_assertOk($greeting); + $this->assertOk($greeting); - if ($this->_username) { - $this->_command(sprintf("USER %s\r\n", $this->_username)); - $this->_command(sprintf("PASS %s\r\n", $this->_password)); + if ($this->username) { + $this->command(sprintf("USER %s\r\n", $this->username)); + $this->command(sprintf("PASS %s\r\n", $this->password)); } } } @@ -176,16 +162,16 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function disconnect() { - if (isset($this->_connection)) { - $this->_connection->disconnect(); + if (isset($this->connection)) { + $this->connection->disconnect(); } else { - $this->_command("QUIT\r\n"); - if (!fclose($this->_socket)) { + $this->command("QUIT\r\n"); + if (!fclose($this->socket)) { throw new Swift_Plugins_Pop_Pop3Exception( - sprintf('POP3 host [%s] connection could not be stopped', $this->_host) + sprintf('POP3 host [%s] connection could not be stopped', $this->host) ); } - $this->_socket = null; + $this->socket = null; } } @@ -196,8 +182,8 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL */ public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) { - if (isset($this->_transport)) { - if ($this->_transport !== $evt->getTransport()) { + if (isset($this->transport)) { + if ($this->transport !== $evt->getTransport()) { return; } } @@ -227,26 +213,26 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL { } - private function _command($command) + private function command($command) { - if (!fwrite($this->_socket, $command)) { + if (!fwrite($this->socket, $command)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to write command [%s] to POP3 host', trim($command)) ); } - if (false === $response = fgets($this->_socket)) { + if (false === $response = fgets($this->socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to read from POP3 host after command [%s]', trim($command)) ); } - $this->_assertOk($response); + $this->assertOk($response); return $response; } - private function _assertOk($response) + private function assertOk($response) { if (substr($response, 0, 3) != '+OK') { throw new Swift_Plugins_Pop_Pop3Exception( @@ -255,10 +241,10 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL } } - private function _getHostString() + private function getHostString() { - $host = $this->_host; - switch (strtolower($this->_crypto)) { + $host = $this->host; + switch (strtolower($this->crypto)) { case 'ssl': $host = 'ssl://'.$host; break; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php index c3a1f868544..8d797dd117b 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php @@ -11,7 +11,7 @@ /** * Redirects all email to a single recipient. * - * @author Fabien Potencier + * @author Fabien Potencier */ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener { @@ -20,14 +20,14 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener * * @var mixed */ - private $_recipient; + private $recipient; /** * List of regular expression for recipient whitelisting. * * @var array */ - private $_whitelist = array(); + private $whitelist = array(); /** * Create a new RedirectingPlugin. @@ -37,8 +37,8 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function __construct($recipient, array $whitelist = array()) { - $this->_recipient = $recipient; - $this->_whitelist = $whitelist; + $this->recipient = $recipient; + $this->whitelist = $whitelist; } /** @@ -48,7 +48,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function setRecipient($recipient) { - $this->_recipient = $recipient; + $this->recipient = $recipient; } /** @@ -58,7 +58,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function getRecipient() { - return $this->_recipient; + return $this->recipient; } /** @@ -68,7 +68,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function setWhitelist(array $whitelist) { - $this->_whitelist = $whitelist; + $this->whitelist = $whitelist; } /** @@ -78,7 +78,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function getWhitelist() { - return $this->_whitelist; + return $this->whitelist; } /** @@ -106,9 +106,9 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener } // Filter remaining headers against whitelist - $this->_filterHeaderSet($headers, 'To'); - $this->_filterHeaderSet($headers, 'Cc'); - $this->_filterHeaderSet($headers, 'Bcc'); + $this->filterHeaderSet($headers, 'To'); + $this->filterHeaderSet($headers, 'Cc'); + $this->filterHeaderSet($headers, 'Bcc'); // Add each hard coded recipient $to = $message->getTo(); @@ -116,7 +116,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener $to = array(); } - foreach ((array) $this->_recipient as $recipient) { + foreach ((array) $this->recipient as $recipient) { if (!array_key_exists($recipient, $to)) { $message->addTo($recipient); } @@ -126,13 +126,13 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener /** * Filter header set against a whitelist of regular expressions. * - * @param Swift_Mime_HeaderSet $headerSet - * @param string $type + * @param Swift_Mime_SimpleHeaderSet $headerSet + * @param string $type */ - private function _filterHeaderSet(Swift_Mime_HeaderSet $headerSet, $type) + private function filterHeaderSet(Swift_Mime_SimpleHeaderSet $headerSet, $type) { foreach ($headerSet->getAll($type) as $headers) { - $headers->setNameAddresses($this->_filterNameAddresses($headers->getNameAddresses())); + $headers->setNameAddresses($this->filterNameAddresses($headers->getNameAddresses())); } } @@ -143,12 +143,12 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener * * @return array */ - private function _filterNameAddresses(array $recipients) + private function filterNameAddresses(array $recipients) { $filtered = array(); foreach ($recipients as $address => $name) { - if ($this->_isWhitelisted($address)) { + if ($this->isWhitelisted($address)) { $filtered[$address] = $name; } } @@ -163,13 +163,13 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener * * @return bool */ - protected function _isWhitelisted($recipient) + protected function isWhitelisted($recipient) { - if (in_array($recipient, (array) $this->_recipient)) { + if (in_array($recipient, (array) $this->recipient)) { return true; } - foreach ($this->_whitelist as $pattern) { + foreach ($this->whitelist as $pattern) { if (preg_match($pattern, $recipient)) { return true; } @@ -185,10 +185,10 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener */ public function sendPerformed(Swift_Events_SendEvent $evt) { - $this->_restoreMessage($evt->getMessage()); + $this->restoreMessage($evt->getMessage()); } - private function _restoreMessage(Swift_Mime_Message $message) + private function restoreMessage(Swift_Mime_SimpleMessage $message) { // restore original headers $headers = $message->getHeaders(); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php index 0f21b7d6052..3a2b6657c09 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporter.php @@ -24,9 +24,9 @@ interface Swift_Plugins_Reporter /** * Notifies this ReportNotifier that $address failed or succeeded. * - * @param Swift_Mime_Message $message - * @param string $address - * @param int $result from {@link RESULT_PASS, RESULT_FAIL} + * @param Swift_Mime_SimpleMessage $message + * @param string $address + * @param int $result from {@link RESULT_PASS, RESULT_FAIL} */ - public function notify(Swift_Mime_Message $message, $address, $result); + public function notify(Swift_Mime_SimpleMessage $message, $address, $result); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php index a37901ff0d4..5ffca24c61c 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php @@ -20,7 +20,7 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener * * @var Swift_Plugins_Reporter */ - private $_reporter; + private $reporter; /** * Create a new ReporterPlugin using $reporter. @@ -29,7 +29,7 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener */ public function __construct(Swift_Plugins_Reporter $reporter) { - $this->_reporter = $reporter; + $this->reporter = $reporter; } /** @@ -49,13 +49,13 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener $message = $evt->getMessage(); $failures = array_flip($evt->getFailedRecipients()); foreach ((array) $message->getTo() as $address => $null) { - $this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS); + $this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); } foreach ((array) $message->getCc() as $address => $null) { - $this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS); + $this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); } foreach ((array) $message->getBcc() as $address => $null) { - $this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS); + $this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS)); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php index cad9d168ef2..67c117ac7c2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php @@ -20,22 +20,22 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter * * @var array */ - private $_failures = array(); + private $failures = array(); - private $_failures_cache = array(); + private $failures_cache = array(); /** * Notifies this ReportNotifier that $address failed or succeeded. * - * @param Swift_Mime_Message $message - * @param string $address - * @param int $result from {@link RESULT_PASS, RESULT_FAIL} + * @param Swift_Mime_SimpleMessage $message + * @param string $address + * @param int $result from {@link RESULT_PASS, RESULT_FAIL} */ - public function notify(Swift_Mime_Message $message, $address, $result) + public function notify(Swift_Mime_SimpleMessage $message, $address, $result) { - if (self::RESULT_FAIL == $result && !isset($this->_failures_cache[$address])) { - $this->_failures[] = $address; - $this->_failures_cache[$address] = true; + if (self::RESULT_FAIL == $result && !isset($this->failures_cache[$address])) { + $this->failures[] = $address; + $this->failures_cache[$address] = true; } } @@ -46,7 +46,7 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter */ public function getFailedRecipients() { - return $this->_failures; + return $this->failures; } /** @@ -54,6 +54,6 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter */ public function clear() { - $this->_failures = $this->_failures_cache = array(); + $this->failures = $this->failures_cache = array(); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php index c62593557e3..525eef570a9 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php @@ -18,11 +18,11 @@ class Swift_Plugins_Reporters_HtmlReporter implements Swift_Plugins_Reporter /** * Notifies this ReportNotifier that $address failed or succeeded. * - * @param Swift_Mime_Message $message - * @param string $address - * @param int $result from {@see RESULT_PASS, RESULT_FAIL} + * @param Swift_Mime_SimpleMessage $message + * @param string $address + * @param int $result from {@see RESULT_PASS, RESULT_FAIL} */ - public function notify(Swift_Mime_Message $message, $address, $result) + public function notify(Swift_Mime_SimpleMessage $message, $address, $result) { if (self::RESULT_PASS == $result) { echo '
'.PHP_EOL; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php index 24bc929ee6b..77c2e8db6ec 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php @@ -29,28 +29,28 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @var Swift_Plugins_Sleeper */ - private $_sleeper; + private $sleeper; /** * The Timer instance which provides the timestamp. * * @var Swift_Plugins_Timer */ - private $_timer; + private $timer; /** * The time at which the first email was sent. * * @var int */ - private $_start; + private $start; /** * The rate at which messages should be sent. * * @var int */ - private $_rate; + private $rate; /** * The mode for throttling. @@ -59,14 +59,14 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @var int */ - private $_mode; + private $mode; /** * An internal counter of the number of messages sent. * * @var int */ - private $_messages = 0; + private $messages = 0; /** * Create a new ThrottlerPlugin. @@ -78,10 +78,10 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin */ public function __construct($rate, $mode = self::BYTES_PER_MINUTE, Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null) { - $this->_rate = $rate; - $this->_mode = $mode; - $this->_sleeper = $sleeper; - $this->_timer = $timer; + $this->rate = $rate; + $this->mode = $mode; + $this->sleeper = $sleeper; + $this->timer = $timer; } /** @@ -92,22 +92,22 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $time = $this->getTimestamp(); - if (!isset($this->_start)) { - $this->_start = $time; + if (!isset($this->start)) { + $this->start = $time; } - $duration = $time - $this->_start; + $duration = $time - $this->start; - switch ($this->_mode) { - case self::BYTES_PER_MINUTE : - $sleep = $this->_throttleBytesPerMinute($duration); + switch ($this->mode) { + case self::BYTES_PER_MINUTE: + $sleep = $this->throttleBytesPerMinute($duration); break; - case self::MESSAGES_PER_SECOND : - $sleep = $this->_throttleMessagesPerSecond($duration); + case self::MESSAGES_PER_SECOND: + $sleep = $this->throttleMessagesPerSecond($duration); break; - case self::MESSAGES_PER_MINUTE : - $sleep = $this->_throttleMessagesPerMinute($duration); + case self::MESSAGES_PER_MINUTE: + $sleep = $this->throttleMessagesPerMinute($duration); break; - default : + default: $sleep = 0; break; } @@ -125,7 +125,7 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin public function sendPerformed(Swift_Events_SendEvent $evt) { parent::sendPerformed($evt); - ++$this->_messages; + ++$this->messages; } /** @@ -135,8 +135,8 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin */ public function sleep($seconds) { - if (isset($this->_sleeper)) { - $this->_sleeper->sleep($seconds); + if (isset($this->sleeper)) { + $this->sleeper->sleep($seconds); } else { sleep($seconds); } @@ -149,8 +149,8 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin */ public function getTimestamp() { - if (isset($this->_timer)) { - return $this->_timer->getTimestamp(); + if (isset($this->timer)) { + return $this->timer->getTimestamp(); } return time(); @@ -163,9 +163,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @return int */ - private function _throttleBytesPerMinute($timePassed) + private function throttleBytesPerMinute($timePassed) { - $expectedDuration = $this->getBytesOut() / ($this->_rate / 60); + $expectedDuration = $this->getBytesOut() / ($this->rate / 60); return (int) ceil($expectedDuration - $timePassed); } @@ -177,9 +177,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @return int */ - private function _throttleMessagesPerSecond($timePassed) + private function throttleMessagesPerSecond($timePassed) { - $expectedDuration = $this->_messages / ($this->_rate); + $expectedDuration = $this->messages / $this->rate; return (int) ceil($expectedDuration - $timePassed); } @@ -191,9 +191,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin * * @return int */ - private function _throttleMessagesPerMinute($timePassed) + private function throttleMessagesPerMinute($timePassed) { - $expectedDuration = $this->_messages / ($this->_rate / 60); + $expectedDuration = $this->messages / ($this->rate / 60); return (int) ceil($expectedDuration - $timePassed); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php index 503db84d883..79eafde9ad9 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Preferences.php @@ -16,7 +16,7 @@ class Swift_Preferences { /** Singleton instance */ - private static $_instance = null; + private static $instance = null; /** Constructor not to be used */ private function __construct() @@ -26,15 +26,15 @@ class Swift_Preferences /** * Gets the instance of Preferences. * - * @return Swift_Preferences + * @return self */ public static function getInstance() { - if (!isset(self::$_instance)) { - self::$_instance = new self(); + if (!isset(self::$instance)) { + self::$instance = new self(); } - return self::$_instance; + return self::$instance; } /** @@ -42,12 +42,11 @@ class Swift_Preferences * * @param string $charset * - * @return Swift_Preferences + * @return $this */ public function setCharset($charset) { - Swift_DependencyContainer::getInstance() - ->register('properties.charset')->asValue($charset); + Swift_DependencyContainer::getInstance()->register('properties.charset')->asValue($charset); return $this; } @@ -57,12 +56,11 @@ class Swift_Preferences * * @param string $dir * - * @return Swift_Preferences + * @return $this */ public function setTempDir($dir) { - Swift_DependencyContainer::getInstance() - ->register('tempdir')->asValue($dir); + Swift_DependencyContainer::getInstance()->register('tempdir')->asValue($dir); return $this; } @@ -72,12 +70,11 @@ class Swift_Preferences * * @param string $type * - * @return Swift_Preferences + * @return $this */ public function setCacheType($type) { - Swift_DependencyContainer::getInstance() - ->register('cache')->asAliasOf(sprintf('cache.%s', $type)); + Swift_DependencyContainer::getInstance()->register('cache')->asAliasOf(sprintf('cache.%s', $type)); return $this; } @@ -87,7 +84,7 @@ class Swift_Preferences * * @param bool $dotEscape * - * @return Swift_Preferences + * @return $this */ public function setQPDotEscape($dotEscape) { diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php index 974b24f2701..c129281b347 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/SendmailTransport.php @@ -30,16 +30,4 @@ class Swift_SendmailTransport extends Swift_Transport_SendmailTransport $this->setCommand($command); } - - /** - * Create a new SendmailTransport instance. - * - * @param string $command - * - * @return Swift_SendmailTransport - */ - public static function newInstance($command = '/usr/sbin/sendmail -bs') - { - return new self($command); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php deleted file mode 100644 index 2e7a8726d21..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SignedMessage.php +++ /dev/null @@ -1,23 +0,0 @@ - - * - * @deprecated - */ -class Swift_SignedMessage extends Swift_Message -{ -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php index 9ffcef39c9f..8e66e18f4e0 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/BodySigner.php @@ -20,7 +20,7 @@ interface Swift_Signers_BodySigner extends Swift_Signer * * @param Swift_Message $message * - * @return Swift_Signers_BodySigner + * @return self */ public function signMessage(Swift_Message $message); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php index 6040b2856f2..a88daa19815 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php @@ -11,7 +11,7 @@ /** * DKIM Signer used to apply DKIM Signature to a message. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner { @@ -20,99 +20,103 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @var string */ - protected $_privateKey; + protected $privateKey; /** * DomainName. * * @var string */ - protected $_domainName; + protected $domainName; /** * Selector. * * @var string */ - protected $_selector; + protected $selector; + + private $passphrase = ''; /** * Hash algorithm used. * + * @see RFC6376 3.3: Signers MUST implement and SHOULD sign using rsa-sha256. + * * @var string */ - protected $_hashAlgorithm = 'rsa-sha1'; + protected $hashAlgorithm = 'rsa-sha256'; /** * Body canon method. * * @var string */ - protected $_bodyCanon = 'simple'; + protected $bodyCanon = 'simple'; /** * Header canon method. * * @var string */ - protected $_headerCanon = 'simple'; + protected $headerCanon = 'simple'; /** * Headers not being signed. * * @var array */ - protected $_ignoredHeaders = array('return-path' => true); + protected $ignoredHeaders = array('return-path' => true); /** * Signer identity. * * @var string */ - protected $_signerIdentity; + protected $signerIdentity; /** * BodyLength. * * @var int */ - protected $_bodyLen = 0; + protected $bodyLen = 0; /** * Maximum signedLen. * * @var int */ - protected $_maxLen = PHP_INT_MAX; + protected $maxLen = PHP_INT_MAX; /** * Embbed bodyLen in signature. * * @var bool */ - protected $_showLen = false; + protected $showLen = false; /** * When the signature has been applied (true means time()), false means not embedded. * * @var mixed */ - protected $_signatureTimestamp = true; + protected $signatureTimestamp = true; /** * When will the signature expires false means not embedded, if sigTimestamp is auto - * Expiration is relative, otherwhise it's absolute. + * Expiration is relative, otherwise it's absolute. * * @var int */ - protected $_signatureExpiration = false; + protected $signatureExpiration = false; /** * Must we embed signed headers? * * @var bool */ - protected $_debugHeaders = false; + protected $debugHeaders = false; // work variables /** @@ -120,46 +124,46 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @var array */ - protected $_signedHeaders = array(); + protected $signedHeaders = array(); /** - * If debugHeaders is set store debugDatas here. + * If debugHeaders is set store debugData here. * * @var string */ - private $_debugHeadersData = ''; + private $debugHeadersData = ''; /** * Stores the bodyHash. * * @var string */ - private $_bodyHash = ''; + private $bodyHash = ''; /** * Stores the signature header. * * @var Swift_Mime_Headers_ParameterizedHeader */ - protected $_dkimHeader; + protected $dkimHeader; - private $_bodyHashHandler; + private $bodyHashHandler; - private $_headerHash; + private $headerHash; - private $_headerCanonData = ''; + private $headerCanonData = ''; - private $_bodyCanonEmptyCounter = 0; + private $bodyCanonEmptyCounter = 0; - private $_bodyCanonIgnoreStart = 2; + private $bodyCanonIgnoreStart = 2; - private $_bodyCanonSpace = false; + private $bodyCanonSpace = false; - private $_bodyCanonLastChar = null; + private $bodyCanonLastChar = null; - private $_bodyCanonLine = ''; + private $bodyCanonLine = ''; - private $_bound = array(); + private $bound = array(); /** * Constructor. @@ -167,27 +171,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * @param string $privateKey * @param string $domainName * @param string $selector + * @param string $passphrase */ - public function __construct($privateKey, $domainName, $selector) + public function __construct($privateKey, $domainName, $selector, $passphrase = '') { - $this->_privateKey = $privateKey; - $this->_domainName = $domainName; - $this->_signerIdentity = '@'.$domainName; - $this->_selector = $selector; - } - - /** - * Instanciate DKIMSigner. - * - * @param string $privateKey - * @param string $domainName - * @param string $selector - * - * @return Swift_Signers_DKIMSigner - */ - public static function newInstance($privateKey, $domainName, $selector) - { - return new static($privateKey, $domainName, $selector); + $this->privateKey = $privateKey; + $this->domainName = $domainName; + $this->signerIdentity = '@'.$domainName; + $this->selector = $selector; + $this->passphrase = $passphrase; } /** @@ -197,14 +189,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function reset() { - $this->_headerHash = null; - $this->_signedHeaders = array(); - $this->_bodyHash = null; - $this->_bodyHashHandler = null; - $this->_bodyCanonIgnoreStart = 2; - $this->_bodyCanonEmptyCounter = 0; - $this->_bodyCanonLastChar = null; - $this->_bodyCanonSpace = false; + $this->headerHash = null; + $this->signedHeaders = array(); + $this->bodyHash = null; + $this->bodyHashHandler = null; + $this->bodyCanonIgnoreStart = 2; + $this->bodyCanonEmptyCounter = 0; + $this->bodyCanonLastChar = null; + $this->bodyCanonSpace = false; } /** @@ -219,14 +211,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $bytes * - * @throws Swift_IoException - * * @return int + * + * @throws Swift_IoException */ + // TODO fix return public function write($bytes) { - $this->_canonicalizeBody($bytes); - foreach ($this->_bound as $is) { + $this->canonicalizeBody($bytes); + foreach ($this->bound as $is) { $is->write($bytes); } } @@ -234,8 +227,6 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner /** * For any bytes that are currently buffered inside the stream, force them * off the buffer. - * - * @throws Swift_IoException */ public function commit() { @@ -253,7 +244,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner public function bind(Swift_InputByteStream $is) { // Don't have to mirror anything - $this->_bound[] = $is; + $this->bound[] = $is; return; } @@ -269,15 +260,13 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner public function unbind(Swift_InputByteStream $is) { // Don't have to mirror anything - foreach ($this->_bound as $k => $stream) { + foreach ($this->bound as $k => $stream) { if ($stream === $is) { - unset($this->_bound[$k]); + unset($this->bound[$k]); return; } } - - return; } /** @@ -292,19 +281,28 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner } /** - * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256. + * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1. * - * @param string $hash + * @param string $hash 'rsa-sha1' or 'rsa-sha256' * - * @return Swift_Signers_DKIMSigner + * @throws Swift_SwiftException + * + * @return $this */ public function setHashAlgorithm($hash) { - // Unable to sign with rsa-sha256 - if ($hash == 'rsa-sha1') { - $this->_hashAlgorithm = 'rsa-sha1'; - } else { - $this->_hashAlgorithm = 'rsa-sha256'; + switch ($hash) { + case 'rsa-sha1': + $this->hashAlgorithm = 'rsa-sha1'; + break; + case 'rsa-sha256': + $this->hashAlgorithm = 'rsa-sha256'; + if (!defined('OPENSSL_ALGO_SHA256')) { + throw new Swift_SwiftException('Unable to set sha256 as it is not supported by OpenSSL.'); + } + break; + default: + throw new Swift_SwiftException('Unable to set the hash algorithm, must be one of rsa-sha1 or rsa-sha256 (%s given).', $hash); } return $this; @@ -315,14 +313,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $canon * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setBodyCanon($canon) { if ($canon == 'relaxed') { - $this->_bodyCanon = 'relaxed'; + $this->bodyCanon = 'relaxed'; } else { - $this->_bodyCanon = 'simple'; + $this->bodyCanon = 'simple'; } return $this; @@ -333,14 +331,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $canon * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setHeaderCanon($canon) { if ($canon == 'relaxed') { - $this->_headerCanon = 'relaxed'; + $this->headerCanon = 'relaxed'; } else { - $this->_headerCanon = 'simple'; + $this->headerCanon = 'simple'; } return $this; @@ -351,11 +349,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param string $identity * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignerIdentity($identity) { - $this->_signerIdentity = $identity; + $this->signerIdentity = $identity; return $this; } @@ -365,19 +363,19 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param mixed $len (bool or int) * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setBodySignedLen($len) { if ($len === true) { - $this->_showLen = true; - $this->_maxLen = PHP_INT_MAX; + $this->showLen = true; + $this->maxLen = PHP_INT_MAX; } elseif ($len === false) { $this->showLen = false; - $this->_maxLen = PHP_INT_MAX; + $this->maxLen = PHP_INT_MAX; } else { - $this->_showLen = true; - $this->_maxLen = (int) $len; + $this->showLen = true; + $this->maxLen = (int) $len; } return $this; @@ -388,11 +386,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param int $time A timestamp * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureTimestamp($time) { - $this->_signatureTimestamp = $time; + $this->signatureTimestamp = $time; return $this; } @@ -402,11 +400,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @param int $time A timestamp * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureExpiration($time) { - $this->_signatureExpiration = $time; + $this->signatureExpiration = $time; return $this; } @@ -420,7 +418,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function setDebugHeaders($debug) { - $this->_debugHeaders = (bool) $debug; + $this->debugHeaders = (bool) $debug; return $this; } @@ -431,15 +429,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner public function startBody() { // Init - switch ($this->_hashAlgorithm) { - case 'rsa-sha256' : - $this->_bodyHashHandler = hash_init('sha256'); + switch ($this->hashAlgorithm) { + case 'rsa-sha256': + $this->bodyHashHandler = hash_init('sha256'); break; - case 'rsa-sha1' : - $this->_bodyHashHandler = hash_init('sha1'); + case 'rsa-sha1': + $this->bodyHashHandler = hash_init('sha1'); break; } - $this->_bodyCanonLine = ''; + $this->bodyCanonLine = ''; } /** @@ -447,7 +445,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function endBody() { - $this->_endOfBody(); + $this->endOfBody(); } /** @@ -457,7 +455,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function getAlteredHeaders() { - if ($this->_debugHeaders) { + if ($this->debugHeaders) { return array('DKIM-Signature', 'X-DebugHash'); } else { return array('DKIM-Signature'); @@ -473,7 +471,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner */ public function ignoreHeader($header_name) { - $this->_ignoredHeaders[strtolower($header_name)] = true; + $this->ignoredHeaders[strtolower($header_name)] = true; return $this; } @@ -481,24 +479,24 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner /** * Set the headers to sign. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * * @return Swift_Signers_DKIMSigner */ - public function setHeaders(Swift_Mime_HeaderSet $headers) + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) { - $this->_headerCanonData = ''; + $this->headerCanonData = ''; // Loop through Headers $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header - if (!isset($this->_ignoredHeaders[strtolower($hName)])) { + if (!isset($this->ignoredHeaders[strtolower($hName)])) { if ($headers->has($hName)) { $tmp = $headers->getAll($hName); foreach ($tmp as $header) { if ($header->getFieldBody() != '') { - $this->_addHeader($header->toString()); - $this->_signedHeaders[] = $header->getFieldName(); + $this->addHeader($header->toString()); + $this->signedHeaders[] = $header->getFieldName(); } } } @@ -511,37 +509,37 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner /** * Add the signature to the given Headers. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * * @return Swift_Signers_DKIMSigner */ - public function addSignature(Swift_Mime_HeaderSet $headers) + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) { // Prepare the DKIM-Signature - $params = array('v' => '1', 'a' => $this->_hashAlgorithm, 'bh' => base64_encode($this->_bodyHash), 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'i' => $this->_signerIdentity, 's' => $this->_selector); - if ($this->_bodyCanon != 'simple') { - $params['c'] = $this->_headerCanon.'/'.$this->_bodyCanon; - } elseif ($this->_headerCanon != 'simple') { - $params['c'] = $this->_headerCanon; + $params = array('v' => '1', 'a' => $this->hashAlgorithm, 'bh' => base64_encode($this->bodyHash), 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'i' => $this->signerIdentity, 's' => $this->selector); + if ($this->bodyCanon != 'simple') { + $params['c'] = $this->headerCanon.'/'.$this->bodyCanon; + } elseif ($this->headerCanon != 'simple') { + $params['c'] = $this->headerCanon; } - if ($this->_showLen) { - $params['l'] = $this->_bodyLen; + if ($this->showLen) { + $params['l'] = $this->bodyLen; } - if ($this->_signatureTimestamp === true) { + if ($this->signatureTimestamp === true) { $params['t'] = time(); - if ($this->_signatureExpiration !== false) { - $params['x'] = $params['t'] + $this->_signatureExpiration; + if ($this->signatureExpiration !== false) { + $params['x'] = $params['t'] + $this->signatureExpiration; } } else { - if ($this->_signatureTimestamp !== false) { - $params['t'] = $this->_signatureTimestamp; + if ($this->signatureTimestamp !== false) { + $params['t'] = $this->signatureTimestamp; } - if ($this->_signatureExpiration !== false) { - $params['x'] = $this->_signatureExpiration; + if ($this->signatureExpiration !== false) { + $params['x'] = $this->signatureExpiration; } } - if ($this->_debugHeaders) { - $params['z'] = implode('|', $this->_debugHeadersData); + if ($this->debugHeaders) { + $params['z'] = implode('|', $this->debugHeadersData); } $string = ''; foreach ($params as $k => $v) { @@ -551,67 +549,57 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner $headers->addTextHeader('DKIM-Signature', $string); // Add the last DKIM-Signature $tmp = $headers->getAll('DKIM-Signature'); - $this->_dkimHeader = end($tmp); - $this->_addHeader(trim($this->_dkimHeader->toString())."\r\n b=", true); - $this->_endOfHeaders(); - if ($this->_debugHeaders) { - $headers->addTextHeader('X-DebugHash', base64_encode($this->_headerHash)); + $this->dkimHeader = end($tmp); + $this->addHeader(trim($this->dkimHeader->toString())."\r\n b=", true); + if ($this->debugHeaders) { + $headers->addTextHeader('X-DebugHash', base64_encode($this->headerHash)); } - $this->_dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->_getEncryptedHash()), 73, ' '))); + $this->dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->getEncryptedHash()), 73, ' '))); return $this; } /* Private helpers */ - protected function _addHeader($header, $is_sig = false) + protected function addHeader($header, $is_sig = false) { - switch ($this->_headerCanon) { - case 'relaxed' : + switch ($this->headerCanon) { + case 'relaxed': // Prepare Header and cascade $exploded = explode(':', $header, 2); $name = strtolower(trim($exploded[0])); $value = str_replace("\r\n", '', $exploded[1]); $value = preg_replace("/[ \t][ \t]+/", ' ', $value); $header = $name.':'.trim($value).($is_sig ? '' : "\r\n"); - case 'simple' : + case 'simple': // Nothing to do } - $this->_addToHeaderHash($header); + $this->addToHeaderHash($header); } - /** - * @deprecated This method is currently useless in this class but it must be - * kept for BC reasons due to its "protected" scope. This method - * might be overriden by custom client code. - */ - protected function _endOfHeaders() - { - } - - protected function _canonicalizeBody($string) + protected function canonicalizeBody($string) { $len = strlen($string); $canon = ''; - $method = ($this->_bodyCanon == 'relaxed'); + $method = ($this->bodyCanon == 'relaxed'); for ($i = 0; $i < $len; ++$i) { - if ($this->_bodyCanonIgnoreStart > 0) { - --$this->_bodyCanonIgnoreStart; + if ($this->bodyCanonIgnoreStart > 0) { + --$this->bodyCanonIgnoreStart; continue; } switch ($string[$i]) { - case "\r" : - $this->_bodyCanonLastChar = "\r"; + case "\r": + $this->bodyCanonLastChar = "\r"; break; - case "\n" : - if ($this->_bodyCanonLastChar == "\r") { + case "\n": + if ($this->bodyCanonLastChar == "\r") { if ($method) { - $this->_bodyCanonSpace = false; + $this->bodyCanonSpace = false; } - if ($this->_bodyCanonLine == '') { - ++$this->_bodyCanonEmptyCounter; + if ($this->bodyCanonLine == '') { + ++$this->bodyCanonEmptyCounter; } else { - $this->_bodyCanonLine = ''; + $this->bodyCanonLine = ''; $canon .= "\r\n"; } } else { @@ -619,55 +607,55 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner // todo handle it but should never happen } break; - case ' ' : - case "\t" : + case ' ': + case "\t": if ($method) { - $this->_bodyCanonSpace = true; + $this->bodyCanonSpace = true; break; } - default : - if ($this->_bodyCanonEmptyCounter > 0) { - $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); - $this->_bodyCanonEmptyCounter = 0; + default: + if ($this->bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter); + $this->bodyCanonEmptyCounter = 0; } - if ($this->_bodyCanonSpace) { - $this->_bodyCanonLine .= ' '; + if ($this->bodyCanonSpace) { + $this->bodyCanonLine .= ' '; $canon .= ' '; - $this->_bodyCanonSpace = false; + $this->bodyCanonSpace = false; } - $this->_bodyCanonLine .= $string[$i]; + $this->bodyCanonLine .= $string[$i]; $canon .= $string[$i]; } } - $this->_addToBodyHash($canon); + $this->addToBodyHash($canon); } - protected function _endOfBody() + protected function endOfBody() { // Add trailing Line return if last line is non empty - if (strlen($this->_bodyCanonLine) > 0) { - $this->_addToBodyHash("\r\n"); + if (strlen($this->bodyCanonLine) > 0) { + $this->addToBodyHash("\r\n"); } - $this->_bodyHash = hash_final($this->_bodyHashHandler, true); + $this->bodyHash = hash_final($this->bodyHashHandler, true); } - private function _addToBodyHash($string) + private function addToBodyHash($string) { $len = strlen($string); - if ($len > ($new_len = ($this->_maxLen - $this->_bodyLen))) { + if ($len > ($new_len = ($this->maxLen - $this->bodyLen))) { $string = substr($string, 0, $new_len); $len = $new_len; } - hash_update($this->_bodyHashHandler, $string); - $this->_bodyLen += $len; + hash_update($this->bodyHashHandler, $string); + $this->bodyLen += $len; } - private function _addToHeaderHash($header) + private function addToHeaderHash($header) { - if ($this->_debugHeaders) { - $this->_debugHeadersData[] = trim($header); + if ($this->debugHeaders) { + $this->debugHeadersData[] = trim($header); } - $this->_headerCanonData .= $header; + $this->headerCanonData .= $header; } /** @@ -675,10 +663,10 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner * * @return string */ - private function _getEncryptedHash() + private function getEncryptedHash() { $signature = ''; - switch ($this->_hashAlgorithm) { + switch ($this->hashAlgorithm) { case 'rsa-sha1': $algorithm = OPENSSL_ALGO_SHA1; break; @@ -686,11 +674,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner $algorithm = OPENSSL_ALGO_SHA256; break; } - $pkeyId = openssl_get_privatekey($this->_privateKey); + $pkeyId = openssl_get_privatekey($this->privateKey, $this->passphrase); if (!$pkeyId) { throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']'); } - if (openssl_sign($this->_headerCanonData, $signature, $pkeyId, $algorithm)) { + if (openssl_sign($this->headerCanonData, $signature, $pkeyId, $algorithm)) { return $signature; } throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php index 3f42d3f6e90..40654987f9b 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php @@ -11,7 +11,7 @@ /** * DomainKey Signer used to apply DomainKeys Signature to a message. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner { @@ -20,56 +20,56 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @var string */ - protected $_privateKey; + protected $privateKey; /** * DomainName. * * @var string */ - protected $_domainName; + protected $domainName; /** * Selector. * * @var string */ - protected $_selector; + protected $selector; /** * Hash algorithm used. * * @var string */ - protected $_hashAlgorithm = 'rsa-sha1'; + protected $hashAlgorithm = 'rsa-sha1'; /** * Canonisation method. * * @var string */ - protected $_canon = 'simple'; + protected $canon = 'simple'; /** * Headers not being signed. * * @var array */ - protected $_ignoredHeaders = array(); + protected $ignoredHeaders = array(); /** * Signer identity. * * @var string */ - protected $_signerIdentity; + protected $signerIdentity; /** * Must we embed signed headers? * * @var bool */ - protected $_debugHeaders = false; + protected $debugHeaders = false; // work variables /** @@ -77,37 +77,37 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @var array */ - private $_signedHeaders = array(); + private $signedHeaders = array(); /** * Stores the signature header. * * @var Swift_Mime_Headers_ParameterizedHeader */ - protected $_domainKeyHeader; + protected $domainKeyHeader; /** * Hash Handler. * * @var resource|null */ - private $_hashHandler; + private $hashHandler; - private $_hash; + private $hash; - private $_canonData = ''; + private $canonData = ''; - private $_bodyCanonEmptyCounter = 0; + private $bodyCanonEmptyCounter = 0; - private $_bodyCanonIgnoreStart = 2; + private $bodyCanonIgnoreStart = 2; - private $_bodyCanonSpace = false; + private $bodyCanonSpace = false; - private $_bodyCanonLastChar = null; + private $bodyCanonLastChar = null; - private $_bodyCanonLine = ''; + private $bodyCanonLine = ''; - private $_bound = array(); + private $bound = array(); /** * Constructor. @@ -118,39 +118,25 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner */ public function __construct($privateKey, $domainName, $selector) { - $this->_privateKey = $privateKey; - $this->_domainName = $domainName; - $this->_signerIdentity = '@'.$domainName; - $this->_selector = $selector; - } - - /** - * Instanciate DomainKeySigner. - * - * @param string $privateKey - * @param string $domainName - * @param string $selector - * - * @return Swift_Signers_DomainKeySigner - */ - public static function newInstance($privateKey, $domainName, $selector) - { - return new static($privateKey, $domainName, $selector); + $this->privateKey = $privateKey; + $this->domainName = $domainName; + $this->signerIdentity = '@'.$domainName; + $this->selector = $selector; } /** * Resets internal states. * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function reset() { - $this->_hash = null; - $this->_hashHandler = null; - $this->_bodyCanonIgnoreStart = 2; - $this->_bodyCanonEmptyCounter = 0; - $this->_bodyCanonLastChar = null; - $this->_bodyCanonSpace = false; + $this->hash = null; + $this->hashHandler = null; + $this->bodyCanonIgnoreStart = 2; + $this->bodyCanonEmptyCounter = 0; + $this->bodyCanonLastChar = null; + $this->bodyCanonSpace = false; return $this; } @@ -167,15 +153,16 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $bytes * + * @return int + * * @throws Swift_IoException * - * @return int - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function write($bytes) { - $this->_canonicalizeBody($bytes); - foreach ($this->_bound as $is) { + $this->canonicalizeBody($bytes); + foreach ($this->bound as $is) { $is->write($bytes); } @@ -188,7 +175,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @throws Swift_IoException * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function commit() { @@ -203,12 +190,12 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param Swift_InputByteStream $is * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function bind(Swift_InputByteStream $is) { // Don't have to mirror anything - $this->_bound[] = $is; + $this->bound[] = $is; return $this; } @@ -221,16 +208,16 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param Swift_InputByteStream $is * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function unbind(Swift_InputByteStream $is) { // Don't have to mirror anything - foreach ($this->_bound as $k => $stream) { + foreach ($this->bound as $k => $stream) { if ($stream === $is) { - unset($this->_bound[$k]); + unset($this->bound[$k]); - return; + break; } } @@ -243,7 +230,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @throws Swift_IoException * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function flushBuffers() { @@ -257,11 +244,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $hash * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setHashAlgorithm($hash) { - $this->_hashAlgorithm = 'rsa-sha1'; + $this->hashAlgorithm = 'rsa-sha1'; return $this; } @@ -271,14 +258,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $canon simple | nofws defaults to simple * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setCanon($canon) { if ($canon == 'nofws') { - $this->_canon = 'nofws'; + $this->canon = 'nofws'; } else { - $this->_canon = 'simple'; + $this->canon = 'simple'; } return $this; @@ -289,11 +276,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $identity * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setSignerIdentity($identity) { - $this->_signerIdentity = $identity; + $this->signerIdentity = $identity; return $this; } @@ -303,11 +290,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param bool $debug * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function setDebugHeaders($debug) { - $this->_debugHeaders = (bool) $debug; + $this->debugHeaders = (bool) $debug; return $this; } @@ -324,7 +311,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner */ public function endBody() { - $this->_endOfBody(); + $this->endOfBody(); } /** @@ -334,7 +321,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner */ public function getAlteredHeaders() { - if ($this->_debugHeaders) { + if ($this->debugHeaders) { return array('DomainKey-Signature', 'X-DebugHash'); } @@ -346,11 +333,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @param string $header_name * - * @return Swift_Signers_DomainKeySigner + * @return $this */ public function ignoreHeader($header_name) { - $this->_ignoredHeaders[strtolower($header_name)] = true; + $this->ignoredHeaders[strtolower($header_name)] = true; return $this; } @@ -358,31 +345,31 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner /** * Set the headers to sign. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_DomainKeySigner + * @return $this */ - public function setHeaders(Swift_Mime_HeaderSet $headers) + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) { - $this->_startHash(); - $this->_canonData = ''; + $this->startHash(); + $this->canonData = ''; // Loop through Headers $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header - if (!isset($this->_ignoredHeaders[strtolower($hName)])) { + if (!isset($this->ignoredHeaders[strtolower($hName)])) { if ($headers->has($hName)) { $tmp = $headers->getAll($hName); foreach ($tmp as $header) { if ($header->getFieldBody() != '') { - $this->_addHeader($header->toString()); - $this->_signedHeaders[] = $header->getFieldName(); + $this->addHeader($header->toString()); + $this->signedHeaders[] = $header->getFieldName(); } } } } } - $this->_endOfHeaders(); + $this->endOfHeaders(); return $this; } @@ -390,14 +377,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner /** * Add the signature to the given Headers. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_DomainKeySigner + * @return $this */ - public function addSignature(Swift_Mime_HeaderSet $headers) + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) { // Prepare the DomainKey-Signature Header - $params = array('a' => $this->_hashAlgorithm, 'b' => chunk_split(base64_encode($this->_getEncryptedHash()), 73, ' '), 'c' => $this->_canon, 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'q' => 'dns', 's' => $this->_selector); + $params = array('a' => $this->hashAlgorithm, 'b' => chunk_split(base64_encode($this->getEncryptedHash()), 73, ' '), 'c' => $this->canon, 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'q' => 'dns', 's' => $this->selector); $string = ''; foreach ($params as $k => $v) { $string .= $k.'='.$v.'; '; @@ -410,50 +397,50 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner /* Private helpers */ - protected function _addHeader($header) + protected function addHeader($header) { - switch ($this->_canon) { - case 'nofws' : + switch ($this->canon) { + case 'nofws': // Prepare Header and cascade $exploded = explode(':', $header, 2); $name = strtolower(trim($exploded[0])); $value = str_replace("\r\n", '', $exploded[1]); $value = preg_replace("/[ \t][ \t]+/", ' ', $value); $header = $name.':'.trim($value)."\r\n"; - case 'simple' : + case 'simple': // Nothing to do } - $this->_addToHash($header); + $this->addToHash($header); } - protected function _endOfHeaders() + protected function endOfHeaders() { - $this->_bodyCanonEmptyCounter = 1; + $this->bodyCanonEmptyCounter = 1; } - protected function _canonicalizeBody($string) + protected function canonicalizeBody($string) { $len = strlen($string); $canon = ''; - $nofws = ($this->_canon == 'nofws'); + $nofws = ($this->canon == 'nofws'); for ($i = 0; $i < $len; ++$i) { - if ($this->_bodyCanonIgnoreStart > 0) { - --$this->_bodyCanonIgnoreStart; + if ($this->bodyCanonIgnoreStart > 0) { + --$this->bodyCanonIgnoreStart; continue; } switch ($string[$i]) { - case "\r" : - $this->_bodyCanonLastChar = "\r"; + case "\r": + $this->bodyCanonLastChar = "\r"; break; - case "\n" : - if ($this->_bodyCanonLastChar == "\r") { + case "\n": + if ($this->bodyCanonLastChar == "\r") { if ($nofws) { - $this->_bodyCanonSpace = false; + $this->bodyCanonSpace = false; } - if ($this->_bodyCanonLine == '') { - ++$this->_bodyCanonEmptyCounter; + if ($this->bodyCanonLine == '') { + ++$this->bodyCanonEmptyCounter; } else { - $this->_bodyCanonLine = ''; + $this->bodyCanonLine = ''; $canon .= "\r\n"; } } else { @@ -461,48 +448,48 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner throw new Swift_SwiftException('Invalid new line sequence in mail found \n without preceding \r'); } break; - case ' ' : - case "\t" : + case ' ': + case "\t": case "\x09": //HTAB if ($nofws) { - $this->_bodyCanonSpace = true; + $this->bodyCanonSpace = true; break; } - default : - if ($this->_bodyCanonEmptyCounter > 0) { - $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); - $this->_bodyCanonEmptyCounter = 0; + default: + if ($this->bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter); + $this->bodyCanonEmptyCounter = 0; } - $this->_bodyCanonLine .= $string[$i]; + $this->bodyCanonLine .= $string[$i]; $canon .= $string[$i]; } } - $this->_addToHash($canon); + $this->addToHash($canon); } - protected function _endOfBody() + protected function endOfBody() { - if (strlen($this->_bodyCanonLine) > 0) { - $this->_addToHash("\r\n"); + if (strlen($this->bodyCanonLine) > 0) { + $this->addToHash("\r\n"); } - $this->_hash = hash_final($this->_hashHandler, true); + $this->hash = hash_final($this->hashHandler, true); } - private function _addToHash($string) + private function addToHash($string) { - $this->_canonData .= $string; - hash_update($this->_hashHandler, $string); + $this->canonData .= $string; + hash_update($this->hashHandler, $string); } - private function _startHash() + private function startHash() { // Init - switch ($this->_hashAlgorithm) { - case 'rsa-sha1' : - $this->_hashHandler = hash_init('sha1'); + switch ($this->hashAlgorithm) { + case 'rsa-sha1': + $this->hashHandler = hash_init('sha1'); break; } - $this->_canonLine = ''; + $this->bodyCanonLine = ''; } /** @@ -510,14 +497,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner * * @return string */ - private function _getEncryptedHash() + private function getEncryptedHash() { $signature = ''; - $pkeyId = openssl_get_privatekey($this->_privateKey); + $pkeyId = openssl_get_privatekey($this->privateKey); if (!$pkeyId) { throw new Swift_SwiftException('Unable to load DomainKey Private Key ['.openssl_error_string().']'); } - if (openssl_sign($this->_canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { + if (openssl_sign($this->canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { return $signature; } throw new Swift_SwiftException('Unable to sign DomainKey Hash ['.openssl_error_string().']'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php index c75cb08a518..6104e34f3f5 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php @@ -20,21 +20,21 @@ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream * * @param string $header_name * - * @return Swift_Signers_HeaderSigner + * @return self */ public function ignoreHeader($header_name); /** * Prepare the Signer to get a new Body. * - * @return Swift_Signers_HeaderSigner + * @return self */ public function startBody(); /** * Give the signal that the body has finished streaming. * - * @return Swift_Signers_HeaderSigner + * @return self */ public function endBody(); @@ -43,18 +43,18 @@ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream * * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_HeaderSigner + * @return self */ - public function setHeaders(Swift_Mime_HeaderSet $headers); + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers); /** * Add the header(s) to the headerSet. * - * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_SimpleHeaderSet $headers * - * @return Swift_Signers_HeaderSigner + * @return self */ - public function addSignature(Swift_Mime_HeaderSet $headers); + public function addSignature(Swift_Mime_SimpleHeaderSet $headers); /** * Return the list of header a signer might tamper. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php index 3a35ad55d07..deb29f575f2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php @@ -12,13 +12,13 @@ * DKIM Signer used to apply DKIM Signature to a message * Takes advantage of pecl extension. * - * @author Xavier De Cock + * @author Xavier De Cock */ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner { - private $_peclLoaded = false; + private $peclLoaded = false; - private $_dkimHandler = null; + private $dkimHandler = null; private $dropFirstLF = true; @@ -33,22 +33,17 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner throw new Swift_SwiftException('php-opendkim extension not found'); } - $this->_peclLoaded = true; + $this->peclLoaded = true; parent::__construct($privateKey, $domainName, $selector); } - public static function newInstance($privateKey, $domainName, $selector) - { - return new static($privateKey, $domainName, $selector); - } - - public function addSignature(Swift_Mime_HeaderSet $headers) + public function addSignature(Swift_Mime_SimpleHeaderSet $headers) { $header = new Swift_Mime_Headers_OpenDKIMHeader('DKIM-Signature'); - $headerVal = $this->_dkimHandler->getSignatureHeader(); + $headerVal = $this->dkimHandler->getSignatureHeader(); if (!$headerVal) { - throw new Swift_SwiftException('OpenDKIM Error: '.$this->_dkimHandler->getError()); + throw new Swift_SwiftException('OpenDKIM Error: '.$this->dkimHandler->getError()); } $header->setValue($headerVal); $headers->set($header); @@ -56,40 +51,40 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner return $this; } - public function setHeaders(Swift_Mime_HeaderSet $headers) + public function setHeaders(Swift_Mime_SimpleHeaderSet $headers) { - $bodyLen = $this->_bodyLen; + $bodyLen = $this->bodyLen; if (is_bool($bodyLen)) { $bodyLen = -1; } - $hash = $this->_hashAlgorithm == 'rsa-sha1' ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; - $bodyCanon = $this->_bodyCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; - $headerCanon = $this->_headerCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; - $this->_dkimHandler = new OpenDKIMSign($this->_privateKey, $this->_selector, $this->_domainName, $headerCanon, $bodyCanon, $hash, $bodyLen); + $hash = $this->hashAlgorithm == 'rsa-sha1' ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; + $bodyCanon = $this->bodyCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $headerCanon = $this->headerCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $this->dkimHandler = new OpenDKIMSign($this->privateKey, $this->selector, $this->domainName, $headerCanon, $bodyCanon, $hash, $bodyLen); // Hardcode signature Margin for now - $this->_dkimHandler->setMargin(78); + $this->dkimHandler->setMargin(78); - if (!is_numeric($this->_signatureTimestamp)) { + if (!is_numeric($this->signatureTimestamp)) { OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, time()); } else { - if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->_signatureTimestamp)) { + if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->signatureTimestamp)) { throw new Swift_SwiftException('Unable to force signature timestamp ['.openssl_error_string().']'); } } - if (isset($this->_signerIdentity)) { - $this->_dkimHandler->setSigner($this->_signerIdentity); + if (isset($this->signerIdentity)) { + $this->dkimHandler->setSigner($this->signerIdentity); } $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header - if (!isset($this->_ignoredHeaders[strtolower($hName)])) { + if (!isset($this->ignoredHeaders[strtolower($hName)])) { $tmp = $headers->getAll($hName); if ($headers->has($hName)) { foreach ($tmp as $header) { if ($header->getFieldBody() != '') { $htosign = $header->toString(); - $this->_dkimHandler->header($htosign); - $this->_signedHeaders[] = $header->getFieldName(); + $this->dkimHandler->header($htosign); + $this->signedHeaders[] = $header->getFieldName(); } } } @@ -101,28 +96,28 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner public function startBody() { - if (!$this->_peclLoaded) { + if (!$this->peclLoaded) { return parent::startBody(); } $this->dropFirstLF = true; - $this->_dkimHandler->eoh(); + $this->dkimHandler->eoh(); return $this; } public function endBody() { - if (!$this->_peclLoaded) { + if (!$this->peclLoaded) { return parent::endBody(); } - $this->_dkimHandler->eom(); + $this->dkimHandler->eom(); return $this; } public function reset() { - $this->_dkimHandler = null; + $this->dkimHandler = null; parent::reset(); return $this; @@ -133,11 +128,11 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner * * @param int $time * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureTimestamp($time) { - $this->_signatureTimestamp = $time; + $this->signatureTimestamp = $time; return $this; } @@ -147,11 +142,11 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner * * @param int $time * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setSignatureExpiration($time) { - $this->_signatureExpiration = $time; + $this->signatureExpiration = $time; return $this; } @@ -161,21 +156,21 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner * * @param bool $debug * - * @return Swift_Signers_DKIMSigner + * @return $this */ public function setDebugHeaders($debug) { - $this->_debugHeaders = (bool) $debug; + $this->debugHeaders = (bool) $debug; return $this; } // Protected - protected function _canonicalizeBody($string) + protected function canonicalizeBody($string) { - if (!$this->_peclLoaded) { - return parent::_canonicalizeBody($string); + if (!$this->peclLoaded) { + return parent::canonicalizeBody($string); } if (false && $this->dropFirstLF === true) { if ($string[0] == "\r" && $string[1] == "\n") { @@ -184,7 +179,7 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner } $this->dropFirstLF = false; if (strlen($string)) { - $this->_dkimHandler->body($string); + $this->dkimHandler->body($string); } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php index b267099a860..eea2648c9e9 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php @@ -34,7 +34,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner protected $replacementFactory; /** - * @var Swift_Mime_HeaderFactory + * @var Swift_Mime_SimpleHeaderFactory */ protected $headerFactory; @@ -59,39 +59,20 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner ->lookup('transport.replacementfactory'); $this->signOptions = PKCS7_DETACHED; - - // Supported since php5.4 - if (defined('OPENSSL_CIPHER_AES_128_CBC')) { - $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; - } else { - $this->encryptCipher = OPENSSL_CIPHER_RC2_128; - } - } - - /** - * Returns an new Swift_Signers_SMimeSigner instance. - * - * @param string $certificate - * @param string $privateKey - * - * @return Swift_Signers_SMimeSigner - */ - public static function newInstance($certificate = null, $privateKey = null) - { - return new self($certificate, $privateKey); + $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; } /** * Set the certificate location to use for signing. * - * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php + * @see http://www.php.net/manual/en/openssl.pkcs7.flags.php * * @param string $certificate * @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead * @param int $signOptions Bitwise operator options for openssl_pkcs7_sign() * @param string $extraCerts A file containing intermediate certificates needed by the signing certificate * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED, $extraCerts = null) { @@ -117,13 +98,13 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner /** * Set the certificate location to use for encryption. * - * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php - * @link http://nl3.php.net/manual/en/openssl.ciphers.php + * @see http://www.php.net/manual/en/openssl.pkcs7.flags.php + * @see http://nl3.php.net/manual/en/openssl.ciphers.php * * @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates. * @param int $cipher * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function setEncryptCertificate($recipientCerts, $cipher = null) { @@ -169,7 +150,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner * * @param bool $signThenEncrypt * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function setSignThenEncrypt($signThenEncrypt = true) { @@ -189,7 +170,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner /** * Resets internal states. * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function reset() { @@ -201,7 +182,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner * * @param Swift_Message $message * - * @return Swift_Signers_SMimeSigner + * @return $this */ public function signMessage(Swift_Message $message) { @@ -297,7 +278,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner $args[] = $this->extraCerts; } - if (!call_user_func_array('openssl_pkcs7_sign', $args)) { + if (!openssl_pkcs7_sign(...$args)) { throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string())); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php index 62516114019..011c03ab188 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/SmtpTransport.php @@ -11,7 +11,7 @@ /** * Sends Messages over SMTP with ESMTP support. * - * @author Chris Corbyn + * @author Chris Corbyn * * @method Swift_SmtpTransport setUsername(string $username) Set the username to authenticate with. * @method string getUsername() Get the username to authenticate with. @@ -41,18 +41,4 @@ class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport $this->setPort($port); $this->setEncryption($security); } - - /** - * Create a new SmtpTransport instance. - * - * @param string $host - * @param int $port - * @param string $security - * - * @return Swift_SmtpTransport - */ - public static function newInstance($host = 'localhost', $port = 25, $security = null) - { - return new self($host, $port, $security); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php index c16ab4b38eb..9d0e8fee2be 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Spool.php @@ -35,11 +35,11 @@ interface Swift_Spool /** * Queues a message. * - * @param Swift_Mime_Message $message The message to store + * @param Swift_Mime_SimpleMessage $message The message to store * * @return bool Whether the operation has succeeded */ - public function queueMessage(Swift_Mime_Message $message); + public function queueMessage(Swift_Mime_SimpleMessage $message); /** * Sends messages using the given transport instance. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php index cf9bf78fb8f..f92567ba021 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/SpoolTransport.php @@ -32,16 +32,4 @@ class Swift_SpoolTransport extends Swift_Transport_SpoolTransport $arguments ); } - - /** - * Create a new SpoolTransport instance. - * - * @param Swift_Spool $spool - * - * @return Swift_SpoolTransport - */ - public static function newInstance(Swift_Spool $spool) - { - return new self($spool); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php index d5735667b94..ba1f6d323fc 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php @@ -13,26 +13,26 @@ * * This stream filter deals with Byte arrays rather than simple strings. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilter { /** The needle(s) to search for */ - private $_search; + private $search; /** The replacement(s) to make */ - private $_replace; + private $replace; /** The Index for searching */ - private $_index; + private $index; /** The Search Tree */ - private $_tree = array(); + private $tree = array(); /** Gives the size of the largest search */ - private $_treeMaxLen = 0; + private $treeMaxLen = 0; - private $_repSize; + private $repSize; /** * Create a new ByteArrayReplacementFilter with $search and $replace. @@ -42,11 +42,11 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt */ public function __construct($search, $replace) { - $this->_search = $search; - $this->_index = array(); - $this->_tree = array(); - $this->_replace = array(); - $this->_repSize = array(); + $this->search = $search; + $this->index = array(); + $this->tree = array(); + $this->replace = array(); + $this->repSize = array(); $tree = null; $i = null; @@ -56,10 +56,10 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt $tree[-1] = min(count($replace) - 1, $i - 1); $tree[-2] = $last_size; } - $tree = &$this->_tree; + $tree = &$this->tree; if (is_array($search_element)) { foreach ($search_element as $k => $char) { - $this->_index[$char] = true; + $this->index[$char] = true; if (!isset($tree[$char])) { $tree[$char] = array(); } @@ -74,23 +74,23 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt } $tree = &$tree[$search_element]; $size = max($last_size, $size); - $this->_index[$search_element] = true; + $this->index[$search_element] = true; } } if ($i !== null) { $tree[-1] = min(count($replace) - 1, $i); $tree[-2] = $last_size; - $this->_treeMaxLen = $size; + $this->treeMaxLen = $size; } foreach ($replace as $rep) { if (!is_array($rep)) { $rep = array($rep); } - $this->_replace[] = $rep; + $this->replace[] = $rep; } - for ($i = count($this->_replace) - 1; $i >= 0; --$i) { - $this->_replace[$i] = $rep = $this->filter($this->_replace[$i], $i); - $this->_repSize[$i] = count($rep); + for ($i = count($this->replace) - 1; $i >= 0; --$i) { + $this->replace[$i] = $rep = $this->filter($this->replace[$i], $i); + $this->repSize[$i] = count($rep); } } @@ -105,36 +105,37 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt { $endOfBuffer = end($buffer); - return isset($this->_index[$endOfBuffer]); + return isset($this->index[$endOfBuffer]); } /** * Perform the actual replacements on $buffer and return the result. * * @param array $buffer - * @param int $_minReplaces + * @param int $minReplaces * * @return array */ - public function filter($buffer, $_minReplaces = -1) + public function filter($buffer, $minReplaces = -1) { - if ($this->_treeMaxLen == 0) { + if ($this->treeMaxLen == 0) { return $buffer; } $newBuffer = array(); $buf_size = count($buffer); + $last_size = 0; for ($i = 0; $i < $buf_size; ++$i) { - $search_pos = $this->_tree; + $search_pos = $this->tree; $last_found = PHP_INT_MAX; // We try to find if the next byte is part of a search pattern - for ($j = 0; $j <= $this->_treeMaxLen; ++$j) { + for ($j = 0; $j <= $this->treeMaxLen; ++$j) { // We have a new byte for a search pattern - if (isset($buffer [$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { + if (isset($buffer[$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { $search_pos = $search_pos[$buffer[$p]]; // We have a complete pattern, save, in case we don't find a better match later if (isset($search_pos[-1]) && $search_pos[-1] < $last_found - && $search_pos[-1] > $_minReplaces) { + && $search_pos[-1] > $minReplaces) { $last_found = $search_pos[-1]; $last_size = $search_pos[-2]; } @@ -142,9 +143,9 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt // We got a complete pattern elseif ($last_found !== PHP_INT_MAX) { // Adding replacement datas to output buffer - $rep_size = $this->_repSize[$last_found]; + $rep_size = $this->repSize[$last_found]; for ($j = 0; $j < $rep_size; ++$j) { - $newBuffer[] = $this->_replace[$last_found][$j]; + $newBuffer[] = $this->replace[$last_found][$j]; } // We Move cursor forward $i += $last_size - 1; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php index d0db8b96197..50a63f1aaa2 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php @@ -16,10 +16,10 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter { /** The needle(s) to search for */ - private $_search; + private $search; /** The replacement(s) to make */ - private $_replace; + private $replace; /** * Create a new StringReplacementFilter with $search and $replace. @@ -29,8 +29,8 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter */ public function __construct($search, $replace) { - $this->_search = $search; - $this->_replace = $replace; + $this->search = $search; + $this->replace = $replace; } /** @@ -42,8 +42,12 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter */ public function shouldBuffer($buffer) { + if ('' === $buffer) { + return false; + } + $endOfBuffer = substr($buffer, -1); - foreach ((array) $this->_search as $needle) { + foreach ((array) $this->search as $needle) { if (false !== strpos($needle, $endOfBuffer)) { return true; } @@ -61,6 +65,6 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter */ public function filter($buffer) { - return str_replace($this->_search, $this->_replace, $buffer); + return str_replace($this->search, $this->replace, $buffer); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php index e98240b5bc5..f60f0cf8218 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php @@ -16,7 +16,7 @@ class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_ReplacementFilterFactory { /** Lazy-loaded filters */ - private $_filters = array(); + private $filters = array(); /** * Create a new StreamFilter to replace $search with $replace in a string. @@ -28,18 +28,18 @@ class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_Replac */ public function createFilter($search, $replace) { - if (!isset($this->_filters[$search][$replace])) { - if (!isset($this->_filters[$search])) { - $this->_filters[$search] = array(); + if (!isset($this->filters[$search][$replace])) { + if (!isset($this->filters[$search])) { + $this->filters[$search] = array(); } - if (!isset($this->_filters[$search][$replace])) { - $this->_filters[$search][$replace] = array(); + if (!isset($this->filters[$search][$replace])) { + $this->filters[$search][$replace] = array(); } - $this->_filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); + $this->filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); } - return $this->_filters[$search][$replace]; + return $this->filters[$search][$replace]; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php index 6535eadf253..f6214b7bfc5 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport.php @@ -32,18 +32,41 @@ interface Swift_Transport */ public function stop(); + /** + * Check if this Transport mechanism is alive. + * + * If a Transport mechanism session is no longer functional, the method + * returns FALSE. It is the responsibility of the developer to handle this + * case and restart the Transport mechanism manually. + * + * @example + * + * if (!$transport->ping()) { + * $transport->stop(); + * $transport->start(); + * } + * + * The Transport mechanism will be started, if it is not already. + * + * It is undefined if the Transport mechanism attempts to restart as long as + * the return value reflects whether the mechanism is now functional. + * + * @return bool TRUE if the transport is alive + */ + public function ping(); + /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null); + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null); /** * Register a plugin in the Transport. diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php index 72d4ecdff4d..34c3323fdba 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php @@ -16,34 +16,35 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport { /** Input-Output buffer for sending/receiving SMTP commands and responses */ - protected $_buffer; + protected $buffer; /** Connection status */ - protected $_started = false; + protected $started = false; /** The domain name to use in HELO command */ - protected $_domain = '[127.0.0.1]'; + protected $domain = '[127.0.0.1]'; /** The event dispatching layer */ - protected $_eventDispatcher; + protected $eventDispatcher; /** Source Ip */ - protected $_sourceIp; + protected $sourceIp; /** Return an array of params for the Buffer */ - abstract protected function _getBufferParams(); + abstract protected function getBufferParams(); /** * Creates a new EsmtpTransport using the given I/O buffer. * * @param Swift_Transport_IoBuffer $buf * @param Swift_Events_EventDispatcher $dispatcher + * @param string $localDomain */ - public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher) + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1') { - $this->_eventDispatcher = $dispatcher; - $this->_buffer = $buf; - $this->_lookupHostname(); + $this->eventDispatcher = $dispatcher; + $this->buffer = $buf; + $this->setLocalDomain($localDomain); } /** @@ -52,16 +53,25 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport * This should be a fully-qualified domain name and should be truly the domain * you're using. * - * If your server doesn't have a domain name, use the IP in square - * brackets (i.e. [127.0.0.1]). + * If your server does not have a domain name, use the IP address. This will + * automatically be wrapped in square brackets as described in RFC 5321, + * section 4.1.3. * * @param string $domain * - * @return Swift_Transport_AbstractSmtpTransport + * @return $this */ public function setLocalDomain($domain) { - $this->_domain = $domain; + if (substr($domain, 0, 1) !== '[') { + if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + $domain = '['.$domain.']'; + } elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + $domain = '[IPv6:'.$domain.']'; + } + } + + $this->domain = $domain; return $this; } @@ -69,11 +79,14 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport /** * Get the name of the domain Swift will identify as. * + * If an IP address was specified, this will be returned wrapped in square + * brackets as described in RFC 5321, section 4.1.3. + * * @return string */ public function getLocalDomain() { - return $this->_domain; + return $this->domain; } /** @@ -83,7 +96,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function setSourceIp($source) { - $this->_sourceIp = $source; + $this->sourceIp = $source; } /** @@ -93,7 +106,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function getSourceIp() { - return $this->_sourceIp; + return $this->sourceIp; } /** @@ -101,27 +114,27 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function start() { - if (!$this->_started) { - if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); + if (!$this->started) { + if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); if ($evt->bubbleCancelled()) { return; } } try { - $this->_buffer->initialize($this->_getBufferParams()); + $this->buffer->initialize($this->getBufferParams()); } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } - $this->_readGreeting(); - $this->_doHeloCommand(); + $this->readGreeting(); + $this->doHeloCommand(); if ($evt) { - $this->_eventDispatcher->dispatchEvent($evt, 'transportStarted'); + $this->eventDispatcher->dispatchEvent($evt, 'transportStarted'); } - $this->_started = true; + $this->started = true; } } @@ -132,7 +145,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function isStarted() { - return $this->_started; + return $this->started; } /** @@ -141,25 +154,25 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $sent = 0; $failedRecipients = (array) $failedRecipients; - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } - if (!$reversePath = $this->_getReversePath($message)) { - $this->_throwException(new Swift_TransportException( + if (!$reversePath = $this->getReversePath($message)) { + $this->throwException(new Swift_TransportException( 'Cannot send message without a sender address' ) ); @@ -173,8 +186,8 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport $message->setBcc(array()); try { - $sent += $this->_sendTo($message, $reversePath, $tos, $failedRecipients); - $sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients); + $sent += $this->sendTo($message, $reversePath, $tos, $failedRecipients); + $sent += $this->sendBcc($message, $reversePath, $bcc, $failedRecipients); } catch (Exception $e) { $message->setBcc($bcc); throw $e; @@ -191,7 +204,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); } $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); //Make sure a new Message ID is used @@ -204,9 +217,9 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function stop() { - if ($this->_started) { - if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); + if ($this->started) { + if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); if ($evt->bubbleCancelled()) { return; } @@ -218,16 +231,39 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } try { - $this->_buffer->terminate(); + $this->buffer->terminate(); if ($evt) { - $this->_eventDispatcher->dispatchEvent($evt, 'transportStopped'); + $this->eventDispatcher->dispatchEvent($evt, 'transportStopped'); } } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } } - $this->_started = false; + $this->started = false; + } + + /** + * {@inheritdoc} + */ + public function ping() + { + try { + if (!$this->isStarted()) { + $this->start(); + } + + $this->executeCommand("NOOP\r\n", array(250)); + } catch (Swift_TransportException $e) { + try { + $this->stop(); + } catch (Swift_TransportException $e) { + } + + return false; + } + + return true; } /** @@ -237,7 +273,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_eventDispatcher->bindEventListener($plugin); + $this->eventDispatcher->bindEventListener($plugin); } /** @@ -255,7 +291,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport */ public function getBuffer() { - return $this->_buffer; + return $this->buffer; } /** @@ -273,32 +309,32 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport public function executeCommand($command, $codes = array(), &$failures = null) { $failures = (array) $failures; - $seq = $this->_buffer->write($command); - $response = $this->_getFullResponse($seq); - if ($evt = $this->_eventDispatcher->createCommandEvent($this, $command, $codes)) { - $this->_eventDispatcher->dispatchEvent($evt, 'commandSent'); + $seq = $this->buffer->write($command); + $response = $this->getFullResponse($seq); + if ($evt = $this->eventDispatcher->createCommandEvent($this, $command, $codes)) { + $this->eventDispatcher->dispatchEvent($evt, 'commandSent'); } - $this->_assertResponseCode($response, $codes); + $this->assertResponseCode($response, $codes); return $response; } /** Read the opening SMTP greeting */ - protected function _readGreeting() + protected function readGreeting() { - $this->_assertResponseCode($this->_getFullResponse(0), array(220)); + $this->assertResponseCode($this->getFullResponse(0), array(220)); } /** Send the HELO welcome */ - protected function _doHeloCommand() + protected function doHeloCommand() { $this->executeCommand( - sprintf("HELO %s\r\n", $this->_domain), array(250) + sprintf("HELO %s\r\n", $this->domain), array(250) ); } /** Send the MAIL FROM command */ - protected function _doMailFromCommand($address) + protected function doMailFromCommand($address) { $this->executeCommand( sprintf("MAIL FROM:<%s>\r\n", $address), array(250) @@ -306,7 +342,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send the RCPT TO command */ - protected function _doRcptToCommand($address) + protected function doRcptToCommand($address) { $this->executeCommand( sprintf("RCPT TO:<%s>\r\n", $address), array(250, 251, 252) @@ -314,27 +350,27 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send the DATA command */ - protected function _doDataCommand() + protected function doDataCommand() { $this->executeCommand("DATA\r\n", array(354)); } /** Stream the contents of the message over the buffer */ - protected function _streamMessage(Swift_Mime_Message $message) + protected function streamMessage(Swift_Mime_SimpleMessage $message) { - $this->_buffer->setWriteTranslations(array("\r\n." => "\r\n..")); + $this->buffer->setWriteTranslations(array("\r\n." => "\r\n..")); try { - $message->toByteStream($this->_buffer); - $this->_buffer->flushBuffers(); + $message->toByteStream($this->buffer); + $this->buffer->flushBuffers(); } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } - $this->_buffer->setWriteTranslations(array()); + $this->buffer->setWriteTranslations(array()); $this->executeCommand("\r\n.\r\n", array(250)); } /** Determine the best-use reverse path for this message */ - protected function _getReversePath(Swift_Mime_Message $message) + protected function getReversePath(Swift_Mime_SimpleMessage $message) { $return = $message->getReturnPath(); $sender = $message->getSender(); @@ -355,10 +391,10 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Throw a TransportException, first sending it to any listeners */ - protected function _throwException(Swift_TransportException $e) + protected function throwException(Swift_TransportException $e) { - if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { - $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); + if ($evt = $this->eventDispatcher->createTransportExceptionEvent($this, $e)) { + $this->eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); if (!$evt->bubbleCancelled()) { throw $e; } @@ -368,18 +404,18 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Throws an Exception if a response code is incorrect */ - protected function _assertResponseCode($response, $wanted) + protected function assertResponseCode($response, $wanted) { list($code) = sscanf($response, '%3d'); $valid = (empty($wanted) || in_array($code, $wanted)); - if ($evt = $this->_eventDispatcher->createResponseEvent($this, $response, + if ($evt = $this->eventDispatcher->createResponseEvent($this, $response, $valid)) { - $this->_eventDispatcher->dispatchEvent($evt, 'responseReceived'); + $this->eventDispatcher->dispatchEvent($evt, 'responseReceived'); } if (!$valid) { - $this->_throwException( + $this->throwException( new Swift_TransportException( 'Expected response code '.implode('/', $wanted).' but got code '. '"'.$code.'", with message "'.$response.'"', @@ -389,18 +425,18 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Get an entire multi-line response using its sequence number */ - protected function _getFullResponse($seq) + protected function getFullResponse($seq) { $response = ''; try { do { - $line = $this->_buffer->readLine($seq); + $line = $this->buffer->readLine($seq); $response .= $line; - } while (null !== $line && false !== $line && ' ' != $line{3}); + } while (null !== $line && false !== $line && ' ' != $line[3]); } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } catch (Swift_IoException $e) { - $this->_throwException( + $this->throwException( new Swift_TransportException( $e->getMessage()) ); @@ -410,13 +446,13 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send an email to the given recipients from the given reverse path */ - private function _doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) + private function doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) { $sent = 0; - $this->_doMailFromCommand($reversePath); + $this->doMailFromCommand($reversePath); foreach ($recipients as $forwardPath) { try { - $this->_doRcptToCommand($forwardPath); + $this->doRcptToCommand($forwardPath); ++$sent; } catch (Swift_TransportException $e) { $failedRecipients[] = $forwardPath; @@ -424,8 +460,8 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } if ($sent != 0) { - $this->_doDataCommand(); - $this->_streamMessage($message); + $this->doDataCommand(); + $this->streamMessage($message); } else { $this->reset(); } @@ -434,23 +470,23 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport } /** Send a message to the given To: recipients */ - private function _sendTo(Swift_Mime_Message $message, $reversePath, array $to, array &$failedRecipients) + private function sendTo(Swift_Mime_SimpleMessage $message, $reversePath, array $to, array &$failedRecipients) { if (empty($to)) { return 0; } - return $this->_doMailTransaction($message, $reversePath, array_keys($to), + return $this->doMailTransaction($message, $reversePath, array_keys($to), $failedRecipients); } /** Send a message to all Bcc: recipients */ - private function _sendBcc(Swift_Mime_Message $message, $reversePath, array $bcc, array &$failedRecipients) + private function sendBcc(Swift_Mime_SimpleMessage $message, $reversePath, array $bcc, array &$failedRecipients) { $sent = 0; foreach ($bcc as $forwardPath => $name) { $message->setBcc(array($forwardPath => $name)); - $sent += $this->_doMailTransaction( + $sent += $this->doMailTransaction( $message, $reversePath, array($forwardPath), $failedRecipients ); } @@ -458,33 +494,14 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport return $sent; } - /** Try to determine the hostname of the server this is run on */ - private function _lookupHostname() - { - if (!empty($_SERVER['SERVER_NAME']) - && $this->_isFqdn($_SERVER['SERVER_NAME'])) { - $this->_domain = $_SERVER['SERVER_NAME']; - } elseif (!empty($_SERVER['SERVER_ADDR'])) { - $this->_domain = sprintf('[%s]', $_SERVER['SERVER_ADDR']); - } - } - - /** Determine is the $hostname is a fully-qualified name */ - private function _isFqdn($hostname) - { - // We could do a really thorough check, but there's really no point - if (false !== $dotPos = strpos($hostname, '.')) { - return ($dotPos > 0) && ($dotPos != strlen($hostname) - 1); - } - - return false; - } - /** * Destructor. */ public function __destruct() { - $this->stop(); + try { + $this->stop(); + } catch (Exception $e) { + } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php index 53f721d03c6..26c2d745a95 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php @@ -40,7 +40,7 @@ class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport $challenge = $agent->executeCommand("AUTH CRAM-MD5\r\n", array(334)); $challenge = base64_decode(substr($challenge, 4)); $message = base64_encode( - $username.' '.$this->_getResponse($password, $challenge) + $username.' '.$this->getResponse($password, $challenge) ); $agent->executeCommand(sprintf("%s\r\n", $message), array(235)); @@ -60,7 +60,7 @@ class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport * * @return string */ - private function _getResponse($secret, $challenge) + private function getResponse($secret, $challenge) { if (strlen($secret) > 64) { $secret = pack('H32', md5($secret)); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php index d8331316963..fa5d2110041 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php @@ -13,7 +13,7 @@ /** * Handles NTLM authentication. * - * @author Ward Peeters + * @author Ward Peeters */ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Esmtp_Authenticator { @@ -38,19 +38,17 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es * @param string $password * * @return bool + * + * @throws \LogicException */ public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) { - if (!function_exists('mcrypt_module_open')) { - throw new LogicException('The mcrypt functions need to be enabled to use the NTLM authenticator.'); - } - - if (!function_exists('openssl_random_pseudo_bytes')) { + if (!function_exists('openssl_encrypt')) { throw new LogicException('The OpenSSL extension must be enabled to use the NTLM authenticator.'); } if (!function_exists('bcmul')) { - throw new LogicException('The BCMatch functions must be enabled to use the NTLM authenticator.'); + throw new LogicException('The BCMath functions must be enabled to use the NTLM authenticator.'); } try { @@ -60,7 +58,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es // extra parameters for our unit cases $timestamp = func_num_args() > 3 ? func_get_arg(3) : $this->getCorrectTimestamp(bcmul(microtime(true), '1000')); - $client = func_num_args() > 4 ? func_get_arg(4) : $this->getRandomBytes(8); + $client = func_num_args() > 4 ? func_get_arg(4) : random_bytes(8); // Message 3 response $this->sendMessage3($response, $username, $password, $timestamp, $client, $agent); @@ -125,10 +123,10 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es $responseHex = bin2hex($response); $length = floor(hexdec(substr($responseHex, 28, 4)) / 256) * 2; $offset = floor(hexdec(substr($responseHex, 32, 4)) / 256) * 2; - $challenge = $this->hex2bin(substr($responseHex, 48, 16)); - $context = $this->hex2bin(substr($responseHex, 64, 16)); - $targetInfoH = $this->hex2bin(substr($responseHex, 80, 16)); - $targetName = $this->hex2bin(substr($responseHex, $offset, $length)); + $challenge = hex2bin(substr($responseHex, 48, 16)); + $context = hex2bin(substr($responseHex, 64, 16)); + $targetInfoH = hex2bin(substr($responseHex, 80, 16)); + $targetName = hex2bin(substr($responseHex, $offset, $length)); $offset = floor(hexdec(substr($responseHex, 88, 4)) / 256) * 2; $targetInfoBlock = substr($responseHex, $offset); list($domainName, $serverName, $DNSDomainName, $DNSServerName, $terminatorByte) = $this->readSubBlock($targetInfoBlock); @@ -142,7 +140,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es $serverName, $DNSDomainName, $DNSServerName, - $this->hex2bin($targetInfoBlock), + hex2bin($targetInfoBlock), $terminatorByte, ); } @@ -165,7 +163,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es while ($offset < $length) { $blockLength = hexdec(substr(substr($block, $offset, 8), -4)) / 256; $offset += 8; - $data[] = $this->hex2bin(substr($block, $offset, $blockLength * 2)); + $data[] = hex2bin(substr($block, $offset, $blockLength * 2)); $offset += $blockLength * 2; } @@ -300,9 +298,14 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es return explode('\\', $name); } - list($user, $domain) = explode('@', $name); + if (false !== strpos($name, '@')) { + list($user, $domain) = explode('@', $name); - return array($domain, $user); + return array($domain, $user); + } + + // no domain passed + return array('', $name); } /** @@ -365,11 +368,9 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es protected function getCorrectTimestamp($time) { // Get our timestamp (tricky!) - bcscale(0); - $time = number_format($time, 0, '.', ''); // save microtime to string - $time = bcadd($time, '11644473600000'); // add epoch time - $time = bcmul($time, 10000); // tenths of a microsecond. + $time = bcadd($time, '11644473600000', 0); // add epoch time + $time = bcmul($time, 10000, 0); // tenths of a microsecond. $binary = $this->si2bin($time, 64); // create 64 bit binary string $timestamp = ''; @@ -459,10 +460,11 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es } } - return $this->hex2bin(implode('', $material)); + return hex2bin(implode('', $material)); } /** HELPER FUNCTIONS */ + /** * Create our security buffer depending on length and offset. * @@ -538,7 +540,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es protected function createByte($input, $bytes = 4, $isHex = true) { if ($isHex) { - $byte = $this->hex2bin(str_pad($input, $bytes * 2, '00')); + $byte = hex2bin(str_pad($input, $bytes * 2, '00')); } else { $byte = str_pad($input, $bytes, "\x00"); } @@ -546,39 +548,19 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es return $byte; } - /** - * Create random bytes. - * - * @param $length - * - * @return string - */ - protected function getRandomBytes($length) - { - $bytes = openssl_random_pseudo_bytes($length, $strong); - - if (false !== $bytes && true === $strong) { - return $bytes; - } - - throw new RuntimeException('OpenSSL did not produce a secure random number.'); - } - /** ENCRYPTION ALGORITHMS */ + /** * DES Encryption. * - * @param string $value + * @param string $value An 8-byte string * @param string $key * * @return string */ protected function desEncrypt($value, $key) { - $cipher = mcrypt_module_open(MCRYPT_DES, '', 'ecb', ''); - mcrypt_generic_init($cipher, $key, mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_DEV_RANDOM)); - - return mcrypt_generic($cipher, $value); + return substr(openssl_encrypt($value, 'DES-ECB', $key, \OPENSSL_RAW_DATA), 0, 8); } /** @@ -616,7 +598,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es { $input = $this->convertTo16bit($input); - return function_exists('hash') ? $this->hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); + return function_exists('hash') ? hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); } /** @@ -631,22 +613,6 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es return iconv('UTF-8', 'UTF-16LE', $input); } - /** - * Hex2bin replacement for < PHP 5.4. - * - * @param string $hex - * - * @return string Binary - */ - protected function hex2bin($hex) - { - if (function_exists('hex2bin')) { - return hex2bin($hex); - } else { - return pack('H*', $hex); - } - } - /** * @param string $message */ @@ -671,7 +637,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es 'Target Information Terminator', ); - $data = $this->parseMessage2($this->hex2bin($message)); + $data = $this->parseMessage2(hex2bin($message)); foreach ($map as $key => $value) { echo bin2hex($data[$key]).' - '.$data[$key].' ||| '.$value."
\n"; @@ -717,7 +683,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es ); foreach ($map as $key => $value) { - echo $data[$key].' - '.$this->hex2bin($data[$key]).' ||| '.$value."
\n"; + echo $data[$key].' - '.hex2bin($data[$key]).' ||| '.$value."
\n"; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php index ca35e7b83ad..d1a4cc3d774 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php @@ -13,7 +13,7 @@ * * Example: * - * $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls') + * $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls')) * ->setAuthMode('XOAUTH2') * ->setUsername('YOUR_EMAIL_ADDRESS') * ->setPassword('YOUR_ACCESS_TOKEN'); diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php index cb36133c94d..94387f01a2e 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php @@ -20,35 +20,35 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler * * @var Swift_Transport_Esmtp_Authenticator[] */ - private $_authenticators = array(); + private $authenticators = array(); /** * The username for authentication. * * @var string */ - private $_username; + private $username; /** * The password for authentication. * * @var string */ - private $_password; + private $password; /** * The auth mode for authentication. * * @var string */ - private $_auth_mode; + private $auth_mode; /** * The ESMTP AUTH parameters available. * * @var string[] */ - private $_esmtpParams = array(); + private $esmtpParams = array(); /** * Create a new AuthHandler with $authenticators for support. @@ -67,7 +67,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setAuthenticators(array $authenticators) { - $this->_authenticators = $authenticators; + $this->authenticators = $authenticators; } /** @@ -77,7 +77,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getAuthenticators() { - return $this->_authenticators; + return $this->authenticators; } /** @@ -87,7 +87,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setUsername($username) { - $this->_username = $username; + $this->username = $username; } /** @@ -97,7 +97,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getUsername() { - return $this->_username; + return $this->username; } /** @@ -107,7 +107,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setPassword($password) { - $this->_password = $password; + $this->password = $password; } /** @@ -117,7 +117,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getPassword() { - return $this->_password; + return $this->password; } /** @@ -127,7 +127,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setAuthMode($mode) { - $this->_auth_mode = $mode; + $this->auth_mode = $mode; } /** @@ -137,7 +137,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function getAuthMode() { - return $this->_auth_mode; + return $this->auth_mode; } /** @@ -157,7 +157,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function setKeywordParams(array $parameters) { - $this->_esmtpParams = $parameters; + $this->esmtpParams = $parameters; } /** @@ -167,20 +167,20 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler */ public function afterEhlo(Swift_Transport_SmtpAgent $agent) { - if ($this->_username) { + if ($this->username) { $count = 0; - foreach ($this->_getAuthenticatorsForAgent() as $authenticator) { + foreach ($this->getAuthenticatorsForAgent() as $authenticator) { if (in_array(strtolower($authenticator->getAuthKeyword()), - array_map('strtolower', $this->_esmtpParams))) { + array_map('strtolower', $this->esmtpParams))) { ++$count; - if ($authenticator->authenticate($agent, $this->_username, $this->_password)) { + if ($authenticator->authenticate($agent, $this->username, $this->password)) { return; } } } throw new Swift_TransportException( 'Failed to authenticate on SMTP server with username "'. - $this->_username.'" using '.$count.' possible authenticators' + $this->username.'" using '.$count.' possible authenticators' ); } } @@ -246,13 +246,13 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler * * @return array */ - protected function _getAuthenticatorsForAgent() + protected function getAuthenticatorsForAgent() { - if (!$mode = strtolower($this->_auth_mode)) { - return $this->_authenticators; + if (!$mode = strtolower($this->auth_mode)) { + return $this->authenticators; } - foreach ($this->_authenticators as $authenticator) { + foreach ($this->authenticators as $authenticator) { if (strtolower($authenticator->getAuthKeyword()) == $mode) { return array($authenticator); } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php index a1cd0dcd1de..7eb7ef33086 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php @@ -20,21 +20,21 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @var Swift_Transport_EsmtpHandler[] */ - private $_handlers = array(); + private $handlers = array(); /** * ESMTP capabilities. * * @var string[] */ - private $_capabilities = array(); + private $capabilities = array(); /** * Connection buffer parameters. * * @var array */ - private $_params = array( + private $params = array( 'protocol' => 'tcp', 'host' => 'localhost', 'port' => 25, @@ -51,10 +51,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * @param Swift_Transport_IoBuffer $buf * @param Swift_Transport_EsmtpHandler[] $extensionHandlers * @param Swift_Events_EventDispatcher $dispatcher + * @param string $localDomain */ - public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher) + public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1') { - parent::__construct($buf, $dispatcher); + parent::__construct($buf, $dispatcher, $localDomain); $this->setExtensionHandlers($extensionHandlers); } @@ -63,11 +64,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param string $host * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setHost($host) { - $this->_params['host'] = $host; + $this->params['host'] = $host; return $this; } @@ -79,7 +80,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getHost() { - return $this->_params['host']; + return $this->params['host']; } /** @@ -87,11 +88,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param int $port * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setPort($port) { - $this->_params['port'] = (int) $port; + $this->params['port'] = (int) $port; return $this; } @@ -103,7 +104,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getPort() { - return $this->_params['port']; + return $this->params['port']; } /** @@ -111,12 +112,12 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param int $timeout seconds * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setTimeout($timeout) { - $this->_params['timeout'] = (int) $timeout; - $this->_buffer->setParam('timeout', (int) $timeout); + $this->params['timeout'] = (int) $timeout; + $this->buffer->setParam('timeout', (int) $timeout); return $this; } @@ -128,7 +129,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getTimeout() { - return $this->_params['timeout']; + return $this->params['timeout']; } /** @@ -136,16 +137,17 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param string $encryption * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setEncryption($encryption) { + $encryption = strtolower($encryption); if ('tls' == $encryption) { - $this->_params['protocol'] = 'tcp'; - $this->_params['tls'] = true; + $this->params['protocol'] = 'tcp'; + $this->params['tls'] = true; } else { - $this->_params['protocol'] = $encryption; - $this->_params['tls'] = false; + $this->params['protocol'] = $encryption; + $this->params['tls'] = false; } return $this; @@ -158,7 +160,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getEncryption() { - return $this->_params['tls'] ? 'tls' : $this->_params['protocol']; + return $this->params['tls'] ? 'tls' : $this->params['protocol']; } /** @@ -166,11 +168,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param array $options * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setStreamOptions($options) { - $this->_params['stream_context_options'] = $options; + $this->params['stream_context_options'] = $options; return $this; } @@ -182,7 +184,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getStreamOptions() { - return $this->_params['stream_context_options']; + return $this->params['stream_context_options']; } /** @@ -190,11 +192,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param string $source * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setSourceIp($source) { - $this->_params['sourceIp'] = $source; + $this->params['sourceIp'] = $source; return $this; } @@ -206,7 +208,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getSourceIp() { - return isset($this->_params['sourceIp']) ? $this->_params['sourceIp'] : null; + return $this->params['sourceIp'] ?? null; } /** @@ -214,7 +216,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo * * @param Swift_Transport_EsmtpHandler[] $handlers * - * @return Swift_Transport_EsmtpTransport + * @return $this */ public function setExtensionHandlers(array $handlers) { @@ -222,10 +224,11 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo foreach ($handlers as $handler) { $assoc[$handler->getHandledKeyword()] = $handler; } - - @uasort($assoc, array($this, '_sortHandlers')); - $this->_handlers = $assoc; - $this->_setHandlerParams(); + uasort($assoc, function ($a, $b) { + return $a->getPriorityOver($b->getHandledKeyword()); + }); + $this->handlers = $assoc; + $this->setHandlerParams(); return $this; } @@ -237,7 +240,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo */ public function getExtensionHandlers() { - return array_values($this->_handlers); + return array_values($this->handlers); } /** @@ -257,7 +260,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo $failures = (array) $failures; $stopSignal = false; $response = null; - foreach ($this->_getActiveHandlers() as $handler) { + foreach ($this->getActiveHandlers() as $handler) { $response = $handler->onCommand( $this, $command, $codes, $failures, $stopSignal ); @@ -269,18 +272,16 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo return parent::executeCommand($command, $codes, $failures); } - // -- Mixin invocation code - /** Mixin handling method for ESMTP handlers */ public function __call($method, $args) { - foreach ($this->_handlers as $handler) { + foreach ($this->handlers as $handler) { if (in_array(strtolower($method), array_map('strtolower', (array) $handler->exposeMixinMethods()) )) { $return = call_user_func_array(array($handler, $method), $args); // Allow fluid method calls - if (is_null($return) && substr($method, 0, 3) == 'set') { + if (null === $return && substr($method, 0, 3) == 'set') { return $this; } else { return $return; @@ -291,53 +292,53 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Get the params to initialize the buffer */ - protected function _getBufferParams() + protected function getBufferParams() { - return $this->_params; + return $this->params; } /** Overridden to perform EHLO instead */ - protected function _doHeloCommand() + protected function doHeloCommand() { try { $response = $this->executeCommand( - sprintf("EHLO %s\r\n", $this->_domain), array(250) + sprintf("EHLO %s\r\n", $this->domain), array(250) ); } catch (Swift_TransportException $e) { - return parent::_doHeloCommand(); + return parent::doHeloCommand(); } - if ($this->_params['tls']) { + if ($this->params['tls']) { try { $this->executeCommand("STARTTLS\r\n", array(220)); - if (!$this->_buffer->startTLS()) { + if (!$this->buffer->startTLS()) { throw new Swift_TransportException('Unable to connect with TLS encryption'); } try { $response = $this->executeCommand( - sprintf("EHLO %s\r\n", $this->_domain), array(250) + sprintf("EHLO %s\r\n", $this->domain), array(250) ); } catch (Swift_TransportException $e) { - return parent::_doHeloCommand(); + return parent::doHeloCommand(); } } catch (Swift_TransportException $e) { - $this->_throwException($e); + $this->throwException($e); } } - $this->_capabilities = $this->_getCapabilities($response); - $this->_setHandlerParams(); - foreach ($this->_getActiveHandlers() as $handler) { + $this->capabilities = $this->getCapabilities($response); + $this->setHandlerParams(); + foreach ($this->getActiveHandlers() as $handler) { $handler->afterEhlo($this); } } /** Overridden to add Extension support */ - protected function _doMailFromCommand($address) + protected function doMailFromCommand($address) { - $handlers = $this->_getActiveHandlers(); + $handlers = $this->getActiveHandlers(); $params = array(); foreach ($handlers as $handler) { $params = array_merge($params, (array) $handler->getMailParams()); @@ -349,9 +350,9 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Overridden to add Extension support */ - protected function _doRcptToCommand($address) + protected function doRcptToCommand($address) { - $handlers = $this->_getActiveHandlers(); + $handlers = $this->getActiveHandlers(); $params = array(); foreach ($handlers as $handler) { $params = array_merge($params, (array) $handler->getRcptParams()); @@ -363,7 +364,7 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Determine ESMTP capabilities by function group */ - private function _getCapabilities($ehloResponse) + private function getCapabilities($ehloResponse) { $capabilities = array(); $ehloResponse = trim($ehloResponse); @@ -382,31 +383,25 @@ class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTranspo } /** Set parameters which are used by each extension handler */ - private function _setHandlerParams() + private function setHandlerParams() { - foreach ($this->_handlers as $keyword => $handler) { - if (array_key_exists($keyword, $this->_capabilities)) { - $handler->setKeywordParams($this->_capabilities[$keyword]); + foreach ($this->handlers as $keyword => $handler) { + if (array_key_exists($keyword, $this->capabilities)) { + $handler->setKeywordParams($this->capabilities[$keyword]); } } } /** Get ESMTP handlers which are currently ok to use */ - private function _getActiveHandlers() + private function getActiveHandlers() { $handlers = array(); - foreach ($this->_handlers as $keyword => $handler) { - if (array_key_exists($keyword, $this->_capabilities)) { + foreach ($this->handlers as $keyword => $handler) { + if (array_key_exists($keyword, $this->capabilities)) { $handlers[] = $handler; } } return $handlers; } - - /** Custom sort for extension handler ordering */ - private function _sortHandlers($a, $b) - { - return $a->getPriorityOver($b->getHandledKeyword()); - } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php index c039f3beccf..94151f89fef 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php @@ -20,7 +20,31 @@ class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTran * * @var Swift_Transport */ - private $_currentTransport; + private $currentTransport; + + // needed as __construct is called from elsewhere explicitly + public function __construct() + { + parent::__construct(); + } + + /** + * {@inheritdoc} + */ + public function ping() + { + $maxTransports = count($this->transports); + for ($i = 0; $i < $maxTransports + && $transport = $this->getNextTransport(); ++$i) { + if ($transport->ping()) { + return true; + } else { + $this->killCurrentTransport(); + } + } + + return count($this->transports) > 0; + } /** * Send the given Message. @@ -28,35 +52,35 @@ class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTran * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - $maxTransports = count($this->_transports); + $maxTransports = count($this->transports); $sent = 0; - $this->_lastUsedTransport = null; + $this->lastUsedTransport = null; for ($i = 0; $i < $maxTransports - && $transport = $this->_getNextTransport(); ++$i) { + && $transport = $this->getNextTransport(); ++$i) { try { if (!$transport->isStarted()) { $transport->start(); } if ($sent = $transport->send($message, $failedRecipients)) { - $this->_lastUsedTransport = $transport; + $this->lastUsedTransport = $transport; return $sent; } } catch (Swift_TransportException $e) { - $this->_killCurrentTransport(); + $this->killCurrentTransport(); } } - if (count($this->_transports) == 0) { + if (count($this->transports) == 0) { throw new Swift_TransportException( 'All Transports in FailoverTransport failed, or no Transports available' ); @@ -65,18 +89,18 @@ class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTran return $sent; } - protected function _getNextTransport() + protected function getNextTransport() { - if (!isset($this->_currentTransport)) { - $this->_currentTransport = parent::_getNextTransport(); + if (!isset($this->currentTransport)) { + $this->currentTransport = parent::getNextTransport(); } - return $this->_currentTransport; + return $this->currentTransport; } - protected function _killCurrentTransport() + protected function killCurrentTransport() { - $this->_currentTransport = null; - parent::_killCurrentTransport(); + $this->currentTransport = null; + parent::killCurrentTransport(); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php index fbf0b2602e4..dc6a2149bab 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php @@ -20,21 +20,26 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport * * @var Swift_Transport[] */ - private $_deadTransports = array(); + private $deadTransports = array(); /** * The Transports which are used in rotation. * * @var Swift_Transport[] */ - protected $_transports = array(); + protected $transports = array(); /** * The Transport used in the last successful send operation. * * @var Swift_Transport */ - protected $_lastUsedTransport = null; + protected $lastUsedTransport = null; + + // needed as __construct is called from elsewhere explicitly + public function __construct() + { + } /** * Set $transports to delegate to. @@ -43,8 +48,8 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function setTransports(array $transports) { - $this->_transports = $transports; - $this->_deadTransports = array(); + $this->transports = $transports; + $this->deadTransports = array(); } /** @@ -54,7 +59,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function getTransports() { - return array_merge($this->_transports, $this->_deadTransports); + return array_merge($this->transports, $this->deadTransports); } /** @@ -64,7 +69,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function getLastUsedTransport() { - return $this->_lastUsedTransport; + return $this->lastUsedTransport; } /** @@ -74,7 +79,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function isStarted() { - return count($this->_transports) > 0; + return count($this->transports) > 0; } /** @@ -82,7 +87,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function start() { - $this->_transports = array_merge($this->_transports, $this->_deadTransports); + $this->transports = array_merge($this->transports, $this->deadTransports); } /** @@ -90,44 +95,58 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function stop() { - foreach ($this->_transports as $transport) { + foreach ($this->transports as $transport) { $transport->stop(); } } + /** + * {@inheritdoc} + */ + public function ping() + { + foreach ($this->transports as $transport) { + if (!$transport->ping()) { + $this->killCurrentTransport(); + } + } + + return count($this->transports) > 0; + } + /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - $maxTransports = count($this->_transports); + $maxTransports = count($this->transports); $sent = 0; - $this->_lastUsedTransport = null; + $this->lastUsedTransport = null; for ($i = 0; $i < $maxTransports - && $transport = $this->_getNextTransport(); ++$i) { + && $transport = $this->getNextTransport(); ++$i) { try { if (!$transport->isStarted()) { $transport->start(); } if ($sent = $transport->send($message, $failedRecipients)) { - $this->_lastUsedTransport = $transport; + $this->lastUsedTransport = $transport; break; } } catch (Swift_TransportException $e) { - $this->_killCurrentTransport(); + $this->killCurrentTransport(); } } - if (count($this->_transports) == 0) { + if (count($this->transports) == 0) { throw new Swift_TransportException( 'All Transports in LoadBalancedTransport failed, or no Transports available' ); @@ -143,7 +162,7 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - foreach ($this->_transports as $transport) { + foreach ($this->transports as $transport) { $transport->registerPlugin($plugin); } } @@ -153,10 +172,10 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport * * @return Swift_Transport */ - protected function _getNextTransport() + protected function getNextTransport() { - if ($next = array_shift($this->_transports)) { - $this->_transports[] = $next; + if ($next = array_shift($this->transports)) { + $this->transports[] = $next; } return $next; @@ -165,14 +184,14 @@ class Swift_Transport_LoadBalancedTransport implements Swift_Transport /** * Tag the currently used (top of stack) transport as dead/useless. */ - protected function _killCurrentTransport() + protected function killCurrentTransport() { - if ($transport = array_pop($this->_transports)) { + if ($transport = array_pop($this->transports)) { try { $transport->stop(); } catch (Exception $e) { } - $this->_deadTransports[] = $transport; + $this->deadTransports[] = $transport; } } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php deleted file mode 100644 index 77489cedc68..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php +++ /dev/null @@ -1,32 +0,0 @@ -_invoker = $invoker; - $this->_eventDispatcher = $eventDispatcher; - } - - /** - * Not used. - */ - public function isStarted() - { - return false; - } - - /** - * Not used. - */ - public function start() - { - } - - /** - * Not used. - */ - public function stop() - { - } - - /** - * Set the additional parameters used on the mail() function. - * - * This string is formatted for sprintf() where %s is the sender address. - * - * @param string $params - * - * @return Swift_Transport_MailTransport - */ - public function setExtraParams($params) - { - $this->_extraParams = $params; - - return $this; - } - - /** - * Get the additional parameters used on the mail() function. - * - * This string is formatted for sprintf() where %s is the sender address. - * - * @return string - */ - public function getExtraParams() - { - return $this->_extraParams; - } - - /** - * Send the given Message. - * - * Recipient/sender data will be retrieved from the Message API. - * The return value is the number of recipients who were accepted for delivery. - * - * @param Swift_Mime_Message $message - * @param string[] $failedRecipients An array of failures by-reference - * - * @return int - */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) - { - $failedRecipients = (array) $failedRecipients; - - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); - if ($evt->bubbleCancelled()) { - return 0; - } - } - - $count = ( - count((array) $message->getTo()) - + count((array) $message->getCc()) - + count((array) $message->getBcc()) - ); - - $toHeader = $message->getHeaders()->get('To'); - $subjectHeader = $message->getHeaders()->get('Subject'); - - if (!$toHeader) { - $this->_throwException(new Swift_TransportException('Cannot send message without a recipient')); - } - $to = $toHeader->getFieldBody(); - $subject = $subjectHeader ? $subjectHeader->getFieldBody() : ''; - - $reversePath = $this->_getReversePath($message); - - // Remove headers that would otherwise be duplicated - $message->getHeaders()->remove('To'); - $message->getHeaders()->remove('Subject'); - - $messageStr = $message->toString(); - - $message->getHeaders()->set($toHeader); - $message->getHeaders()->set($subjectHeader); - - // Separate headers from body - if (false !== $endHeaders = strpos($messageStr, "\r\n\r\n")) { - $headers = substr($messageStr, 0, $endHeaders)."\r\n"; //Keep last EOL - $body = substr($messageStr, $endHeaders + 4); - } else { - $headers = $messageStr."\r\n"; - $body = ''; - } - - unset($messageStr); - - if ("\r\n" != PHP_EOL) { - // Non-windows (not using SMTP) - $headers = str_replace("\r\n", PHP_EOL, $headers); - $subject = str_replace("\r\n", PHP_EOL, $subject); - $body = str_replace("\r\n", PHP_EOL, $body); - } else { - // Windows, using SMTP - $headers = str_replace("\r\n.", "\r\n..", $headers); - $subject = str_replace("\r\n.", "\r\n..", $subject); - $body = str_replace("\r\n.", "\r\n..", $body); - } - - if ($this->_invoker->mail($to, $subject, $body, $headers, - sprintf($this->_extraParams, escapeshellarg($reversePath)))) { - if ($evt) { - $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); - $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); - } - } else { - $failedRecipients = array_merge( - $failedRecipients, - array_keys((array) $message->getTo()), - array_keys((array) $message->getCc()), - array_keys((array) $message->getBcc()) - ); - - if ($evt) { - $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); - $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); - } - - $message->generateId(); - - $count = 0; - } - - return $count; - } - - /** - * Register a plugin. - * - * @param Swift_Events_EventListener $plugin - */ - public function registerPlugin(Swift_Events_EventListener $plugin) - { - $this->_eventDispatcher->bindEventListener($plugin); - } - - /** Throw a TransportException, first sending it to any listeners */ - protected function _throwException(Swift_TransportException $e) - { - if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { - $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); - if (!$evt->bubbleCancelled()) { - throw $e; - } - } else { - throw $e; - } - } - - /** Determine the best-use reverse path for this message */ - private function _getReversePath(Swift_Mime_Message $message) - { - $return = $message->getReturnPath(); - $sender = $message->getSender(); - $from = $message->getFrom(); - $path = null; - if (!empty($return)) { - $path = $return; - } elseif (!empty($sender)) { - $keys = array_keys($sender); - $path = array_shift($keys); - } elseif (!empty($from)) { - $keys = array_keys($from); - $path = array_shift($keys); - } - - return $path; - } -} diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php index ad20e0e535f..dc38078c3c3 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/NullTransport.php @@ -16,14 +16,14 @@ class Swift_Transport_NullTransport implements Swift_Transport { /** The event dispatcher from the plugin API */ - private $_eventDispatcher; + private $eventDispatcher; /** * Constructor. */ public function __construct(Swift_Events_EventDispatcher $eventDispatcher) { - $this->_eventDispatcher = $eventDispatcher; + $this->eventDispatcher = $eventDispatcher; } /** @@ -50,18 +50,26 @@ class Swift_Transport_NullTransport implements Swift_Transport { } + /** + * {@inheritdoc} + */ + public function ping() + { + return true; + } + /** * Sends the given message. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent emails */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } @@ -69,7 +77,7 @@ class Swift_Transport_NullTransport implements Swift_Transport if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $count = ( @@ -88,6 +96,6 @@ class Swift_Transport_NullTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_eventDispatcher->bindEventListener($plugin); + $this->eventDispatcher->bindEventListener($plugin); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php index 34ac4ce3af8..807538505bf 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php @@ -24,7 +24,7 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * * @var array */ - private $_params = array( + private $params = array( 'timeout' => 30, 'blocking' => 1, 'command' => '/usr/sbin/sendmail -bs', @@ -36,10 +36,11 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * * @param Swift_Transport_IoBuffer $buf * @param Swift_Events_EventDispatcher $dispatcher + * @param string $localDomain */ - public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher) + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1') { - parent::__construct($buf, $dispatcher); + parent::__construct($buf, $dispatcher, $localDomain); } /** @@ -64,11 +65,11 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * * @param string $command * - * @return Swift_Transport_SendmailTransport + * @return $this */ public function setCommand($command) { - $this->_params['command'] = $command; + $this->params['command'] = $command; return $this; } @@ -80,7 +81,7 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran */ public function getCommand() { - return $this->_params['command']; + return $this->params['command']; } /** @@ -92,12 +93,12 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran * NOTE: If using 'sendmail -t' you will not be aware of any failures until * they bounce (i.e. send() will always return 100% success). * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; $command = $this->getCommand(); @@ -105,18 +106,18 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran $count = 0; if (false !== strpos($command, ' -t')) { - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } if (false === strpos($command, ' -f')) { - $command .= ' -f'.escapeshellarg($this->_getReversePath($message)); + $command .= ' -f'.escapeshellarg($this->getReversePath($message)); } - $buffer->initialize(array_merge($this->_params, array('command' => $command))); + $buffer->initialize(array_merge($this->params, array('command' => $command))); if (false === strpos($command, ' -i') && false === strpos($command, ' -oi')) { $buffer->setWriteTranslations(array("\r\n" => "\n", "\n." => "\n..")); @@ -136,14 +137,14 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); $evt->setFailedRecipients($failedRecipients); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); } elseif (false !== strpos($command, ' -bs')) { $count = parent::send($message, $failedRecipients); } else { - $this->_throwException(new Swift_TransportException( + $this->throwException(new Swift_TransportException( 'Unsupported sendmail command flags ['.$command.']. '. 'Must be one of "-bs" or "-t" but can include additional flags.' )); @@ -153,8 +154,8 @@ class Swift_Transport_SendmailTransport extends Swift_Transport_AbstractSmtpTran } /** Get the params to initialize the buffer */ - protected function _getBufferParams() + protected function getBufferParams() { - return $this->_params; + return $this->params; } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php deleted file mode 100644 index 4cab66bd6bf..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php +++ /dev/null @@ -1,39 +0,0 @@ -_eventDispatcher = $eventDispatcher; - $this->_spool = $spool; + $this->eventDispatcher = $eventDispatcher; + $this->spool = $spool; } /** @@ -35,11 +35,11 @@ class Swift_Transport_SpoolTransport implements Swift_Transport * * @param Swift_Spool $spool * - * @return Swift_Transport_SpoolTransport + * @return $this */ public function setSpool(Swift_Spool $spool) { - $this->_spool = $spool; + $this->spool = $spool; return $this; } @@ -51,7 +51,7 @@ class Swift_Transport_SpoolTransport implements Swift_Transport */ public function getSpool() { - return $this->_spool; + return $this->spool; } /** @@ -78,28 +78,36 @@ class Swift_Transport_SpoolTransport implements Swift_Transport { } + /** + * {@inheritdoc} + */ + public function ping() + { + return true; + } + /** * Sends the given message. * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent e-mail's */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) + public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) { - if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { - $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) { + $this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } - $success = $this->_spool->queueMessage($message); + $success = $this->spool->queueMessage($message); if ($evt) { $evt->setResult($success ? Swift_Events_SendEvent::RESULT_SPOOLED : Swift_Events_SendEvent::RESULT_FAILED); - $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + $this->eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } return 1; @@ -112,6 +120,6 @@ class Swift_Transport_SpoolTransport implements Swift_Transport */ public function registerPlugin(Swift_Events_EventListener $plugin) { - $this->_eventDispatcher->bindEventListener($plugin); + $this->eventDispatcher->bindEventListener($plugin); } } diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php index 5134ea48a45..bc6ed5a34b4 100644 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php +++ b/htdocs/includes/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php @@ -11,27 +11,27 @@ /** * A generic IoBuffer implementation supporting remote sockets and local processes. * - * @author Chris Corbyn + * @author Chris Corbyn */ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_Transport_IoBuffer { /** A primary socket */ - private $_stream; + private $stream; /** The input stream */ - private $_in; + private $in; /** The output stream */ - private $_out; + private $out; /** Buffer initialization parameters */ - private $_params = array(); + private $params = array(); /** The ReplacementFilterFactory */ - private $_replacementFactory; + private $replacementFactory; /** Translations performed on data being streamed into the buffer */ - private $_translations = array(); + private $translations = array(); /** * Create a new StreamBuffer using $replacementFactory for transformations. @@ -40,7 +40,7 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function __construct(Swift_ReplacementFilterFactory $replacementFactory) { - $this->_replacementFactory = $replacementFactory; + $this->replacementFactory = $replacementFactory; } /** @@ -52,14 +52,14 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function initialize(array $params) { - $this->_params = $params; + $this->params = $params; switch ($params['type']) { case self::TYPE_PROCESS: - $this->_establishProcessConnection(); + $this->establishProcessConnection(); break; case self::TYPE_SOCKET: default: - $this->_establishSocketConnection(); + $this->establishSocketConnection(); break; } } @@ -72,27 +72,26 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function setParam($param, $value) { - if (isset($this->_stream)) { + if (isset($this->stream)) { switch ($param) { case 'timeout': - if ($this->_stream) { - stream_set_timeout($this->_stream, $value); + if ($this->stream) { + stream_set_timeout($this->stream, $value); } break; case 'blocking': - if ($this->_stream) { - stream_set_blocking($this->_stream, 1); + if ($this->stream) { + stream_set_blocking($this->stream, 1); } - } } - $this->_params[$param] = $value; + $this->params[$param] = $value; } public function startTLS() { - return stream_socket_enable_crypto($this->_stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); + return stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); } /** @@ -100,22 +99,22 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function terminate() { - if (isset($this->_stream)) { - switch ($this->_params['type']) { + if (isset($this->stream)) { + switch ($this->params['type']) { case self::TYPE_PROCESS: - fclose($this->_in); - fclose($this->_out); - proc_close($this->_stream); + fclose($this->in); + fclose($this->out); + proc_close($this->stream); break; case self::TYPE_SOCKET: default: - fclose($this->_stream); + fclose($this->stream); break; } } - $this->_stream = null; - $this->_out = null; - $this->_in = null; + $this->stream = null; + $this->out = null; + $this->in = null; } /** @@ -128,19 +127,19 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn */ public function setWriteTranslations(array $replacements) { - foreach ($this->_translations as $search => $replace) { + foreach ($this->translations as $search => $replace) { if (!isset($replacements[$search])) { $this->removeFilter($search); - unset($this->_translations[$search]); + unset($this->translations[$search]); } } foreach ($replacements as $search => $replace) { - if (!isset($this->_translations[$search])) { + if (!isset($this->translations[$search])) { $this->addFilter( - $this->_replacementFactory->createFilter($search, $replace), $search + $this->replacementFactory->createFilter($search, $replace), $search ); - $this->_translations[$search] = true; + $this->translations[$search] = true; } } } @@ -153,20 +152,20 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn * * @param int $sequence of last write to scan from * - * @throws Swift_IoException - * * @return string + * + * @throws Swift_IoException */ public function readLine($sequence) { - if (isset($this->_out) && !feof($this->_out)) { - $line = fgets($this->_out); + if (isset($this->out) && !feof($this->out)) { + $line = fgets($this->out); if (strlen($line) == 0) { - $metas = stream_get_meta_data($this->_out); + $metas = stream_get_meta_data($this->out); if ($metas['timed_out']) { throw new Swift_IoException( 'Connection to '. - $this->_getReadConnectionDescription(). + $this->getReadConnectionDescription(). ' Timed Out' ); } @@ -185,20 +184,20 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn * * @param int $length * - * @throws Swift_IoException - * * @return string|bool + * + * @throws Swift_IoException */ public function read($length) { - if (isset($this->_out) && !feof($this->_out)) { - $ret = fread($this->_out, $length); + if (isset($this->out) && !feof($this->out)) { + $ret = fread($this->out, $length); if (strlen($ret) == 0) { - $metas = stream_get_meta_data($this->_out); + $metas = stream_get_meta_data($this->out); if ($metas['timed_out']) { throw new Swift_IoException( 'Connection to '. - $this->_getReadConnectionDescription(). + $this->getReadConnectionDescription(). ' Timed Out' ); } @@ -214,22 +213,22 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn } /** Flush the stream contents */ - protected function _flush() + protected function flush() { - if (isset($this->_in)) { - fflush($this->_in); + if (isset($this->in)) { + fflush($this->in); } } /** Write this bytes to the stream */ - protected function _commit($bytes) + protected function doCommit($bytes) { - if (isset($this->_in)) { + if (isset($this->in)) { $bytesToWrite = strlen($bytes); $totalBytesWritten = 0; while ($totalBytesWritten < $bytesToWrite) { - $bytesWritten = fwrite($this->_in, substr($bytes, $totalBytesWritten)); + $bytesWritten = fwrite($this->in, substr($bytes, $totalBytesWritten)); if (false === $bytesWritten || 0 === $bytesWritten) { break; } @@ -238,7 +237,7 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn } if ($totalBytesWritten > 0) { - return ++$this->_sequence; + return ++$this->sequence; } } } @@ -246,77 +245,79 @@ class Swift_Transport_StreamBuffer extends Swift_ByteStream_AbstractFilterableIn /** * Establishes a connection to a remote server. */ - private function _establishSocketConnection() + private function establishSocketConnection() { - $host = $this->_params['host']; - if (!empty($this->_params['protocol'])) { - $host = $this->_params['protocol'].'://'.$host; + $host = $this->params['host']; + if (!empty($this->params['protocol'])) { + $host = $this->params['protocol'].'://'.$host; } $timeout = 15; - if (!empty($this->_params['timeout'])) { - $timeout = $this->_params['timeout']; + if (!empty($this->params['timeout'])) { + $timeout = $this->params['timeout']; } $options = array(); - if (!empty($this->_params['sourceIp'])) { - $options['socket']['bindto'] = $this->_params['sourceIp'].':0'; + if (!empty($this->params['sourceIp'])) { + $options['socket']['bindto'] = $this->params['sourceIp'].':0'; } - if (isset($this->_params['stream_context_options'])) { - $options = array_merge($options, $this->_params['stream_context_options']); + + if (isset($this->params['stream_context_options'])) { + $options = array_merge($options, $this->params['stream_context_options']); } $streamContext = stream_context_create($options); - $this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext); - if (false === $this->_stream) { + $this->stream = @stream_socket_client($host.':'.$this->params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext); + if (false === $this->stream) { throw new Swift_TransportException( - 'Connection could not be established with host '.$this->_params['host']. + 'Connection could not be established with host '.$this->params['host']. ' ['.$errstr.' #'.$errno.']' ); } - if (!empty($this->_params['blocking'])) { - stream_set_blocking($this->_stream, 1); + if (!empty($this->params['blocking'])) { + stream_set_blocking($this->stream, 1); } else { - stream_set_blocking($this->_stream, 0); + stream_set_blocking($this->stream, 0); } - stream_set_timeout($this->_stream, $timeout); - $this->_in = &$this->_stream; - $this->_out = &$this->_stream; + stream_set_timeout($this->stream, $timeout); + $this->in = &$this->stream; + $this->out = &$this->stream; } /** * Opens a process for input/output. */ - private function _establishProcessConnection() + private function establishProcessConnection() { - $command = $this->_params['command']; + $command = $this->params['command']; $descriptorSpec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'), ); - $this->_stream = proc_open($command, $descriptorSpec, $pipes); + $pipes = array(); + $this->stream = proc_open($command, $descriptorSpec, $pipes); stream_set_blocking($pipes[2], 0); if ($err = stream_get_contents($pipes[2])) { throw new Swift_TransportException( 'Process could not be started ['.$err.']' ); } - $this->_in = &$pipes[0]; - $this->_out = &$pipes[1]; + $this->in = &$pipes[0]; + $this->out = &$pipes[1]; } - private function _getReadConnectionDescription() + private function getReadConnectionDescription() { - switch ($this->_params['type']) { + switch ($this->params['type']) { case self::TYPE_PROCESS: - return 'Process '.$this->_params['command']; + return 'Process '.$this->params['command']; break; case self::TYPE_SOCKET: default: - $host = $this->_params['host']; - if (!empty($this->_params['protocol'])) { - $host = $this->_params['protocol'].'://'.$host; + $host = $this->params['host']; + if (!empty($this->params['protocol'])) { + $host = $this->params['protocol'].'://'.$host; } - $host .= ':'.$this->_params['port']; + $host .= ':'.$this->params['port']; return $host; break; diff --git a/htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php b/htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php deleted file mode 100644 index e16c212c49f..00000000000 --- a/htdocs/includes/swiftmailer/lib/classes/Swift/Validate.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ -class Swift_Validate -{ - /** - * Grammar Object. - * - * @var Swift_Mime_Grammar - */ - private static $grammar = null; - - /** - * Checks if an e-mail address matches the current grammars. - * - * @param string $email - * - * @return bool - */ - public static function email($email) - { - if (self::$grammar === null) { - self::$grammar = Swift_DependencyContainer::getInstance() - ->lookup('mime.grammar'); - } - - return (bool) preg_match( - '/^'.self::$grammar->getDefinition('addr-spec').'$/D', - $email - ); - } -} diff --git a/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php b/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php index 04f394b3267..4ce9c7cbbc5 100644 --- a/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php +++ b/htdocs/includes/swiftmailer/lib/dependency_maps/mime_deps.php @@ -1,13 +1,25 @@ register('properties.charset') ->asValue('utf-8') - ->register('mime.grammar') - ->asSharedInstanceOf('Swift_Mime_Grammar') + ->register('email.validator') + ->asSharedInstanceOf('Egulias\EmailValidator\EmailValidator') + + ->register('mime.idgenerator.idright') + // As SERVER_NAME can come from the user in certain configurations, check that + // it does not contain forbidden characters (see RFC 952 and RFC 2181). Use + // preg_replace() instead of preg_match() to prevent DoS attacks with long host names. + ->asValue(!empty($_SERVER['SERVER_NAME']) && preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $_SERVER['SERVER_NAME']) === '' ? $_SERVER['SERVER_NAME'] : 'swift.generated') + + ->register('mime.idgenerator') + ->asSharedInstanceOf('Swift_Mime_IdGenerator') + ->withDependencies(array( + 'mime.idgenerator.idright', + )) ->register('mime.message') ->asNewInstanceOf('Swift_Mime_SimpleMessage') @@ -15,7 +27,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.qpcontentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', 'properties.charset', )) @@ -25,7 +37,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.qpcontentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', 'properties.charset', )) @@ -35,7 +47,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.base64contentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', )) ->addConstructorValue($swift_mime_types) @@ -45,7 +57,7 @@ Swift_DependencyContainer::getInstance() 'mime.headerset', 'mime.base64contentencoder', 'cache', - 'mime.grammar', + 'mime.idgenerator', )) ->addConstructorValue($swift_mime_types) @@ -54,7 +66,7 @@ Swift_DependencyContainer::getInstance() ->withDependencies(array( 'mime.qpheaderencoder', 'mime.rfc2231encoder', - 'mime.grammar', + 'email.validator', 'properties.charset', )) @@ -93,7 +105,7 @@ Swift_DependencyContainer::getInstance() ->withDependencies(array('properties.charset')) ->asNewInstanceOf('Swift_Mime_ContentEncoder_NativeQpContentEncoder') - ->register('mime.qpcontentencoderproxy') + ->register('mime.qpcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoderProxy') ->withDependencies(array('mime.safeqpcontentencoder', 'mime.nativeqpcontentencoder', 'properties.charset')) @@ -113,11 +125,6 @@ Swift_DependencyContainer::getInstance() ->register('mime.rfc2231encoder') ->asNewInstanceOf('Swift_Encoder_Rfc2231Encoder') ->withDependencies(array('mime.charstream')) - - // As of PHP 5.4.7, the quoted_printable_encode() function behaves correctly. - // see https://github.com/php/php-src/commit/18bb426587d62f93c54c40bf8535eb8416603629 - ->register('mime.qpcontentencoder') - ->asAliasOf(version_compare(phpversion(), '5.4.7', '>=') ? 'mime.qpcontentencoderproxy' : 'mime.safeqpcontentencoder') ; unset($swift_mime_types); diff --git a/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php b/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php index 77e432cfac0..15772abb255 100644 --- a/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php +++ b/htdocs/includes/swiftmailer/lib/dependency_maps/transport_deps.php @@ -1,12 +1,19 @@ register('transport.localdomain') + // As SERVER_NAME can come from the user in certain configurations, check that + // it does not contain forbidden characters (see RFC 952 and RFC 2181). Use + // preg_replace() instead of preg_match() to prevent DoS attacks with long host names. + ->asValue(!empty($_SERVER['SERVER_NAME']) && preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $_SERVER['SERVER_NAME']) === '' ? trim($_SERVER['SERVER_NAME'], '[]') : '127.0.0.1') + ->register('transport.smtp') ->asNewInstanceOf('Swift_Transport_EsmtpTransport') ->withDependencies(array( 'transport.buffer', array('transport.authhandler'), 'transport.eventdispatcher', + 'transport.localdomain', )) ->register('transport.sendmail') @@ -14,12 +21,9 @@ Swift_DependencyContainer::getInstance() ->withDependencies(array( 'transport.buffer', 'transport.eventdispatcher', + 'transport.localdomain', )) - ->register('transport.mail') - ->asNewInstanceOf('Swift_Transport_MailTransport') - ->withDependencies(array('transport.mailinvoker', 'transport.eventdispatcher')) - ->register('transport.loadbalanced') ->asNewInstanceOf('Swift_Transport_LoadBalancedTransport') @@ -34,9 +38,6 @@ Swift_DependencyContainer::getInstance() ->asNewInstanceOf('Swift_Transport_NullTransport') ->withDependencies(array('transport.eventdispatcher')) - ->register('transport.mailinvoker') - ->asSharedInstanceOf('Swift_Transport_SimpleMailInvoker') - ->register('transport.buffer') ->asNewInstanceOf('Swift_Transport_StreamBuffer') ->withDependencies(array('transport.replacementfactory')) diff --git a/htdocs/includes/swiftmailer/lib/mime_types.php b/htdocs/includes/swiftmailer/lib/mime_types.php index 2d7b98dc1aa..b42c1cc1a3e 100644 --- a/htdocs/includes/swiftmailer/lib/mime_types.php +++ b/htdocs/includes/swiftmailer/lib/mime_types.php @@ -7,7 +7,7 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * - * autogenerated using http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types + * autogenerated using https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types * and https://raw.github.com/minad/mimemagic/master/script/freedesktop.org.xml */ diff --git a/htdocs/includes/swiftmailer/lib/preferences.php b/htdocs/includes/swiftmailer/lib/preferences.php index e5195014824..27b7065dbee 100644 --- a/htdocs/includes/swiftmailer/lib/preferences.php +++ b/htdocs/includes/swiftmailer/lib/preferences.php @@ -17,9 +17,3 @@ $preferences->setCharset('utf-8'); if (@is_writable($tmpDir = sys_get_temp_dir())) { $preferences->setTempDir($tmpDir)->setCacheType('disk'); } - -// this should only be done when Swiftmailer won't use the native QP content encoder -// see mime_deps.php -if (version_compare(phpversion(), '5.4.7', '<')) { - $preferences->setQPDotEscape(false); -} diff --git a/htdocs/includes/swiftmailer/lib/swift_init.php b/htdocs/includes/swiftmailer/lib/swift_init.php deleted file mode 100644 index 5c4bae4f4f1..00000000000 --- a/htdocs/includes/swiftmailer/lib/swift_init.php +++ /dev/null @@ -1,28 +0,0 @@ - 'audio/wav', 'wma' => 'audio/x-ms-wma', 'wmv' => 'audio/x-ms-wmv', - 'xls' => 'application/excel', + 'xls' => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml' => 'application/xml', ); From d31684376a28c1592c79b21233cdb6e767acf4df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Sun, 21 Jan 2018 18:59:48 +0100 Subject: [PATCH 02/91] swiftmailer --- htdocs/core/class/CMailFile.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 25988fd801d..be1eb75a8d1 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -399,6 +399,8 @@ class CMailFile require_once DOL_DOCUMENT_ROOT.'/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/Warning.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/Parser.php'; @@ -406,8 +408,6 @@ class CMailFile require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Create the message //$this->message = Swift_Message::newInstance(); From 0568461a7b5fb2bdb781f9a8f27238d9cb335872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Thu, 25 Jan 2018 22:03:51 +0100 Subject: [PATCH 03/91] swiftmailer --- htdocs/admin/mails.php | 123 +++++++++++++++--- htdocs/core/class/CMailFile.class.php | 46 ++++--- .../EmailValidator/EmailLexer.php | 0 .../EmailValidator/EmailParser.php | 0 .../EmailValidator/EmailValidator.php | 0 .../Exception/AtextAfterCFWS.php | 0 .../EmailValidator/Exception/CRLFAtTheEnd.php | 0 .../EmailValidator/Exception/CRLFX2.php | 0 .../EmailValidator/Exception/CRNoLF.php | 0 .../Exception/CharNotAllowed.php | 0 .../Exception/CommaInDomain.php | 0 .../Exception/ConsecutiveAt.php | 0 .../Exception/ConsecutiveDot.php | 0 .../Exception/DomainHyphened.php | 0 .../EmailValidator/Exception/DotAtEnd.php | 0 .../EmailValidator/Exception/DotAtStart.php | 0 .../EmailValidator/Exception/ExpectingAT.php | 0 .../Exception/ExpectingATEXT.php | 0 .../Exception/ExpectingCTEXT.php | 0 .../Exception/ExpectingDTEXT.php | 0 .../Exception/ExpectingDomainLiteralClose.php | 0 .../Exception/ExpectingQPair.php | 0 .../EmailValidator/Exception/InvalidEmail.php | 0 .../EmailValidator/Exception/NoDNSRecord.php | 0 .../EmailValidator/Exception/NoDomainPart.php | 0 .../EmailValidator/Exception/NoLocalPart.php | 0 .../Exception/UnclosedComment.php | 0 .../Exception/UnclosedQuotedString.php | 0 .../Exception/UnopenedComment.php | 0 .../EmailValidator/Parser/DomainPart.php | 0 .../EmailValidator/Parser/LocalPart.php | 0 .../EmailValidator/Parser/Parser.php | 0 .../Validation/DNSCheckValidation.php | 0 .../Validation/EmailValidation.php | 0 .../Validation/Error/RFCWarnings.php | 0 .../Validation/Error/SpoofEmail.php | 0 .../Exception/EmptyValidationList.php | 0 .../Validation/MultipleErrors.php | 0 .../Validation/MultipleValidationWithAnd.php | 0 .../Validation/NoRFCWarningsValidation.php | 0 .../Validation/RFCValidation.php | 0 .../Validation/SpoofCheckValidation.php | 0 .../EmailValidator/Warning/AddressLiteral.php | 0 .../EmailValidator/Warning/CFWSNearAt.php | 0 .../EmailValidator/Warning/CFWSWithFWS.php | 0 .../EmailValidator/Warning/Comment.php | 0 .../Warning/DeprecatedComment.php | 0 .../EmailValidator/Warning/DomainLiteral.php | 0 .../EmailValidator/Warning/DomainTooLong.php | 0 .../EmailValidator/Warning/EmailTooLong.php | 0 .../EmailValidator/Warning/IPV6BadChar.php | 0 .../EmailValidator/Warning/IPV6ColonEnd.php | 0 .../EmailValidator/Warning/IPV6ColonStart.php | 0 .../EmailValidator/Warning/IPV6Deprecated.php | 0 .../Warning/IPV6DoubleColon.php | 0 .../EmailValidator/Warning/IPV6GroupCount.php | 0 .../EmailValidator/Warning/IPV6MaxGroups.php | 0 .../EmailValidator/Warning/LabelTooLong.php | 0 .../EmailValidator/Warning/LocalTooLong.php | 0 .../EmailValidator/Warning/NoDNSMXRecord.php | 0 .../EmailValidator/Warning/ObsoleteDTEXT.php | 0 .../EmailValidator/Warning/QuotedPart.php | 0 .../EmailValidator/Warning/QuotedString.php | 0 .../EmailValidator/Warning/TLD.php | 0 .../EmailValidator/Warning/Warning.php | 0 .../egulias/email-validator/LICENSE | 0 .../egulias/email-validator/README.md | 0 .../includes/{ => swiftmailer}/lexer/LICENSE | 0 .../{ => swiftmailer}/lexer/README.md | 0 .../{ => swiftmailer}/lexer/composer.json | 0 .../Doctrine/Common/Lexer/AbstractLexer.php | 0 htdocs/langs/fr_FR/admin.lang | 4 + 72 files changed, 137 insertions(+), 36 deletions(-) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/EmailLexer.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/EmailParser.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/EmailValidator.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CRLFX2.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CRNoLF.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/DotAtStart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Parser/DomainPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Parser/LocalPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Parser/Parser.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/EmailValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/RFCValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/Comment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/QuotedPart.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/QuotedString.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/TLD.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/EmailValidator/Warning/Warning.php (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/LICENSE (100%) rename htdocs/includes/{ => swiftmailer}/egulias/email-validator/README.md (100%) rename htdocs/includes/{ => swiftmailer}/lexer/LICENSE (100%) rename htdocs/includes/{ => swiftmailer}/lexer/README.md (100%) rename htdocs/includes/{ => swiftmailer}/lexer/composer.json (100%) rename htdocs/includes/{ => swiftmailer}/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php (100%) diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index d482322a054..e9cbdbb8736 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -78,6 +78,10 @@ if ($action == 'update' && empty($_POST["cancel"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_ENABLED", GETPOST("MAIN_MAIL_EMAIL_DKIM_ENABLED"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_DOMAIN", GETPOST("MAIN_MAIL_EMAIL_DKIM_DOMAIN"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_SELECTOR", GETPOST("MAIN_MAIL_EMAIL_DKIM_SELECTOR"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY", GETPOST("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY"),'chaine',0,'',$conf->entity); // Content parameters dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); @@ -151,26 +155,32 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS").prop("disabled", true); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val(0); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val(0); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").hide(); '; if ($linuxlike) { print ' - jQuery("#MAIN_MAIL_SMTP_SERVER").hide(); - jQuery("#MAIN_MAIL_SMTP_PORT").hide(); - jQuery("#smtp_server_mess").show(); - jQuery("#smtp_port_mess").show(); - '; + jQuery("#MAIN_MAIL_SMTP_SERVER").hide(); + jQuery("#MAIN_MAIL_SMTP_PORT").hide(); + jQuery("#smtp_server_mess").show(); + jQuery("#smtp_port_mess").show();'; } else { - print ' - jQuery("#MAIN_MAIL_SMTP_SERVER").prop("disabled", true); - jQuery("#MAIN_MAIL_SMTP_PORT").prop("disabled", true); - jQuery("#smtp_server_mess").hide(); - jQuery("#smtp_port_mess").hide(); - '; - } - print ' + print ' + jQuery("#MAIN_MAIL_SMTP_SERVER").prop("disabled", true); + jQuery("#MAIN_MAIL_SMTP_PORT").prop("disabled", true); + jQuery("#smtp_server_mess").hide(); + jQuery("#smtp_port_mess").hide();'; + } + print ' } if (jQuery("#MAIN_MAIL_SENDMODE").val()==\'smtps\') { @@ -179,6 +189,14 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val(0); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").hide(); jQuery("#MAIN_MAIL_SMTP_SERVER").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER").show(); @@ -193,6 +211,14 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val('.$conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED.'); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").show(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").show(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").show(); jQuery("#MAIN_MAIL_SMTP_SERVER").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER").show(); @@ -205,16 +231,16 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_SENDMODE").change(function() { initfields(); }); - jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { + jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { if (jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val() == 1) jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val(0); }); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").change(function() { if (jQuery("#MAIN_MAIL_EMAIL_TLS").val() == 1) jQuery("#MAIN_MAIL_EMAIL_TLS").val(0); - }); + }); })'; - print ''."\n"; + print ''."\n"; } print '
'; @@ -368,9 +394,9 @@ if ($action == 'edit') print ''; } - // TLS + // TLS - print ''.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + print ''.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) { if (function_exists('openssl_open')) @@ -383,7 +409,6 @@ if ($action == 'edit') print ''; // STARTTLS - print ''.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) { @@ -396,8 +421,35 @@ if ($action == 'edit') else print yn(0).' ('.$langs->trans("NotSupported").')'; print ''; - // Separator + // DKIM + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_DKIM_ENABLED',(! empty($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED)?$conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED:0),1); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print ''; + // Domain + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_DOMAIN").''; + print ''; + + // Selector + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_SELECTOR").''; + print ''; + + // PRIVATE KEY + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").''; + print ''; + print ''; + + // Separator print ' '; // From @@ -554,7 +606,36 @@ else else print yn(0).' ('.$langs->trans("NotSupported").')'; print ''; - // Separator + // DKIM + + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print ''; + + // Domain + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_DOMAIN").''; + print '' . $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + print ''; + + // Selector + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_SELECTOR").''; + print '' . $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + print ''; + + // PRIVATE KEY + print ''.$langs->trans("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").''; + print '' . $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + print ''; + + // Separator print ' '; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index be1eb75a8d1..e99581de1ed 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -395,25 +395,32 @@ class CMailFile // Use Swift Mailer library // ------------------------------------------ - $host = dol_getprefix('email'); + $host = dol_getprefix('email'); - require_once DOL_DOCUMENT_ROOT.'/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailParser.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailLexer.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/EmailValidator.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/Warning.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/Parser.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/InputByteStream.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php'; + //require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.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(); - - // Adding a trackid header to a message + //$this->message = new Swift_SignedMessage(); + // Adding a trackid header to a message $headers = $this->message->getHeaders(); $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid); $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host; @@ -749,7 +756,16 @@ class CMailFile // Create the Mailer using your created Transport $this->mailer = new Swift_Mailer($this->transport); - if (! empty($conf->global->MAIN_MAIL_DEBUG)) { + // DKIM SIGN + if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { + $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); + $this->message->attachSigner($signer); + } + + if (! empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); // Or to use the Echo Logger diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/EmailLexer.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/EmailParser.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/EmailValidator.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/AtextAfterCFWS.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFAtTheEnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFX2.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFX2.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRLFX2.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRLFX2.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRNoLF.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRNoLF.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CRNoLF.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CRNoLF.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CharNotAllowed.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/CommaInDomain.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveAt.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ConsecutiveDot.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtStart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtStart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/DotAtStart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/DotAtStart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDTEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingDomainLiteralClose.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDNSRecord.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoLocalPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedComment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnclosedQuotedString.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/UnopenedComment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Parser/DomainPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Parser/LocalPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Parser/Parser.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/DNSCheckValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/EmailValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/RFCWarnings.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Error/SpoofEmail.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/Exception/EmptyValidationList.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleErrors.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/MultipleValidationWithAnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/NoRFCWarningsValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/RFCValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/SpoofCheckValidation.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/AddressLiteral.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSNearAt.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/CFWSWithFWS.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Comment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/Comment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Comment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DeprecatedComment.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainLiteral.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/DomainTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/EmailTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6BadChar.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonEnd.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6ColonStart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6Deprecated.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6DoubleColon.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6GroupCount.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/IPV6MaxGroups.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LabelTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/NoDNSMXRecord.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/ObsoleteDTEXT.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedPart.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedPart.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedPart.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedString.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/QuotedString.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/QuotedString.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/TLD.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/TLD.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/TLD.php diff --git a/htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php b/htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php similarity index 100% rename from htdocs/includes/egulias/email-validator/EmailValidator/Warning/Warning.php rename to htdocs/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php diff --git a/htdocs/includes/egulias/email-validator/LICENSE b/htdocs/includes/swiftmailer/egulias/email-validator/LICENSE similarity index 100% rename from htdocs/includes/egulias/email-validator/LICENSE rename to htdocs/includes/swiftmailer/egulias/email-validator/LICENSE diff --git a/htdocs/includes/egulias/email-validator/README.md b/htdocs/includes/swiftmailer/egulias/email-validator/README.md similarity index 100% rename from htdocs/includes/egulias/email-validator/README.md rename to htdocs/includes/swiftmailer/egulias/email-validator/README.md diff --git a/htdocs/includes/lexer/LICENSE b/htdocs/includes/swiftmailer/lexer/LICENSE similarity index 100% rename from htdocs/includes/lexer/LICENSE rename to htdocs/includes/swiftmailer/lexer/LICENSE diff --git a/htdocs/includes/lexer/README.md b/htdocs/includes/swiftmailer/lexer/README.md similarity index 100% rename from htdocs/includes/lexer/README.md rename to htdocs/includes/swiftmailer/lexer/README.md diff --git a/htdocs/includes/lexer/composer.json b/htdocs/includes/swiftmailer/lexer/composer.json similarity index 100% rename from htdocs/includes/lexer/composer.json rename to htdocs/includes/swiftmailer/lexer/composer.json diff --git a/htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php b/htdocs/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php similarity index 100% rename from htdocs/includes/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php rename to htdocs/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang index 0953014aa91..29c5381af80 100644 --- a/htdocs/langs/fr_FR/admin.lang +++ b/htdocs/langs/fr_FR/admin.lang @@ -277,6 +277,10 @@ MAIN_MAIL_SMTPS_ID=Identifiant d'authentification SMTP si authentification SMTP MAIN_MAIL_SMTPS_PW=Mot de passe d'authentification SMTP si authentification SMTP requise MAIN_MAIL_EMAIL_TLS= Utilisation du chiffrement TLS (SSL) MAIN_MAIL_EMAIL_STARTTLS= Utiliser le cryptage TTS (STARTTLS) +MAIN_MAIL_EMAIL_DKIM_ENABLED= Utiliser la signature DKIM +MAIN_MAIL_EMAIL_DKIM_DOMAIN=Domaine DKIM +MAIN_MAIL_EMAIL_DKIM_SELECTOR=Sélecteur de clé DKIM +MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY=Clé privée RSA DKIM MAIN_DISABLE_ALL_SMS=Désactiver globalement tout envoi de SMS (pour mode test ou démos) MAIN_SMS_SENDMODE=Méthode d'envoi des SMS MAIN_MAIL_SMS_FROM=Numéro de téléphone par défaut pour l'envoi des SMS From 4f9bb336009b16bf9d827138631cab35c81ba2ea Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 14 Feb 2018 10:47:10 +0100 Subject: [PATCH 04/91] NEW: supplier credit notes: convert to usable absolute discount + link/unlink to supplier invoice + create supplier credit note from excess paid --- htdocs/compta/facture/card.php | 8 +- htdocs/core/class/commoninvoice.class.php | 6 - htdocs/core/class/commonobject.class.php | 2 +- htdocs/core/class/discount.class.php | 64 +++- htdocs/core/class/html.form.class.php | 49 ++- htdocs/core/lib/doc.lib.php | 2 +- htdocs/core/lib/pdf.lib.php | 2 +- htdocs/core/tpl/objectline_view.tpl.php | 4 +- .../fourn/class/fournisseur.facture.class.php | 100 +++++ htdocs/fourn/facture/card.php | 343 +++++++++++++++++- htdocs/societe/class/societe.class.php | 5 +- htdocs/societe/consumption.php | 4 +- 12 files changed, 519 insertions(+), 70 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 01ea8d93de3..df5e78b8712 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2989,11 +2989,11 @@ else if ($id > 0 || ! empty($ref)) $resteapayeraffiche = $resteapayer; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this - $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filterabsolutediscount = "fk_facture IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + $filterabsolutediscount = "fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 9d7ae9d0998..c629c6021b4 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -180,12 +180,6 @@ abstract class CommonInvoice extends CommonObject */ function getSumCreditNotesUsed($multicurrency=0) { - 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); diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 0dd9a245136..a320d102c4e 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -3955,7 +3955,7 @@ abstract class CommonObject $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } + } // TODO handle (EXCESS PAID) else { $this->tpl['description'] = dol_trunc($line->desc,60); diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index 37dedea8b6b..c8aa11996b6 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -60,16 +60,17 @@ class DiscountAbsolute /** * Load object from database into memory * - * @param int $rowid id discount to load - * @param int $fk_facture_source fk_facture_source - * @return int <0 if KO, =0 if not found, >0 if OK + * @param int $rowid id discount to load + * @param int $fk_facture_source fk_facture_source + * @param int $fk_invoice_supplier_source fk_invoice_supplier_source + * @return int <0 if KO, =0 if not found, >0 if OK */ - function fetch($rowid, $fk_facture_source=0) + function fetch($rowid, $fk_facture_source=0, $fk_invoice_supplier_source=0) { global $conf; // Check parameters - if (! $rowid && ! $fk_facture_source) + if (! $rowid && ! $fk_facture_source && ! $fk_invoice_supplier_source) { $this->error='ErrorBadParameters'; return -1; @@ -79,14 +80,16 @@ class DiscountAbsolute $sql.= " sr.fk_user,"; $sql.= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,"; $sql.= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; - $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.description,"; + $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.fk_invoice_supplier_line, sr.fk_invoice_supplier, sr.fk_invoice_supplier_source, sr.description,"; $sql.= " sr.datec,"; - $sql.= " f.facnumber as ref_facture_source"; + $sql.= " f.facnumber as ref_facture_source, fsup.facnumber as ref_invoice_supplier_source"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid"; $sql.= " WHERE sr.entity = " . $conf->entity; if ($rowid) $sql.= " AND sr.rowid=".$rowid; if ($fk_facture_source) $sql.= " AND sr.fk_facture_source=".$fk_facture_source; + if ($fk_invoice_supplier_source) $sql.= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -113,6 +116,10 @@ class DiscountAbsolute $this->fk_facture = $obj->fk_facture; $this->fk_facture_source = $obj->fk_facture_source; // Id avoir source $this->ref_facture_source = $obj->ref_facture_source; // Ref avoir source + $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line; + $this->fk_invoice_supplier = $obj->fk_invoice_supplier; + $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id avoir source + $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref avoir source $this->description = $obj->description; $this->datec = $this->db->jdate($obj->datec); @@ -161,11 +168,12 @@ class DiscountAbsolute $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; $sql.= " (entity, datec, fk_soc, fk_user, description,"; $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,"; - $sql.= " fk_facture_source"; + $sql.= " fk_facture_source, fk_invoice_supplier_source"; $sql.= ")"; $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',"; $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.","; - $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null"); + $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").","; + $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); @@ -194,7 +202,7 @@ class DiscountAbsolute global $conf, $langs; // Check if we can remove the discount - if ($this->fk_facture_source) + if ($this->fk_facture_source) // TODO check { $sql="SELECT COUNT(rowid) as nb"; $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; @@ -278,9 +286,10 @@ class DiscountAbsolute * * @param int $rowidline Invoice line id (To use discount into invoice lines) * @param int $rowidinvoice Invoice id (To use discount as a credit note to reduc payment of invoice) + * @param string $mode 'supplier' to link to supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function link_to_invoice($rowidline,$rowidinvoice) + function link_to_invoice($rowidline,$rowidinvoice,$mode='customer') { // Check parameters if (! $rowidline && ! $rowidinvoice) @@ -295,16 +304,26 @@ class DiscountAbsolute } $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if ($rowidline) $sql.=" SET fk_facture_line = ".$rowidline; - if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; + if($mode == 'supplier') { + if ($rowidline) $sql.=" SET fk_invoice_supplier_line = ".$rowidline; + if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice; + } else { + if ($rowidline) $sql.=" SET fk_facture_line = ".$rowidline; + if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; + } $sql.=" WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->fk_facture_line=$rowidline; - $this->fk_facture=$rowidinvoice; + if($mode == 'supplier') { + $this->fk_invoice_supplier_line=$rowidline; + $this->fk_invoice_supplier=$rowidinvoice; + } else { + $this->fk_facture_line=$rowidline; + $this->fk_facture=$rowidinvoice; + } return 1; } else @@ -319,12 +338,17 @@ class DiscountAbsolute * Link the discount to a particular invoice line or a particular invoice. * Do not call this if discount is linked to a reconcialiated invoice * + * @param string $mode 'supplier' to unlink a supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function unlink_invoice() + function unlink_invoice($mode = 'customer') { $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; + if($mode = 'supplier') { + $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; + } else { + $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; + } $sql.=" WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); @@ -359,8 +383,8 @@ class DiscountAbsolute //$sql = "SELECT rc.amount_ttc as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.entity = " . $conf->entity; - if ($mode != 'supplier') $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available - else $sql.= " AND (rc.fk_suppler_invoice IS NULL AND rc.fk_supplier_invoice IS NULL)"; // Available + if ($mode == 'supplier') $sql.= " AND (rc.fk_facture_source IS NULL AND rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available + else $sql.= " AND (rc.fk_invoice_supplier_source IS NULL AND rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id; if (is_object($user)) $sql.= " AND rc.fk_user = ".$user->id; if ($filter) $sql.=' AND ('.$filter.')'; @@ -452,7 +476,7 @@ class DiscountAbsolute $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; - $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received + $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess paid } else { diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 4e8f67d6552..8a1cc6ac33c 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -1236,6 +1236,7 @@ class Form if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); + // TODO handle (EXCESS PAID) $selectstring=''; if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; @@ -4219,9 +4220,10 @@ class Form * @param int $maxvalue Max value for lines that can be selected * @param string $more More string to add * @param int $hidelist 1=Hide list + * @param string $mode 'supplier' to list available discounts for suppliers, 'customer' instead * @return void */ - function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0) + function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $mode='customer') { global $conf,$langs; if ($htmlname != "none") @@ -4230,28 +4232,51 @@ class Form print ''; print ''; print '
'; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - { - if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - else - { - if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if($mode == 'supplier') { + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + { + if (! $filter || $filter=="fk_invoice_supplier IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + else + { + if (! $filter || $filter=="fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + } else { + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + { + if (! $filter || $filter=="fk_facture IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + else + { + if (! $filter || $filter=="fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } } if (empty($hidelist)) print ': '; print '
'; if (empty($hidelist)) { print '
'; - $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles + if($mode == 'supplier') { + $newfilter = 'fk_facture_source IS NULL AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Exclude customer discounts + $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available + } else { + $newfilter = 'fk_invoice_supplier_source IS NULL AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Exclude supplier discounts + $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available + } if ($filter) $newfilter.=' AND ('.$filter.')'; $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); if ($nbqualifiedlines > 0) { print '   '; } print '
'; diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 99e576ad057..20eaa9a71f7 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -88,7 +88,7 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } + } // TODO handle (EXCESS PAID) else { if ($idprod) diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 377f2215b6d..0fb649506cb 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -1251,7 +1251,7 @@ function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issuppl $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } + } // TODO handle (EXCESS PAID) else { if ($idprod) diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index 8d5b13ece7c..bc5d950ab8e 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -72,7 +72,7 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($line->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -100,7 +100,7 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } + } // TODO handle (EXCESS PAID) else { echo ($txt?' - ':'').dol_htmlentitiesbr($line->description); diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 444eb5d200a..b23c9af5fce 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -897,6 +897,106 @@ class FactureFournisseur extends CommonInvoice } } + /** + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) + * + * @param int $idremise Id of absolute discount + * @return int >0 if OK, <0 if KO + */ + function insert_discount($idremise) + { + global $langs; + + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + + $this->db->begin(); + + $remise=new DiscountAbsolute($this->db); + $result=$remise->fetch($idremise); + + if ($result > 0) + { + if ($remise->fk_invoice_supplier) // Protection against multiple submission + { + $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->db->rollback(); + return -5; + } + + $facligne=new SupplierInvoiceLine($this->db); + $facligne->fk_facture=$this->id; + $facligne->fk_remise_except=$remise->id; + $facligne->desc=$remise->description; // Description ligne + $facligne->vat_src_code=$remise->vat_src_code; + $facligne->tva_tx=$remise->tva_tx; + $facligne->subprice = -$remise->amount_ht; + $facligne->fk_product=0; // Id produit predefini + $facligne->qty=1; + $facligne->remise_percent=0; + $facligne->rang=-1; + $facligne->info_bits=2; + + // Get buy/cost price of invoice that is source of discount + if ($remise->fk_invoice_supplier_source > 0) + { + $srcinvoice=new FactureFournisseur($this->db); + $srcinvoice->fetch($remise->fk_invoice_supplier_source); + $totalcostpriceofinvoice=0; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin=new FormMargin($this->db); + $arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false); + $facligne->pa_ht = $arraytmp['pa_total']; + } + + $facligne->total_ht = -$remise->amount_ht; + $facligne->total_tva = -$remise->amount_tva; + $facligne->total_ttc = -$remise->amount_ttc; + + $facligne->multicurrency_subprice = -$remise->multicurrency_subprice; + $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht; + $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva; + $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; + + $lineid=$facligne->insert(); + if ($lineid > 0) + { + $result=$this->update_price(1); + if ($result > 0) + { + // Create link between discount and invoice line + $result=$remise->link_to_invoice($lineid,0,'supplier'); + if ($result < 0) + { + $this->error=$remise->error; + $this->db->rollback(); + return -4; + } + + $this->db->commit(); + return 1; + } + else + { + $this->error=$facligne->error; + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$facligne->error; + $this->db->rollback(); + return -2; + } + } + else + { + $this->db->rollback(); + return -3; + } + } + /** * Delete invoice from database diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 761d5d591e3..a397d40d147 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -36,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -265,6 +266,14 @@ if (empty($reshook)) $action=''; } } + + // Delete link of credit note to invoice + else if ($action == 'unlinkdiscount' && $user->rights->facture->creer) + { + $discount = new DiscountAbsolute($db); + $result = $discount->fetch(GETPOST("discountid")); + $discount->unlink_invoice('supplier'); + } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { @@ -376,6 +385,186 @@ if (empty($reshook)) $result=$object->update($user); if ($result < 0) dol_print_error($db,$object->error); } + elseif ($action == "setabsolutediscount" && $user->rights->facture->creer) + { + // POST[remise_id] or POST[remise_id_for_payment] + + // We use the credit to reduce amount of invoice + if (! empty($_POST["remise_id"])) { + $ret = $object->fetch($id); + if ($ret > 0) { + $result = $object->insert_discount($_POST["remise_id"]); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + dol_print_error($db, $object->error); + } + } + // We use the credit to reduce remain to pay + if (! empty($_POST["remise_id_for_payment"])) + { + require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; + $discount = new DiscountAbsolute($db); + $discount->fetch($_POST["remise_id_for_payment"]); + + //var_dump($object->getRemainToPay(0)); + //var_dump($discount->amount_ttc);exit; + if ($discount->amount_ttc > $object->getRemainToPay(0)) + { + // TODO Split the discount in 2 automatically + $error++; + setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); + } + + if (! $error) + { + $result = $discount->link_to_invoice(0, $id, 'supplier'); + if ($result < 0) { + setEventMessages($discount->error, $discount->errors, 'errors'); + } + } + } + + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $ret = $object->fetch($id); // Reload to get new records + + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + } + } + // Convertir en reduc + else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); + //$object->fetch_lines(); // Already done into fetch + + // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) + $discountcheck=new DiscountAbsolute($db); + $result=$discountcheck->fetch(0,0,$object->id); + + $canconvert=0; + if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert=1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) $canconvert=1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + if ($canconvert) + { + $db->begin(); + + $amount_ht = $amount_tva = $amount_ttc = array(); + + // Loop on each vat rate + $i = 0; + foreach ($object->lines as $line) + { + if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 + { // no need to create discount if amount is null + $amount_ht[$line->tva_tx] += $line->total_ht; + $amount_tva[$line->tva_tx] += $line->total_tva; + $amount_ttc[$line->tva_tx] += $line->total_ttc; + $i ++; + } + } + + // Insert one discount by VAT rate category + $discount = new DiscountAbsolute($db); + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $discount->description = '(CREDIT_NOTE)'; + elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) + $discount->description = '(DEPOSIT)'; + elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) + $discount->description = '(EXCESS PAID)'; + else { + setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); + } + $discount->fk_soc = $object->socid; + $discount->fk_invoice_supplier_source = $object->id; + + $error = 0; + + if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) + { + // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT + + $sql = 'SELECT SUM(pf.amount) as total_paiements'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; + $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; + $sql.= ' AND pf.fk_paiementfourn = p.rowid'; + $sql.= ' AND p.entity IN (' . getEntity('facture').')'; + $sql.= ' ORDER BY p.datep, p.tms'; + + $resql = $db->query($sql); + if (! $resql) dol_print_error($db); + + $res = $db->fetch_object($resql); + $total_paiements = $res->total_paiements; + + $discount->amount_ht = $discount->amount_ttc = $total_paiements - $object->total_ttc; + $discount->amount_tva = 0; + $discount->tva_tx = 0; + + $result = $discount->create($user); + if ($result < 0) + { + $error++; + } + + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) + { + foreach ($amount_ht as $tva_tx => $xxx) + { + $discount->amount_ht = abs($amount_ht[$tva_tx]); + $discount->amount_tva = abs($amount_tva[$tva_tx]); + $discount->amount_ttc = abs($amount_ttc[$tva_tx]); + $discount->tva_tx = abs($tva_tx); + + $result = $discount->create($user); + if ($result < 0) + { + $error++; + break; + } + } + + } + + if (empty($error)) + { + if($object->type != FactureFournisseur::TYPE_DEPOSIT) { + // Classe facture + $result = $object->set_paid($user); + if ($result >= 0) + { + $db->commit(); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } + } else { + $db->commit(); + } + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $db->rollback(); + } + } + } + // Delete payment elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) @@ -464,6 +653,7 @@ if (empty($reshook)) // Credit note invoice if ($_POST['type'] == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sourceinvoice = GETPOST('fac_avoir','int'); if (! ($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) { @@ -519,6 +709,10 @@ if (empty($reshook)) $id = $object->create($user); + if($id <= 0) { + $error++; + } + if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) { $facture_source = new FactureFournisseur($db); // fetch origin object @@ -677,7 +871,7 @@ if (empty($reshook)) } $num=count($lines); - for ($i = 0; $i < $num; $i++) + for ($i = 0; $i < $num; $i++) // TODO handle subprice < 0 { $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); @@ -1485,6 +1679,7 @@ if ($action == 'create') if ($societe->id > 0) { + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 'supplier'); print $societe->getNomUrl(1); print ''; } @@ -1717,22 +1912,22 @@ if ($action == 'create') print ''; - if ($socid > 0) + if ($societe->id > 0) { // Discounts for third party print '' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); else print $langs->trans("CompanyHasNoRelativeDiscount"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); else print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; print '.'; print ''; } @@ -1944,6 +2139,18 @@ else } $resteapayeraffiche = $resteapayer; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this + $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; + } + + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 'supplier'); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 'supplier'); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); /* * View card @@ -1953,6 +2160,17 @@ else dol_fiche_head($head, 'card', $titre, -1, 'bill'); + $formconfirm = ''; + + // Confirmation de la conversion de l'avoir en reduc + if ($action == 'converttoreduc') { + if($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessReceived'; // TODO translation trop-perçu => trop-payé + elseif($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; + elseif($object->type == FactureFournisseur::TYPE_DEPOSIT) $type_fac = 'Deposit'; + $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac))); // TODO translation client => fournisseur + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); + } + // Clone confirmation if ($action == 'clone') { @@ -2189,7 +2407,88 @@ else print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } print ''; - + + // Relative and absolute discounts + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; + + print '' . $langs->trans('Discounts'); + print ''; + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + // print ' ('.$addrelativediscount.')'; + + // Is there is commercial discount or down payment available ? + if ($absolute_discount > 0) { + print '. '; + if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + if ($object->statut == 0) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '. '; + } else { + if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '
' . $text . '.
'; + } else { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + $text2 = $langs->trans("AbsoluteDiscountUse"); + print $form->textwithpicto($text, $text2); + } + } + } else { + // Discount available of type fixed amount (not credit note) + print '
'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 'supplier'); + } + } else { + if ($absolute_creditnote > 0) // If not, link will be added later + { + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) + print ' (' . $addabsolutediscount . ')
'; + else + print '. '; + } else + print '. '; + } + // Is there credit notes availables ? + if ($absolute_creditnote > 0) + { + // If validated, we show link "add credit note to payment" + if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); + print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); + } else { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; + } + } else { // We can add a credit note on a down payment or standard invoice or situation invoice + // There is credit notes discounts available + if (! $absolute_discount) print '
'; + // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 'supplier'); + $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 'supplier'); // We allow credit note even if amount is higher + } + } + if (! $absolute_discount && ! $absolute_creditnote) { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) + print ' (' . $addabsolutediscount . ')
'; + else + print '. '; + } + // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) + // { + // if (! $absolute_discount && ! $absolute_creditnote) print '
'; + // print '   -   '; + // print $addabsolutediscount; + // print '   -   '.$addcreditnote; // We disbale link to credit note + // } + print ''; + // Label print ''; print ''.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).''; @@ -2539,18 +2838,19 @@ else print $langs->trans('AlreadyPaid'); print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' '; - $resteapayer = $object->total_ttc - $totalpaye; + //$resteapayer = $object->total_ttc - $totalpaye; $resteapayeraffiche = $resteapayer; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; // Loop on each credit note or deposit amount applied $creditnoteamount = 0; $depositamount = 0; - /* + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except_supplier as re"; - $sql .= " WHERE fk_facture = " . $object->id; + $sql .= " re.description, re.fk_invoice_supplier_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = " . $object->id; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -2558,7 +2858,7 @@ else $invoice = new FactureFournisseur($db); while ($i < $num) { $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_facture_source); + $invoice->fetch($obj->fk_invoice_supplier_source); print ''; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) print $langs->trans("CreditNote") . ' '; @@ -2568,7 +2868,7 @@ else print ' :'; print '' . price($obj->amount_ttc) . ''; print ''; - print 'rowid . '">' . img_delete() . ''; + print 'rowid . '">' . img_delete() . ''; // TODO unlinkdiscount print ''; $i ++; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) @@ -2579,7 +2879,7 @@ else } else { dol_print_error($db); } - */ + // Paye partiellement 'escompte' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { @@ -2627,7 +2927,7 @@ else else print $langs->trans('ExcessReceived'); print ' :'; - print '' . price($resteapayeraffiche) . ''; + print '' . price($resteapayeraffiche) . ''; print ' '; } else // Credit note @@ -2649,7 +2949,7 @@ else else print $langs->trans('ExcessPaydBack'); print ' :'; - print '' . price($sign * $resteapayeraffiche) . ''; + print '' . price($sign * $resteapayeraffiche) . ''; print ' '; // Sold credit note @@ -2792,7 +3092,7 @@ else } // Reverse back money or convert to reduction - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { // For credit note only if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { @@ -2806,6 +3106,11 @@ else } } + // For standard invoice with excess paid + if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->facture->creer && empty($discount->id)) + { + print ''; // TODO translation : trop-perçu => trop payé + } // For credit note if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() == 0) { print ''; diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index b9b431f3e3e..4adfae72258 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1718,14 +1718,15 @@ class Societe extends CommonObject * @param User $user Filtre sur un user auteur des remises * @param string $filter Filtre autre * @param integer $maxvalue Filter on max value for discount + * @param string $mode 'supplier' to get available discounts for suppliers, 'customer' instead * @return int <0 if KO, Credit note amount otherwise */ - function getAvailableDiscounts($user='',$filter='',$maxvalue=0) + function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$mode='customer') { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discountstatic=new DiscountAbsolute($this->db); - $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue); + $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$mode); if ($result >= 0) { return $result; diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index ffb4cac77fa..1420562da19 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -490,7 +490,7 @@ if ($sql_select) $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($objp->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -517,7 +517,7 @@ if ($sql_select) echo ($txt?' - ':'').$langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; - } + } // TODO handle (EXCESS PAID) else { echo ($txt?' - ':'').dol_htmlentitiesbr($objp->description); From daca27b2ed8e8a2924105de16b32f7f8d894d117 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 14 Feb 2018 18:02:40 +0100 Subject: [PATCH 05/91] NEW: supplier credit notes: split display in thirdparty discount page + fixes + refactoring --- htdocs/comm/card.php | 2 +- htdocs/comm/remx.php | 372 +++++++++++++++++- htdocs/core/class/discount.class.php | 93 ++++- htdocs/core/class/html.form.class.php | 15 +- .../fourn/class/fournisseur.facture.class.php | 2 +- htdocs/fourn/facture/card.php | 21 +- .../install/mysql/migration/7.0.0-8.0.0.sql | 1 + .../tables/llx_societe_remise_except.key.sql | 1 + .../tables/llx_societe_remise_except.sql | 3 +- htdocs/societe/class/societe.class.php | 25 +- 10 files changed, 476 insertions(+), 59 deletions(-) diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 81443f04d62..d732a10a347 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -392,7 +392,7 @@ if ($object->id > 0) print ''; print ''; print ''; - $amount_discount=$object->getAvailableDiscounts(); + $amount_discount=$object->getAvailableDiscounts(); // TODO adapt to supplier discounts if ($amount_discount < 0) dol_print_error($db,$object->error); if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; //else print $langs->trans("DiscountNone"); diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 0127b8f15be..072baa675fb 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -26,6 +26,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $langs->load("orders"); @@ -143,6 +144,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) $amount_ht=GETPOST('amount_ht'); $desc=GETPOST('desc','alpha'); $tva_tx=GETPOST('tva_tx','alpha'); + $discount_type=! empty($_POST['discount_type'])?GETPOST('discount_type','alpha'):0; if (price2num($amount_ht) > 0) { @@ -157,7 +159,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) { $soc = new Societe($db); $soc->fetch($id); - $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx); + $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx,$discount_type); if ($discountid > 0) { @@ -215,6 +217,7 @@ if (GETPOST('action','aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes') $form=new Form($db); $facturestatic=new Facture($db); +$facturefournstatic=new FactureFournisseur($db); llxHeader('',$langs->trans("GlobalDiscount")); @@ -244,12 +247,13 @@ if ($socid > 0) print '
'; print ''; - // Calcul avoirs en cours + // Calcul avoirs client en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.fk_soc = " . $object->id; $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 0"; // Exclude supplier discounts $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; $sql.= " GROUP BY rc.fk_user"; $resql=$db->query($sql); @@ -264,14 +268,47 @@ if ($socid > 0) dol_print_error($db); } - print ''; + print ''; // TODO adapt text print ''; if (! empty($user->fk_soc)) // No need to show this for external users { - print ''; + print ''; // TODO adapt text print ''; } + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + // Calcul avoirs fournisseur en cours + $remise_all=$remise_user=0; + $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 1"; // Exclude customer discounts + $sql.= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; + $sql.= " GROUP BY rc.fk_user"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $remise_all+=$obj->amount; + if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + } + else + { + dol_print_error($db); + } + + print ''; // TODO adapt text + print ''; + + if (! empty($user->fk_soc)) // No need to show this for external users + { + print ''; // TODO adapt text + print ''; + } + } + print '
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").'
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'; print '
'; @@ -284,6 +321,11 @@ if ($socid > 0) print '
'; print ''; + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print ''; + print ''; + } print ''; print ''; @@ -321,9 +363,18 @@ if ($socid > 0) print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1); } + /* - * Liste remises fixes restant en cours (= liees a aucune facture ni ligne de facture) + * Liste remises fixes client restant en cours (= liees a aucune facture ni ligne de facture) */ + + print load_fiche_titre($langs->trans("DiscountStillRemaining")); + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print '
'; + print '
'; + } + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; $sql.= " rc.datec as dc, rc.description,"; $sql.= " rc.fk_facture_source,"; @@ -334,13 +385,16 @@ if ($socid > 0) $sql.= " WHERE rc.fk_soc = " . $object->id; $sql.= " AND rc.entity = " . $conf->entity; $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; $sql.= " ORDER BY rc.datec DESC"; $resql=$db->query($sql); if ($resql) { - print load_fiche_titre($langs->trans("DiscountStillRemaining")); + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + } print '
'.$langs->trans('DiscountType').' '; + print '
'.$langs->trans("AmountHT").''; print ' '.$langs->trans("Currency".$conf->currency).'
'; print ''; print ''; // Need 120+ for format with AM/PM @@ -449,11 +503,157 @@ if ($socid > 0) dol_print_error($db); } + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print ''; // class="fichehalfleft" + print '
'; + print '
'; + + /* + * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture) + */ + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description,"; + $sql.= " rc.fk_invoice_supplier_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " fa.ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print '
'.$langs->trans("Date").'
'; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $showconfirminfo=array(); + + $i = 0; + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS PAID\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + if ($user->rights->societe->creer || $user->rights->facture->creer) + { + print ''; + } + else print ''; + print ''; + + if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + { + $showconfirminfo['rowid']=$obj->rowid; + $showconfirminfo['amount_ttc']=$obj->amount_ttc; + } + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); // TODO translate ExcessPaid + print ''; + print $obj->description; + print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print '   '; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print ' 
'.$langs->trans("None").'
"; + + if (count($showconfirminfo)) + { + $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); + $amount2=($showconfirminfo['amount_ttc']-$amount1); + $formquestion=array( + 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), + array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), + array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') + ); + $langs->load("dict"); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + } + } + else + { + dol_print_error($db); + } + + print ''; // class="ficheaddleft" + print ''; // class="fichehalfright" + print ''; // class="fichecenter" + } + print '
'; /* * List discount consumed (=liees a une ligne de facture ou facture) */ + + print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print '
'; + print '
'; + } // Remises liees a lignes de factures $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; @@ -471,6 +671,7 @@ if ($socid > 0) $sql.= " AND rc.fk_facture_line = fc.rowid"; $sql.= " AND fc.fk_facture = f.rowid"; $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts $sql.= " ORDER BY dc DESC"; //$sql.= " UNION "; // Remises liees a factures @@ -487,7 +688,7 @@ if ($socid > 0) $sql2.= " WHERE rc.fk_soc =". $object->id; $sql2.= " AND rc.fk_facture = f.rowid"; $sql2.= " AND rc.fk_user = u.rowid"; - + $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts $sql2.= " ORDER BY dc DESC"; $resql=$db->query($sql); @@ -495,7 +696,9 @@ if ($socid > 0) if ($resql) $resql2=$db->query($sql2); if ($resql2) { - print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + } print ''; print ''; print ''; // Need 120+ for format with AM/PM @@ -598,6 +801,159 @@ if ($socid > 0) dol_print_error($db); } + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + print ''; // class="fichehalfleft" + print '
'; + print '
'; + + // Remises liees a lignes de factures + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql.= " rc.fk_invoice_supplier_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " f.rowid, f.ref as facnumber,"; + $sql.= " fa.ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " , ".MAIN_DB_PREFIX."user as u"; + $sql.= " , ".MAIN_DB_PREFIX."facture_fourn_det as fc"; + $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc =". $object->id; + $sql.= " AND rc.fk_invoice_supplier_line = fc.rowid"; + $sql.= " AND fc.fk_facture_fourn = f.rowid"; + $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql.= " ORDER BY dc DESC"; + //$sql.= " UNION "; + // Remises liees a factures + $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql2.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql2.= " rc.fk_invoice_supplier_source,"; + $sql2.= " u.login, u.rowid as user_id,"; + $sql2.= " f.rowid, f.ref as facnumber,"; + $sql2.= " fa.ref, fa.type as type"; + $sql2.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql2.= " , ".MAIN_DB_PREFIX."user as u"; + $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql2.= " WHERE rc.fk_soc =". $object->id; + $sql2.= " AND rc.fk_invoice_supplier = f.rowid"; + $sql2.= " AND rc.fk_user = u.rowid"; + $sql2.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql2.= " ORDER BY dc DESC"; + + $resql=$db->query($sql); + $resql2=null; + if ($resql) $resql2=$db->query($sql2); + if ($resql2) + { + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print '
'.$langs->trans("Date").'
'; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $tab_sqlobj=array(); + $tab_sqlobjOrder=array(); + $num = $db->num_rows($resql); + if ($num > 0) + { + for ($i = 0;$i < $num; $i++) + { + $sqlobj = $db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + } + } + $db->free($resql); + + $num = $db->num_rows($resql2); + for ($i = 0;$i < $num;$i++) + { + $sqlobj = $db->fetch_object($resql2); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + } + $db->free($resql2); + array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); + + $num = count($tab_sqlobj); + if ($num > 0) + { + $i = 0 ; + while ($i < $num ) + { + $obj = array_shift($tab_sqlobj); + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS PAID\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; // TODO adapt to supplier invoice of use getNomUrl + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("Invoice"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + print $obj->description; + print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; // TODO getNomUrl ? + print ' 
'.$langs->trans("None").'
"; + } + else + { + dol_print_error($db); + } + + print '
'; // class="ficheaddleft" + print '
'; // class="fichehalfright" + print ''; // class="fichecenter" + } } llxFooter(); diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index c8aa11996b6..b62e35c183e 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -34,6 +34,7 @@ class DiscountAbsolute public $id; // Id discount public $fk_soc; + public $discount_type; // 0 => customer discount, 1 => supplier discount public $amount_ht; // public $amount_tva; // public $amount_ttc; // @@ -76,7 +77,7 @@ class DiscountAbsolute return -1; } - $sql = "SELECT sr.rowid, sr.fk_soc,"; + $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,"; $sql.= " sr.fk_user,"; $sql.= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,"; $sql.= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; @@ -101,6 +102,7 @@ class DiscountAbsolute $this->id = $obj->rowid; $this->fk_soc = $obj->fk_soc; + $this->discount_type = $obj->discount_type; $this->amount_ht = $obj->amount_ht; $this->amount_tva = $obj->amount_tva; @@ -166,11 +168,11 @@ class DiscountAbsolute // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; - $sql.= " (entity, datec, fk_soc, fk_user, description,"; + $sql.= " (entity, datec, fk_soc, discount_type, fk_user, description,"; $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,"; $sql.= " fk_facture_source, fk_invoice_supplier_source"; $sql.= ")"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',"; + $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type)?0:intval($this->discount_type)).", ".$user->id.", '".$this->db->escape($this->description)."',"; $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.","; $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").","; $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null"); @@ -202,7 +204,7 @@ class DiscountAbsolute global $conf, $langs; // Check if we can remove the discount - if ($this->fk_facture_source) // TODO check + if ($this->fk_facture_source) { $sql="SELECT COUNT(rowid) as nb"; $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; @@ -228,15 +230,46 @@ class DiscountAbsolute return -1; } } + + // Check if we can remove the discount + if ($this->fk_invoice_supplier_source) + { + $sql="SELECT COUNT(rowid) as nb"; + $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; + $sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount + $sql.=" OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit + $sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; + //$sql.=" AND rowid != ".$this->id; + + dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; + return -2; + } + } + else + { + dol_print_error($this->db); + return -1; + } + } $this->db->begin(); // Delete but only if not used $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except "; if ($this->fk_facture_source) $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie + elseif ($this->fk_invoice_supplier_source) $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie else $sql.= " WHERE rowid = ".$this->id; // Delete only line $sql.= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount $sql.= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit + $sql.= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount + $sql.= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); $result=$this->db->query($sql); @@ -263,6 +296,26 @@ class DiscountAbsolute return -1; } } + elseif($this->fk_invoice_supplier_source) { + + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; + $sql.=" set paye=0, fk_statut=1"; + $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source; + + dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } else { $this->db->commit(); @@ -286,10 +339,9 @@ class DiscountAbsolute * * @param int $rowidline Invoice line id (To use discount into invoice lines) * @param int $rowidinvoice Invoice id (To use discount as a credit note to reduc payment of invoice) - * @param string $mode 'supplier' to link to supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function link_to_invoice($rowidline,$rowidinvoice,$mode='customer') + function link_to_invoice($rowidline,$rowidinvoice) { // Check parameters if (! $rowidline && ! $rowidinvoice) @@ -304,7 +356,7 @@ class DiscountAbsolute } $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if($mode == 'supplier') { + if(! empty($this->discount_type)) { if ($rowidline) $sql.=" SET fk_invoice_supplier_line = ".$rowidline; if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice; } else { @@ -317,7 +369,7 @@ class DiscountAbsolute $resql = $this->db->query($sql); if ($resql) { - if($mode == 'supplier') { + if(! empty($this->discount_type)) { $this->fk_invoice_supplier_line=$rowidline; $this->fk_invoice_supplier=$rowidinvoice; } else { @@ -338,13 +390,12 @@ class DiscountAbsolute * Link the discount to a particular invoice line or a particular invoice. * Do not call this if discount is linked to a reconcialiated invoice * - * @param string $mode 'supplier' to unlink a supplier invoice, 'customer' instead * @return int <0 if KO, >0 if OK */ - function unlink_invoice($mode = 'customer') + function unlink_invoice() { $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if($mode = 'supplier') { + if(! empty($this->discount_type)) { $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; } else { $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; @@ -368,14 +419,14 @@ class DiscountAbsolute /** * Return amount (with tax) of discounts currently available for a company, user or other criteria * - * @param Societe $company Object third party for filter - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param int $maxvalue Filter on max value for discount - * @param string $mode 'customer' = discounts the customer has, 'supplier' = discount i have at this supplier + * @param Societe $company Object third party for filter + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param int $maxvalue Filter on max value for discount + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, amount otherwise */ - function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $mode='customer') + function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $discount_type=0) { global $conf; @@ -383,8 +434,12 @@ class DiscountAbsolute //$sql = "SELECT rc.amount_ttc as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.entity = " . $conf->entity; - if ($mode == 'supplier') $sql.= " AND (rc.fk_facture_source IS NULL AND rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available - else $sql.= " AND (rc.fk_invoice_supplier_source IS NULL AND rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available + $sql.= " AND rc.discount_type=".intval($discount_type); + if (! empty($discount_type)) { + $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier + } else { + $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer + } if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id; if (is_object($user)) $sql.= " AND rc.fk_user = ".$user->id; if ($filter) $sql.=' AND ('.$filter.')'; diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 8a1cc6ac33c..e6ab69dff95 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4220,10 +4220,10 @@ class Form * @param int $maxvalue Max value for lines that can be selected * @param string $more More string to add * @param int $hidelist 1=Hide list - * @param string $mode 'supplier' to list available discounts for suppliers, 'customer' instead + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return void */ - function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $mode='customer') + function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0) { global $conf,$langs; if ($htmlname != "none") @@ -4232,7 +4232,7 @@ class Form print ''; print ''; print '
'; - if($mode == 'supplier') { + if(! empty($discount_type)) { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { if (! $filter || $filter=="fk_invoice_supplier IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice @@ -4260,11 +4260,10 @@ class Form if (empty($hidelist)) { print '
'; - if($mode == 'supplier') { - $newfilter = 'fk_facture_source IS NULL AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Exclude customer discounts + $newfilter = 'discount_type='.intval($discount_type); + if(! empty($discount_type)) { $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available } else { - $newfilter = 'fk_invoice_supplier_source IS NULL AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Exclude supplier discounts $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available } if ($filter) $newfilter.=' AND ('.$filter.')'; @@ -4272,9 +4271,9 @@ class Form if ($nbqualifiedlines > 0) { print '   '; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index b23c9af5fce..198954572d1 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -2672,7 +2672,7 @@ class SupplierInvoiceLine extends CommonObjectLine $this->error = $this->db->lasterror(); } } - + // TODO free discount linked to line as in customer invoice if (! $error) { $this->db->commit(); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index a397d40d147..e3c68177b41 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -133,7 +133,7 @@ if (empty($reshook)) $object->fetch_thirdparty(); $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } - + var_dump($conf->global->MAIN_VERSION_LAST_UPGRADE, $conf->global->MAIN_VERSION_LAST_INSTALL); // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { @@ -272,7 +272,7 @@ if (empty($reshook)) { $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); - $discount->unlink_invoice('supplier'); + $discount->unlink_invoice(); } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) @@ -419,7 +419,7 @@ if (empty($reshook)) if (! $error) { - $result = $discount->link_to_invoice(0, $id, 'supplier'); + $result = $discount->link_to_invoice(0, $id); if ($result < 0) { setEventMessages($discount->error, $discount->errors, 'errors'); } @@ -486,6 +486,7 @@ if (empty($reshook)) else { setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); } + $discount->discount_type = 1; // Supplier discount $discount->fk_soc = $object->socid; $discount->fk_invoice_supplier_source = $object->id; @@ -1679,7 +1680,7 @@ if ($action == 'create') if ($societe->id > 0) { - $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 'supplier'); + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); print $societe->getNomUrl(1); print ''; } @@ -2143,12 +2144,12 @@ else $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 'supplier'); - $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 'supplier'); + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); @@ -2442,7 +2443,7 @@ else } else { // Discount available of type fixed amount (not credit note) print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 'supplier'); + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { if ($absolute_creditnote > 0) // If not, link will be added later @@ -2468,9 +2469,9 @@ else } else { // We can add a credit note on a down payment or standard invoice or situation invoice // There is credit notes discounts available if (! $absolute_discount) print '
'; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 'supplier'); + // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 'supplier'); // We allow credit note even if amount is higher + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher } } if (! $absolute_discount && ! $absolute_creditnote) { diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 9bfe0bd2915..bfc2c79a679 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -35,3 +35,4 @@ ALTER TABLE llx_projet ADD COLUMN bill_time integer DEFAULT 0; ALTER TABLE llx_societe ADD COLUMN order_min_amount double(24,8) DEFAULT NULL AFTER outstanding_limit; ALTER TABLE llx_societe ADD COLUMN supplier_order_min_amount double(24,8) DEFAULT NULL AFTER order_min_amount; +ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql index 148a8777915..525af592041 100644 --- a/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql +++ b/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql @@ -26,6 +26,7 @@ ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_soc ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_facture_line (fk_facture_line); ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_facture (fk_facture); ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_facture_source (fk_facture_source); +ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_discount_type (discount_type); ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_user FOREIGN KEY (fk_user) REFERENCES llx_user (rowid); diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.sql index 3a19a026ca9..151e33d7f1e 100644 --- a/htdocs/install/mysql/tables/llx_societe_remise_except.sql +++ b/htdocs/install/mysql/tables/llx_societe_remise_except.sql @@ -23,7 +23,8 @@ create table llx_societe_remise_except ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id - fk_soc integer NOT NULL, -- client + fk_soc integer NOT NULL, -- customer or supplier + discount_type integer DEFAULT 0 NOT NULL, -- 0 => customer, 1 => supplier datec datetime, amount_ht double(24,8) NOT NULL, amount_tva double(24,8) DEFAULT 0 NOT NULL, diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 4adfae72258..2e980ba7ff8 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1661,13 +1661,14 @@ class Societe extends CommonObject /** * Add a discount for third party * - * @param float $remise Amount of discount - * @param User $user User adding discount - * @param string $desc Reason of discount - * @param float $tva_tx VAT rate + * @param float $remise Amount of discount + * @param User $user User adding discount + * @param string $desc Reason of discount + * @param float $tva_tx VAT rate + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, id of discount record if OK */ - function set_remise_except($remise, User $user, $desc, $tva_tx=0) + function set_remise_except($remise, User $user, $desc, $tva_tx=0, $discount_type=0) { global $langs; @@ -1693,11 +1694,13 @@ class Societe extends CommonObject $discount = new DiscountAbsolute($this->db); $discount->fk_soc=$this->id; + $discount->discount_type=$discount_type; $discount->amount_ht=price2num($remise,'MT'); $discount->amount_tva=price2num($remise*$tva_tx/100,'MT'); $discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT'); $discount->tva_tx=price2num($tva_tx,'MT'); $discount->description=$desc; + $result=$discount->create($user); if ($result > 0) { @@ -1715,18 +1718,18 @@ class Societe extends CommonObject /** * Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe * - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param integer $maxvalue Filter on max value for discount - * @param string $mode 'supplier' to get available discounts for suppliers, 'customer' instead + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param integer $maxvalue Filter on max value for discount + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, Credit note amount otherwise */ - function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$mode='customer') + function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$discount_type=0) { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discountstatic=new DiscountAbsolute($this->db); - $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$mode); + $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$discount_type); if ($result >= 0) { return $result; From bd486e4cabae60ec559f12a6b88495efc8081df2 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 10:29:36 +0100 Subject: [PATCH 06/91] FIX: remove var_dump --- htdocs/fourn/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index e3c68177b41..3ab9e4e684c 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -133,7 +133,7 @@ if (empty($reshook)) $object->fetch_thirdparty(); $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } - var_dump($conf->global->MAIN_VERSION_LAST_UPGRADE, $conf->global->MAIN_VERSION_LAST_INSTALL); + // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { From 905adab5176331c11b9936e06f8815723a06a272 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 11:23:59 +0100 Subject: [PATCH 07/91] NEW: supplier credit notes: display supplier discounts in supplier order card --- htdocs/commande/card.php | 7 ++-- htdocs/fourn/commande/card.php | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 6e1d411d55e..a56dc6cd5ac 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -2038,8 +2038,7 @@ if ($action == 'create' && $user->rights->commande->creer) // Relative and absolute discounts if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final - // invoice + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; @@ -2056,8 +2055,8 @@ if ($action == 'create' && $user->rights->commande->creer) else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; - $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL'); - $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL'); + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); if ($absolute_discount) { diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 81ea1a0f951..5c632530a8e 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1477,6 +1477,29 @@ if ($action=='create') } print ''; + if ($societe->id > 0) + { + // Discounts for third party + print '' . $langs->trans('Discounts') . ''; + if ($fourn->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print '. '; + print '
'; + + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); + + if ($absolute_discount) + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + else + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print '.'; + print ''; + } + // Ref supplier print ''.$langs->trans('RefSupplier').''; print ''; @@ -1857,6 +1880,45 @@ elseif (! empty($object->id)) print ''.$author->getNomUrl(1, '', 0, 0, 0).''; print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print '' . $langs->trans('Discounts') . ''; + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) + print '
'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print ''; + // Conditions de reglement par defaut $langs->load('bills'); print ''; From d2bb6a790b2bc98a36ecc05012362dc4656be75d Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 11:45:57 +0100 Subject: [PATCH 08/91] NEW: supplier credit notes: display supplier discounts in supplier proposal card --- htdocs/fourn/commande/card.php | 2 +- htdocs/supplier_proposal/card.php | 62 +++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 5c632530a8e..798c6219356 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1481,7 +1481,7 @@ if ($action=='create') { // Discounts for third party print '' . $langs->trans('Discounts') . ''; - if ($fourn->remise_percent) + if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); else print $langs->trans("CompanyHasNoRelativeDiscount"); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index a5488959016..dcd15b61469 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1048,6 +1048,29 @@ if ($action == 'create') } print '' . "\n"; + if ($soc->id > 0) + { + // Discounts for third party + print '' . $langs->trans('Discounts') . ''; + if ($fourn->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print '. '; + print '
'; + + $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); + + if ($absolute_discount) + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + else + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print '.'; + print ''; + } + // Terms of payment print '' . $langs->trans('PaymentConditionsShort') . ''; $form->select_conditions_paiements(GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $cond_reglement_id, 'cond_reglement_id', -1, 1); @@ -1387,6 +1410,45 @@ if ($action == 'create') print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print ''; + // Payment term print ''; } + $remise_percent = $buyer->remise_percent; + if($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') { + $remise_percent = $seller->remise_supplier_percent; + } ?> - + situation_cycle_ref) { $coldisplay++; diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 60f745d95c7..1929c11a464 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -257,6 +257,19 @@ if ($object->id > 0) print ''; if($conf->global->MAIN_FEATURES_LEVEL > 0) { + // Relative discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + // Absolute discounts (Discounts-Drawbacks-Rebates) print '\n"; - $stripeaccount = $stripe->GetStripeAccount($conf->entity); + $stripeaccount = $stripe->getStripeAccount($service); $txn = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeaccount)); From 7a277a8d2b649d9ae98d18c58b28e35a410c6723 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 21:32:52 +0100 Subject: [PATCH 54/91] Debug list of charges. Compatible with the metadata FULLTAG used by dolibarr native online payment page. --- htdocs/langs/en_US/stripe.lang | 5 ++- htdocs/stripe/charge.php | 82 +++++++++++++++++++++++----------- 2 files changed, 61 insertions(+), 26 deletions(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 5c7b782f593..782c49ce61e 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -46,4 +46,7 @@ ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error C StripeGateways=Stripe gateways OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...) OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) -BankAccountForBankTransfer=Bank account for fund payouts \ No newline at end of file +BankAccountForBankTransfer=Bank account for fund payouts +StripeAccount=Stripe account +StripeChargeList=List of Stripe charges +StripeCustomer=Stripe customer id \ No newline at end of file diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index 9ba246cf9a8..2c937e318a4 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -18,6 +18,8 @@ // Put here all includes required by your class file require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; //require_once DOL_DOCUMENT_ROOT.'/core/lib/stripe.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -55,7 +57,8 @@ $pagenext = $page + 1; llxHeader('', $langs->trans("StripeChargeList")); $form = new Form($db); -$societestatic = new societe($db); +$societestatic = new Societe($db); +$memberstatic = new Adherent($db); $acc = new Account($db); $stripe=new Stripe($db); if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) @@ -92,12 +95,13 @@ if (!$rowid && $stripeaccount) print ''; print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); + print_liste_field_titre("StripeCustomer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); print_liste_field_titre("Origin",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"","","",'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"'); print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"","","",'align="left"',$sortfield,$sortorder); print_liste_field_titre("Paid",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder); + print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"'); print "\n"; print "\n"; @@ -107,21 +111,48 @@ if (!$rowid && $stripeaccount) //print $list; foreach ($list->data as $charge) { + // The metadata FULLTAG is defined by the online payment page + $FULLTAG=$charge->metadata->FULLTAG; + + // Save into $tmparray all metadata + $tmparray = dolExplodeIntoArray($FULLTAG,'.','='); + // Load origin object according to metadata + if (! empty($tmparray['CUS'])) + { + $societestatic->fetch($tmparray['CUS']); + } + else + { + $societestatic->id = 0; + } + if (! empty($tmparray['MEM'])) + { + $memberstatic->fetch($tmparray['MEM']); + } + else + { + $memberstatic->id = 0; + } + print ''; - $societestatic->fetch($charge->metadata->idcustomer); - $societestatic->id=$charge->metadata->idcustomer; - $societestatic->lastname=$obj->lastname; - $societestatic->firstname=$obj->firstname; - $societestatic->admin=$obj->admin; - $societestatic->login=$obj->login; - $societestatic->email=$obj->email; - $societestatic->societe_id=$obj->fk_soc; // Ref print "\n"; + // Stripe customer + print "\n"; // Employee - print "\n"; + print "\n"; // Origine print "\n"; - // Date payment + // Date payment print '\n"; - // Label payment - print "\n"; // Type print ''; // Amount print ""; + // Status + print "\n"; + print "\n"; } } else { From 489dde4db4c70c9555c9bd7d46ace9a03c447abe Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 22:26:42 +0100 Subject: [PATCH 55/91] Prepare database to store payment modes of customers --- .../install/mysql/migration/7.0.0-8.0.0.sql | 20 +++++++++ .../install/mysql/tables/llx_societe_rib.sql | 28 ++++++++++-- .../canvas/company/tpl/card_view.tpl.php | 2 +- .../canvas/individual/tpl/card_view.tpl.php | 2 +- htdocs/societe/class/societe.class.php | 20 ++++----- htdocs/societe/paymentmodes.php | 45 +++++++++++-------- htdocs/stripe/class/stripe.class.php | 6 ++- 7 files changed, 88 insertions(+), 35 deletions(-) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index eb3c865c106..227562ea9bc 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -97,3 +97,23 @@ ALTER TABLE llx_c_payment_term CHANGE COLUMN rowid rowid INTEGER AUTO_INCREMENT ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code); ALTER TABLE llx_oauth_token ADD COLUMN tokenstring text; + +-- Add field for payment modes +ALTER TABLE llx_societe_rib ADD COLUMN type varchar(32) DEFAULT 'ban' after rowid; +ALTER TABLE llx_societe_rib ADD COLUMN last_four varchar(4); +ALTER TABLE llx_societe_rib ADD COLUMN card_type varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN cvn varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN exp_date_month INTEGER; +ALTER TABLE llx_societe_rib ADD COLUMN exp_date_year INTEGER; +ALTER TABLE llx_societe_rib ADD COLUMN country_code varchar(10); +ALTER TABLE llx_societe_rib ADD COLUMN approved integer DEFAULT 0; +ALTER TABLE llx_societe_rib ADD COLUMN email varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN ending_date date; +ALTER TABLE llx_societe_rib ADD COLUMN max_total_amount_of_all_payments double(24,8); +ALTER TABLE llx_societe_rib ADD COLUMN preapproval_key varchar(255); +ALTER TABLE llx_societe_rib ADD COLUMN starting_date date; +ALTER TABLE llx_societe_rib ADD COLUMN total_amount_of_all_payments double(24,8); +ALTER TABLE llx_societe_rib ADD COLUMN stripe_card_ref varchar(128); +ALTER TABLE llx_societe_rib ADD COLUMN status integer NOT NULL DEFAULT 1; + + diff --git a/htdocs/install/mysql/tables/llx_societe_rib.sql b/htdocs/install/mysql/tables/llx_societe_rib.sql index 168a2803c9d..6157af37830 100644 --- a/htdocs/install/mysql/tables/llx_societe_rib.sql +++ b/htdocs/install/mysql/tables/llx_societe_rib.sql @@ -17,15 +17,19 @@ -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . -- +-- Table with the payment modes of a thirdparty (BAN, Paypal, Card, ...) -- ============================================================================= create table llx_societe_rib ( rowid integer AUTO_INCREMENT PRIMARY KEY, + type varchar(32) DEFAULT 'ban', -- 'ban' or 'paypal' or 'card' or 'stripe' + label varchar(30), fk_soc integer NOT NULL, datec datetime, tms timestamp, - label varchar(30), + + -- For BAN bank varchar(255), -- bank name code_banque varchar(128), -- bank code code_guichet varchar(6), -- desk code @@ -37,10 +41,28 @@ create table llx_societe_rib proprio varchar(60), owner_address varchar(255), default_rib smallint NOT NULL DEFAULT 0, - + -- For BAN direct debit feature rum varchar(32), -- RUM value to use for SEPA generation date_rum date, -- Date of mandate frstrecur varchar(16) default 'FRST', -- 'FRST' or 'RECUR' - + --For credit card + last_four varchar(4), -- last 4 + card_type varchar(255), -- card type 'VISA', 'MC' , ... + cvn varchar(255), + exp_date_month INTEGER, + exp_date_year INTEGER, + country_code varchar(10), + --For Paypal + approved INTEGER DEFAULT 0, + email varchar(255), + ending_date date, + max_total_amount_of_all_payments double(24,8), + preapproval_key varchar(255), + starting_date date, + total_amount_of_all_payments double(24,8), + --For Stripe + stripe_card_ref varchar(128), -- 'card_...' + + status integer NOT NULL DEFAULT 1, -- 1=ACTIVE, 0=IN_TRASH import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/societe/canvas/company/tpl/card_view.tpl.php b/htdocs/societe/canvas/company/tpl/card_view.tpl.php index 3865e9b95a0..24ddfbaaaac 100644 --- a/htdocs/societe/canvas/company/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_view.tpl.php @@ -185,7 +185,7 @@ for ($i=1; $i<=4; $i++) { '; print '
' . $langs->trans('Discounts') . ''; + if ($soc->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > SupplierProposal::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) + print '
'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print '
'; print ''; // TODO adapt text + print ''; print ''; if (! empty($user->fk_soc)) // No need to show this for external users { - print ''; // TODO adapt text + print ''; print ''; } @@ -307,12 +307,12 @@ if ($socid > 0) dol_print_error($db); } - print ''; // TODO adapt text + print ''; print ''; if (! empty($user->fk_soc)) // No need to show this for external users { - print ''; // TODO adapt text + print ''; print ''; } } @@ -330,9 +330,10 @@ if ($socid > 0) print '
'; print '
'; From 7367769ec36f96be619cc950cc3e5d6c14c64b61 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 11:59:51 +0100 Subject: [PATCH 09/91] FIX: supplier credit notes: use correct rights in supplier invoice card --- htdocs/fourn/facture/card.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 3ab9e4e684c..ace7ce0b1b7 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -268,7 +268,7 @@ if (empty($reshook)) } // Delete link of credit note to invoice - else if ($action == 'unlinkdiscount' && $user->rights->facture->creer) + else if ($action == 'unlinkdiscount' && $user->rights->fournisseur->facture->creer) { $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); @@ -326,12 +326,12 @@ if (empty($reshook)) } // Multicurrency Code - else if ($action == 'setmulticurrencycode' && $user->rights->facture->creer) { + else if ($action == 'setmulticurrencycode' && $user->rights->fournisseur->facture->creer) { $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); } // Multicurrency rate - else if ($action == 'setmulticurrencyrate' && $user->rights->facture->creer) { + else if ($action == 'setmulticurrencyrate' && $user->rights->fournisseur->facture->creer) { $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha'))); } @@ -385,7 +385,7 @@ if (empty($reshook)) $result=$object->update($user); if ($result < 0) dol_print_error($db,$object->error); } - elseif ($action == "setabsolutediscount" && $user->rights->facture->creer) + elseif ($action == "setabsolutediscount" && $user->rights->fournisseur->facture->creer) { // POST[remise_id] or POST[remise_id_for_payment] @@ -443,7 +443,7 @@ if (empty($reshook)) } } // Convertir en reduc - else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer) + else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); $object->fetch_thirdparty(); @@ -3108,7 +3108,7 @@ else } // For standard invoice with excess paid - if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->facture->creer && empty($discount->id)) + if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->fournisseur->facture->creer && empty($discount->id)) { print ''; // TODO translation : trop-perçu => trop payé } From fa0c65e37ee1f35d1282ff8029616fd82d65186a Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 12:05:36 +0100 Subject: [PATCH 10/91] FIX: supplier credit notes: correctly handle discount split --- htdocs/comm/remx.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 072baa675fb..ad6c1f33a97 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -93,6 +93,12 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->fk_facture=$discount->fk_facture; $newdiscount1->fk_facture_line=$discount->fk_facture_line; $newdiscount2->fk_facture_line=$discount->fk_facture_line; + $newdiscount1->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; + $newdiscount2->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; + $newdiscount1->fk_invoice_supplier=$discount->fk_invoice_supplier; + $newdiscount2->fk_invoice_supplier=$discount->fk_invoice_supplier; + $newdiscount1->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; + $newdiscount2->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') { $newdiscount1->description=$discount->description; @@ -107,6 +113,8 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->fk_user=$discount->fk_user; $newdiscount1->fk_soc=$discount->fk_soc; $newdiscount2->fk_soc=$discount->fk_soc; + $newdiscount1->discount_type=$discount->discount_type; + $newdiscount2->discount_type=$discount->discount_type; $newdiscount1->datec=$discount->datec; $newdiscount2->datec=$discount->datec; $newdiscount1->tva_tx=$discount->tva_tx; From 924a9c392cd5cecf4c9e7666a9df38cf1e7f2037 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 16 Feb 2018 12:30:32 +0100 Subject: [PATCH 11/91] FIX: supplier credit notes: hide relative discounts until supported --- htdocs/fourn/commande/card.php | 7 +++++-- htdocs/fourn/facture/card.php | 19 +++++++++++-------- htdocs/supplier_proposal/card.php | 9 ++++++--- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 798c6219356..c65b7d6cf60 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1479,6 +1479,7 @@ if ($action=='create') if ($societe->id > 0) { +/* // TODO handle supplier relative discount // Discounts for third party print '
' . $langs->trans('Discounts') . ''; if ($societe->remise_percent) @@ -1488,7 +1489,7 @@ if ($action=='create') print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; - +*/ $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1894,11 +1895,13 @@ elseif (! empty($object->id)) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; +*/ $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1908,7 +1911,7 @@ elseif (! empty($object->id)) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) - print '
'; +// print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index ace7ce0b1b7..255c917b6a9 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1917,6 +1917,7 @@ if ($action == 'create') { // Discounts for third party print '
' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); else @@ -1924,6 +1925,7 @@ if ($action == 'create') print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; +*/ if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); else @@ -2417,15 +2419,16 @@ else print '
' . $langs->trans('Discounts'); print ''; +/* // TODO handle supplier relative discount if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); // print ' ('.$addrelativediscount.')'; - +*/ // Is there is commercial discount or down payment available ? if ($absolute_discount > 0) { - print '. '; +// print '. '; if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { if ($object->statut == 0) { print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); @@ -2433,7 +2436,7 @@ else } else { if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
' . $text . '.
'; + print '' . $text . '.
'; } else { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); $text2 = $langs->trans("AbsoluteDiscountUse"); @@ -2442,7 +2445,7 @@ else } } else { // Discount available of type fixed amount (not credit note) - print '
'; +// print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { @@ -2450,10 +2453,10 @@ else { if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) print ' (' . $addabsolutediscount . ')
'; - else - print '. '; +// else +// print '. '; } else - print '. '; + print '. '; } // Is there credit notes availables ? if ($absolute_creditnote > 0) @@ -2468,7 +2471,7 @@ else } } else { // We can add a credit note on a down payment or standard invoice or situation invoice // There is credit notes discounts available - if (! $absolute_discount) print '
'; +// if (! $absolute_discount) print '
'; // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index dcd15b61469..ba78c78dade 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1050,16 +1050,17 @@ if ($action == 'create') if ($soc->id > 0) { +/* // TODO handle supplier relative discount // Discounts for third party print '
' . $langs->trans('Discounts') . ''; - if ($fourn->remise_percent) + if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); else print $langs->trans("CompanyHasNoRelativeDiscount"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; - +*/ $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1424,11 +1425,13 @@ if ($action == 'create') $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; +*/ $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1438,7 +1441,7 @@ if ($action == 'create') print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) - print '
'; +// print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } From f5ad93b272cfcc0d699ee3b9130640520ff5b6d3 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 19 Feb 2018 15:52:07 +0100 Subject: [PATCH 12/91] NEW: supplier credit notes: handle Excess Paid + translation --- htdocs/comm/remx.php | 29 ++++++++++--------- htdocs/core/class/commonobject.class.php | 8 ++++- htdocs/core/class/discount.class.php | 6 ++-- htdocs/core/class/html.form.class.php | 2 +- htdocs/core/lib/doc.lib.php | 12 ++++++-- htdocs/core/lib/pdf.lib.php | 14 +++++++-- htdocs/core/tpl/objectline_view.tpl.php | 11 +++++-- .../fourn/class/fournisseur.facture.class.php | 2 ++ htdocs/fourn/facture/card.php | 10 +++---- htdocs/langs/en_US/bills.lang | 9 +++++- htdocs/langs/en_US/companies.lang | 6 ++-- htdocs/societe/consumption.php | 11 +++++-- 12 files changed, 85 insertions(+), 35 deletions(-) diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index ad6c1f33a97..177b4456912 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -276,12 +276,12 @@ if ($socid > 0) dol_print_error($db); } - print '
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").'
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").'
'.$langs->trans("SupplierAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").'
'.$langs->trans("SupplierAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'; if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; - print ''; + print ''; + print ''; } print ''; print ''; - } - $db->free($resql); - print "
'.$langs->trans('DiscountType').' '; - print '
'.$langs->trans('DiscountType').' '; + print ' '; + print '
'.$langs->trans("AmountHT").''; @@ -401,7 +402,7 @@ if ($socid > 0) if ($resql) { if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } print ''; print ''; @@ -536,7 +537,7 @@ if ($socid > 0) $resql=$db->query($sql); if ($resql) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print '
'; print ''; print ''; // Need 120+ for format with AM/PM @@ -585,7 +586,7 @@ if ($socid > 0) $facturefournstatic->id=$obj->fk_invoice_supplier_source; $facturefournstatic->ref=$obj->ref; $facturefournstatic->type=$obj->type; - print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); // TODO translate ExcessPaid + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); print ''; } else @@ -705,7 +706,7 @@ if ($socid > 0) if ($resql2) { if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } print '
'.$langs->trans("Date").'
'; print ''; @@ -855,7 +856,7 @@ if ($socid > 0) if ($resql) $resql2=$db->query($sql2); if ($resql2) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); // TODO translate + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print '
'; print ''; print ''; // Need 120+ for format with AM/PM @@ -934,12 +935,12 @@ if ($socid > 0) print $obj->description; print ''; } - print ''; // TODO adapt to supplier invoice of use getNomUrl + print ''; print ''; print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index e45acea7675..5abf5e3a0e1 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -3963,7 +3963,13 @@ abstract class CommonObject $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } // TODO handle (EXCESS PAID) + } + elseif ($line->desc == '(EXCESS PAID)') + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } else { $this->tpl['description'] = dol_trunc($line->desc,60); diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index b62e35c183e..b71d84130a1 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -46,6 +46,7 @@ class DiscountAbsolute public $fk_facture; // Id invoice when a discount line is used into an invoice (for credit note) public $fk_facture_source; // Id facture avoir a l'origine de la remise public $ref_facture_source; // Ref facture avoir a l'origine de la remise + public $ref_invoive_supplier_source; /** * Constructor @@ -568,10 +569,11 @@ class DiscountAbsolute $result=''; if ($option == 'invoice') { + $facid=! empty($this->discount_type)?$this->fk_invoice_supplier_source:$this->fk_facture_source; $label=$langs->trans("ShowDiscount").': '.$this->ref_facture_source; - $link = ''; + $link = ''; $linkend=''; - $ref=$this->ref_facture_source; + $ref=! empty($this->discount_type)?$this->ref_invoice_supplier_source:$this->ref_facture_source; $picto='bill'; } if ($option == 'discount') { diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index e6ab69dff95..f65a3bec36c 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -1236,7 +1236,7 @@ class Form if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); - // TODO handle (EXCESS PAID) + if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc); $selectstring=''; if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 20eaa9a71f7..447c7c2149e 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -73,13 +73,15 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$discount->ref_facture_source); + $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref); } elseif ($desc == '(DEPOSIT)' && $line->fk_remise_except) { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$discount->ref_facture_source); + $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice.=' ('.dol_print_date($discount->datec,'day','',$outputlangs).')'; } @@ -88,7 +90,13 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } // TODO handle (EXCESS PAID) + } + elseif ($desc == '(EXCESS PAID)' && $line->fk_remise_except) + { + $discount=new DiscountAbsolute($db); + $discount->fetch($line->fk_remise_except); + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source); + } else { if ($idprod) diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 0fb649506cb..31fcc519051 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -1236,13 +1236,15 @@ function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issuppl { $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$discount->ref_facture_source); + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref); } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) { $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$discount->ref_facture_source); + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec,'day','',$outputlangs).')'; } @@ -1251,7 +1253,13 @@ function pdf_getlinedesc($object,$i,$outputlangs,$hideref=0,$hidedesc=0,$issuppl $discount=new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived",$discount->ref_facture_source); - } // TODO handle (EXCESS PAID) + } + elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) + { + $discount=new DiscountAbsolute($db); + $discount->fetch($object->lines[$i]->fk_remise_except); + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid",$discount->ref_invoice_supplier_source); + } else { if ($idprod) diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index bc5d950ab8e..6371e289207 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -72,7 +72,8 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($line->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) + elseif ($line->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($line->description == '(EXCESS PAID)') $txt=$langs->trans("ExcessPaid"); //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -100,7 +101,13 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; $discount=new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } // TODO handle (EXCESS PAID) + } + elseif ($line->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } else { echo ($txt?' - ':'').dol_htmlentitiesbr($line->description); diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 3fe59d66ff7..4ebab7d0bc4 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -1049,6 +1049,8 @@ class FactureFournisseur extends CommonInvoice } } + // TODO Delete related discounts + if (! $error) { // Delete linked object diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 255c917b6a9..ca29e7299a6 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2167,10 +2167,10 @@ else // Confirmation de la conversion de l'avoir en reduc if ($action == 'converttoreduc') { - if($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessReceived'; // TODO translation trop-perçu => trop-payé + if($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessPaid'; elseif($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; elseif($object->type == FactureFournisseur::TYPE_DEPOSIT) $type_fac = 'Deposit'; - $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac))); // TODO translation client => fournisseur + $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac))); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); } @@ -2872,7 +2872,7 @@ else print ' :'; print ''; print ''; $i ++; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) @@ -2929,7 +2929,7 @@ else if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay'); else - print $langs->trans('ExcessReceived'); + print $langs->trans('ExcessPaid'); print ' :'; print ''; print ''; @@ -3113,7 +3113,7 @@ else // For standard invoice with excess paid if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->fournisseur->facture->creer && empty($discount->id)) { - print ''; // TODO translation : trop-perçu => trop payé + print ''; } // For credit note if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() == 0) { diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index 668090129ff..62386adbe99 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -67,6 +67,7 @@ PaidBack=Paid back DeletePayment=Delete payment ConfirmDeletePayment=Are you sure you want to delete this payment? ConfirmConvertToReduc=Do you want to convert this %s into an absolute discount ?
The amount will so be saved among all discounts and could be used as a discount for a current or a future invoice for this customer. +ConfirmConvertToReducSupplier=Do you want to convert this %s into an absolute discount ?
The amount will so be saved among all discounts and could be used as a discount for a current or a future invoice for this supplier. SupplierPayments=Suppliers payments ReceivedPayments=Received payments ReceivedCustomersPayments=Payments received from customers @@ -91,7 +92,7 @@ PaymentAmount=Payment amount ValidatePayment=Validate payment PaymentHigherThanReminderToPay=Payment higher than reminder to pay HelpPaymentHigherThanReminderToPay=Attention, the payment amount of one or more bills is higher than the rest to pay.
Edit your entry, otherwise confirm and think about creating a credit note of the excess received for each overpaid invoices. -HelpPaymentHigherThanReminderToPaySupplier=Attention, the payment amount of one or more bills is higher than the rest to pay.
Edit your entry, otherwise confirm. +HelpPaymentHigherThanReminderToPaySupplier=Attention, the payment amount of one or more bills is higher than the rest to pay.
Edit your entry, otherwise confirm and think about creating a credit note of the excess paid for each overpaid invoice. ClassifyPaid=Classify 'Paid' ClassifyPaidPartially=Classify 'Paid partially' ClassifyCanceled=Classify 'Abandoned' @@ -110,6 +111,7 @@ DoPayment=Enter payment DoPaymentBack=Enter refund ConvertToReduc=Convert into future discount ConvertExcessReceivedToReduc=Convert excess received into future discount +ConvertExcessPaidToReduc=Convert excess paid into future discount EnterPaymentReceivedFromCustomer=Enter payment received from customer EnterPaymentDueToCustomer=Make payment due to customer DisabledBecauseRemainderToPayIsZero=Disabled because remaining unpaid is zero @@ -220,6 +222,7 @@ RemainderToPayBack=Remaining amount to refund Rest=Pending AmountExpected=Amount claimed ExcessReceived=Excess received +ExcessPaid=Excess paid EscompteOffered=Discount offered (payment before term) EscompteOfferedShort=Discount SendBillRef=Submission of invoice %s @@ -284,15 +287,19 @@ Deposits=Down payments DiscountFromCreditNote=Discount from credit note %s DiscountFromDeposit=Down payments from invoice %s DiscountFromExcessReceived=Payments from excess received of invoice %s +DiscountFromExcessPaid=Payments from excess paid of invoice %s AbsoluteDiscountUse=This kind of credit can be used on invoice before its validation CreditNoteDepositUse=Invoice must be validated to use this kind of credits NewGlobalDiscount=New absolute discount NewRelativeDiscount=New relative discount +DiscountType=Discount type NoteReason=Note/Reason ReasonDiscount=Reason DiscountOfferedBy=Granted by DiscountStillRemaining=Discounts available DiscountAlreadyCounted=Discounts already consumed +CustomerDiscounts=Customer discounts +SupplierDiscounts=Supplier discounts BillAddress=Bill address HelpEscompte=This discount is a discount granted to customer because its payment was made before term. HelpAbandonBadCustomer=This amount has been abandoned (customer said to be a bad customer) and is considered as an exceptional loose. diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 7d2b878c5cc..2eb1ba88e57 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -271,8 +271,10 @@ CompanyHasAbsoluteDiscount=This customer has discount available (credits notes o CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s CompanyHasNoAbsoluteDiscount=This customer has no discount credit available -CustomerAbsoluteDiscountAllUsers=Absolute discounts (granted by all users) -CustomerAbsoluteDiscountMy=Absolute discounts (granted by yourself) +CustomerAbsoluteDiscountAllUsers=Absolute customer discounts (granted by all users) +CustomerAbsoluteDiscountMy=Absolute customer discounts (granted by yourself) +SupplierAbsoluteDiscountAllUsers=Absolute supplier discounts (granted by all users) +SupplierAbsoluteDiscountMy=Absolute supplier discounts (granted by yourself) DiscountNone=None Supplier=Supplier AddContact=Create contact diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index 1420562da19..1a6a4be6199 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -490,7 +490,8 @@ if ($sql_select) $txt=''; print img_object($langs->trans("ShowReduc"),'reduc').' '; if ($objp->description == '(DEPOSIT)') $txt=$langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); // TODO handle (EXCESS PAID) + elseif ($objp->description == '(EXCESS RECEIVED)') $txt=$langs->trans("ExcessReceived"); + elseif ($objp->description == '(EXCESS PAID)') $txt=$langs->trans("ExcessPaid"); //else $txt=$langs->trans("Discount"); print $txt; ?> @@ -510,6 +511,12 @@ if ($sql_select) $discount->fetch($objp->fk_remise_except); echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); } + elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) + { + $discount=new DiscountAbsolute($db); + $discount->fetch($objp->fk_remise_except); + echo ($txt?' - ':'').$langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) { $discount=new DiscountAbsolute($db); @@ -517,7 +524,7 @@ if ($sql_select) echo ($txt?' - ':'').$langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; - } // TODO handle (EXCESS PAID) + } else { echo ($txt?' - ':'').dol_htmlentitiesbr($objp->description); From 57b8df400806f726946cb4ccca55f44dac548dc8 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 19 Feb 2018 17:32:11 +0100 Subject: [PATCH 13/91] FIX: supplier credit notes: delete discount when deleting linked invoice/invoice line --- .../fourn/class/fournisseur.facture.class.php | 68 +++++++++++++++++-- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 4ebab7d0bc4..570966d8600 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -925,13 +925,14 @@ class FactureFournisseur extends CommonInvoice } $facligne=new SupplierInvoiceLine($this->db); - $facligne->fk_facture=$this->id; + $facligne->fk_facture_fourn=$this->id; $facligne->fk_remise_except=$remise->id; $facligne->desc=$remise->description; // Description ligne $facligne->vat_src_code=$remise->vat_src_code; $facligne->tva_tx=$remise->tva_tx; $facligne->subprice = -$remise->amount_ht; $facligne->fk_product=0; // Id produit predefini + $facligne->product_type=0; $facligne->qty=1; $facligne->remise_percent=0; $facligne->rang=-1; @@ -1030,6 +1031,33 @@ class FactureFournisseur extends CommonInvoice // Fin appel triggers } + if (! $error) { + // If invoice was converted into a discount not yet consumed, we remove discount + $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql .= ' WHERE fk_invoice_supplier_source = ' . $rowid; + $sql .= ' AND fk_invoice_supplier_line IS NULL'; + $resql = $this->db->query($sql); + + // If invoice has consumned discounts + $this->fetch_lines(); + $list_rowid_det = array (); + foreach ($this->lines as $key => $invoiceline) { + $list_rowid_det[] = $invoiceline->rowid; + } + + // Consumned discounts are freed + if (count($list_rowid_det)) { + $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql .= ' SET fk_invoice_supplier = NULL, fk_invoice_supplier_line = NULL'; + $sql .= ' WHERE fk_invoice_supplier_line IN (' . join(',', $list_rowid_det) . ')'; + + dol_syslog(get_class($this) . "::delete", LOG_DEBUG); + if (! $this->db->query($sql)) { + $error ++; + } + } + } + if (! $error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';'; @@ -1049,8 +1077,6 @@ class FactureFournisseur extends CommonInvoice } } - // TODO Delete related discounts - if (! $error) { // Delete linked object @@ -1769,6 +1795,22 @@ class FactureFournisseur extends CommonInvoice $rowid = $this->id; } + $this->db->begin(); + + // Libere remise liee a ligne de facture + $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql .= ' SET fk_invoice_supplier_line = NULL'; + $sql .= ' WHERE fk_invoice_supplier_line = ' . $rowid; + + dol_syslog(get_class($this) . "::deleteline", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) + { + $this->error = $this->db->error(); + $this->db->rollback(); + return - 2; + } + $line = new SupplierInvoiceLine($this->db); if ($line->fetch($rowid) < 1) { @@ -1778,12 +1820,24 @@ class FactureFournisseur extends CommonInvoice $res = $line->delete($notrigger); if ($res < 1) { - $this->errors[] = $line->error; + $this->errors[] = $line->error; + $this->db->rollback(); + return - 3; } else { - $res = $this->update_price(); - } + $res = $this->update_price(); - return $res; + if ($res > 0) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + return - 4; + } + } } From a66f7b8bc84428b5c285b46cb2d93d4779226558 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 19 Feb 2018 17:32:59 +0100 Subject: [PATCH 14/91] FIX: supplier credit notes: wrong discount filters --- htdocs/compta/facture/card.php | 8 ++++---- htdocs/fourn/facture/card.php | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index df5e78b8712..ab75eaa86de 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2989,11 +2989,11 @@ else if ($id > 0 || ! empty($ref)) $resteapayeraffiche = $resteapayer; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this - $filterabsolutediscount = "fk_facture IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_facture IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; - $filtercreditnote = "fk_facture IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index ca29e7299a6..fa046a7a97c 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2143,11 +2143,11 @@ else $resteapayeraffiche = $resteapayer; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this - $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source NOT IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); From bcb39e57fb45ad0a85875e4bcae6eba18cef1799 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 20 Feb 2018 10:08:55 +0100 Subject: [PATCH 15/91] FIX: supplier credit notes: wrong credit note filter --- htdocs/fourn/facture/card.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index fa046a7a97c..d9fcf57a4a6 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2147,7 +2147,7 @@ else $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier_source NOT IS NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); @@ -2426,6 +2426,7 @@ else print $langs->trans("CompanyHasNoRelativeDiscount"); // print ' ('.$addrelativediscount.')'; */ + // Is there is commercial discount or down payment available ? if ($absolute_discount > 0) { // print '. '; From a4f2a2532de1a07670e6b1662b062deb353a92ca Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 20 Feb 2018 11:41:57 +0100 Subject: [PATCH 16/91] FIX: supplier credit notes: use MAIN_FEATURES_LEVEL --- htdocs/fourn/commande/card.php | 77 ++++++----- htdocs/fourn/facture/card.php | 217 +++++++++++++++--------------- htdocs/supplier_proposal/card.php | 81 +++++------ 3 files changed, 193 insertions(+), 182 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index c65b7d6cf60..6cd17690c24 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1477,7 +1477,7 @@ if ($action=='create') } print ''; - if ($societe->id > 0) + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) { /* // TODO handle supplier relative discount // Discounts for third party @@ -1881,46 +1881,49 @@ elseif (! empty($object->id)) print ''; print ''; - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; - } + if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; - print ''; // Conditions de reglement par defaut $langs->load('bills'); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index d9fcf57a4a6..0344890458b 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1913,7 +1913,7 @@ if ($action == 'create') print ''; - if ($societe->id > 0) + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) { // Discounts for third party print ''; - - // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - - print ''; - + // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) + // { + // if (! $absolute_discount && ! $absolute_creditnote) print '
'; + // print '   -   '; + // print $addabsolutediscount; + // print '   -   '.$addcreditnote; // We disbale link to credit note + // } + print ''; + } + // Label print ''; print ''; @@ -2852,37 +2855,39 @@ else $creditnoteamount = 0; $depositamount = 0; - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_invoice_supplier_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_invoice_supplier = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new FactureFournisseur($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_invoice_supplier_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_invoice_supplier_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new FactureFournisseur($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_invoice_supplier_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); } - } else { - dol_print_error($db); } @@ -3097,7 +3102,7 @@ else } // Reverse back money or convert to reduction - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD)) { // For credit note only if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index ba78c78dade..17e5a2be199 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1048,11 +1048,11 @@ if ($action == 'create') } print '' . "\n"; - if ($soc->id > 0) + if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $soc->id > 0) { -/* // TODO handle supplier relative discount // Discounts for third party - print ''; print ''; + dol_print_error($db); } - - print "
'.$langs->trans("Date").''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; // TODO getNomUrl ? + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; print ' 
' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; // TODO unlinkdiscount + print 'rowid . '">' . img_delete() . ''; print '
' . price($resteapayeraffiche) . ' 
'.$author->getNomUrl(1, '', 0, 0, 0).'
' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; -*/ - $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - // Remise dispo de type remise fixe (not credit note) -// print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print '
' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; +*/ + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) +// print '
'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print '
' . $langs->trans('Discounts') . ''; @@ -2410,90 +2410,93 @@ else print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } print '
' . $langs->trans('Discounts'); - print ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - // print ' ('.$addrelativediscount.')'; -*/ - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { -// print '. '; - if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '' . $text . '.
'; + if ($conf->global->MAIN_FEATURES_LEVEL > 0) { + + // Relative and absolute discounts + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; + + print '
' . $langs->trans('Discounts'); + print ''; +/* // TODO handle supplier relative discount + if ($societe->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' ('.$addrelativediscount.')'; +*/ + + // Is there is commercial discount or down payment available ? + if ($absolute_discount > 0) { +// print '. '; + if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + if ($object->statut == 0) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '. '; } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); + if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + print '' . $text . '.
'; + } else { + $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + $text2 = $langs->trans("AbsoluteDiscountUse"); + print $form->textwithpicto($text, $text2); + } } + } else { + // Discount available of type fixed amount (not credit note) +// print '
'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { - // Discount available of type fixed amount (not credit note) -// print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); + if ($absolute_creditnote > 0) // If not, link will be added later + { + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) + print ' (' . $addabsolutediscount . ')
'; +// else +// print '. '; + } else + print '. '; } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later + // Is there credit notes availables ? + if ($absolute_creditnote > 0) { + // If validated, we show link "add credit note to payment" + if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { + $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); + print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); + } else { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; + } + } else { // We can add a credit note on a down payment or standard invoice or situation invoice + // There is credit notes discounts available +// if (! $absolute_discount) print '
'; + // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); + $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher + } + } + if (! $absolute_discount && ! $absolute_creditnote) { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) print ' (' . $addabsolutediscount . ')
'; -// else -// print '. '; - } else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available -// if (! $absolute_discount) print '
'; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher + else + print '. '; } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
'; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } - print '
'.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'
'; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
'; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
' . $langs->trans('Discounts') . ''; + print '
' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); else @@ -1411,46 +1411,49 @@ if ($action == 'create') print ''; - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; - } + if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; - print ''; // Payment term print '
' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; -*/ - $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > SupplierProposal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - // Remise dispo de type remise fixe (not credit note) -// print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; } + + $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; + $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; + $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + + print '
' . $langs->trans('Discounts') . ''; +/* // TODO handle supplier relative discount + if ($soc->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print '. '; +*/ + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + if ($absolute_discount) { + if ($object->statut > SupplierProposal::STATUS_DRAFT) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); + } else { + // Remise dispo de type remise fixe (not credit note) +// print '
'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); + } + } + if ($absolute_creditnote) { + print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; + } + if (! $absolute_discount && ! $absolute_creditnote) + print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + print '
'; From 95be1550100ff94cc1a1529c21dccbb536f5452f Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 20 Feb 2018 12:26:29 +0100 Subject: [PATCH 17/91] FIX: supplier credit notes: harmonize discount filters --- htdocs/comm/card.php | 2 +- htdocs/comm/propal/card.php | 15 +++++++++++---- htdocs/commande/card.php | 4 ++-- htdocs/compta/facture/prelevement.php | 16 ++++++++++++---- htdocs/core/class/html.form.class.php | 12 ++++++------ htdocs/expedition/shipment.php | 14 +++++++++++--- htdocs/fourn/commande/card.php | 4 ++-- htdocs/societe/class/api_thirdparties.class.php | 10 ++++++++-- htdocs/supplier_proposal/card.php | 4 ++-- 9 files changed, 55 insertions(+), 26 deletions(-) diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index d732a10a347..81443f04d62 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -392,7 +392,7 @@ if ($object->id > 0) print '
'; print '
'; - $amount_discount=$object->getAvailableDiscounts(); // TODO adapt to supplier discounts + $amount_discount=$object->getAvailableDiscounts(); if ($amount_discount < 0) dol_print_error($db,$object->error); if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; //else print $langs->trans("DiscountNone"); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 54e3cf36c45..4291b22508d 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1873,14 +1873,22 @@ if ($action == 'create') print ''; // Link for thirdparty discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + print ''; - } - $db->free($resql); - print "
' . $langs->trans('Discounts') . ''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; - $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL'); - $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL'); + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); if ($absolute_discount) { @@ -1888,9 +1896,8 @@ if ($action == 'create') print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 0, 0, -1, $conf->currency)); } else { // Remise dispo de type non avoir - $filter = 'fk_facture_source IS NULL'; print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filter, 0, '', 1); + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); } } if ($absolute_creditnote) { diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index a56dc6cd5ac..6cd21df9c78 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -2041,8 +2041,8 @@ if ($action == 'create' && $user->rights->commande->creer) $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 989e742afee..6065ad9cd6f 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -140,8 +140,16 @@ if ($object->id > 0) if ($object->paye) $resteapayer=0; $resteapayeraffiche=$resteapayer; - $absolute_discount=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NULL'); - $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NOT NULL'); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + + $absolute_discount=$object->thirdparty->getAvailableDiscounts('',$filterabsolutediscount); + $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); @@ -282,7 +290,7 @@ if ($object->id > 0) else { // Remise dispo de type non avoir - $filter='fk_facture_source IS NULL'; + $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filter,$resteapayer,'',1); } @@ -302,7 +310,7 @@ if ($object->id > 0) else { // Remise dispo de type avoir - $filter='fk_facture_source IS NOT NULL'; + $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NOT NULL':"fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; if (! $absolute_discount) print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filter,$resteapayer,'',1); } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index f65a3bec36c..aafe9b81cc1 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4235,23 +4235,23 @@ class Form if(! empty($discount_type)) { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_invoice_supplier IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } else { - if (! $filter || $filter=="fk_invoice_supplier IS NOT NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } } else { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_facture IS NOT NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } else { - if (! $filter || $filter=="fk_facture IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); } } @@ -4271,9 +4271,9 @@ class Form if ($nbqualifiedlines > 0) { print '   '; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index a358d349531..cf0cc1d6d24 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -329,12 +329,20 @@ if ($id > 0 || ! empty($ref)) print ''; // Discounts for third party + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + print '"; print ''; + + if($conf->global->MAIN_FEATURES_LEVEL > 0) { + // Absolute discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + print ''; + } print ''; print ''; if ($conf->global->MAIN_FEATURES_LEVEL > 0) { From 876ea3198f735e511a8d1aa47680a908c256065e Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 17:51:44 +0100 Subject: [PATCH 21/91] FIX: handle type in supplier invoice list --- htdocs/fourn/facture/list.php | 49 ++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 31d6ba2f183..75dee1422d2 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -76,6 +76,7 @@ $search_amount_all_tax = GETPOST("search_amount_all_tax","alpha"); $search_product_category=GETPOST('search_product_category','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); $search_refsupplier=GETPOST('search_refsupplier','alpha'); +$search_type=GETPOST('search_type','int'); $search_project=GETPOST('search_project','alpha'); $search_societe=GETPOST('search_societe','alpha'); $search_montant_ht=GETPOST('search_montant_ht','alpha'); @@ -148,6 +149,7 @@ $checkedtypetiers=0; $arrayfields=array( 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), 'f.label'=>array('label'=>$langs->trans("Label"), 'checked'=>0), 'f.datef'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), @@ -203,6 +205,7 @@ if (empty($reshook)) $search_product_category=''; $search_ref=""; $search_refsupplier=""; + $search_type=""; $search_label=""; $search_project=''; $search_societe=""; @@ -261,7 +264,7 @@ llxHeader('',$langs->trans("SuppliersInvoices"),'EN:Suppliers_Invoices|FR:Factur $sql = "SELECT"; if ($search_all || $search_product_category > 0) $sql = 'SELECT DISTINCT'; -$sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_reglement,"; +$sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_reglement,"; $sql.= " f.total_ht, f.total_ttc, f.total_tva as total_vat, f.paye as paye, f.fk_statut as fk_statut, f.libelle as label, f.datec as date_creation, f.tms as date_update,"; $sql.= " f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,"; $sql.= " s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta as code_compta_client, s.code_compta_fournisseur,"; @@ -307,6 +310,15 @@ if ($search_ref) } if ($search_ref) $sql .= natural_search('f.ref', $search_ref); if ($search_refsupplier) $sql .= natural_search('f.ref_supplier', $search_refsupplier); +if ($search_type != '' && $search_type >= 0) +{ + if ($search_type == '0') $sql.=" AND f.type = 0"; // standard + if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement + if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note + if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit + //if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma + //if ($search_type == '5') $sql.=" AND f.type = 5"; // situation +} if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_town) $sql.= natural_search('s.town', $search_town); @@ -377,7 +389,7 @@ $sql.=$hookmanager->resPrint; if (! $search_all) { - $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; + $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; $sql.= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; $sql.= " f.localtax1, f.localtax2,"; $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,'; @@ -434,6 +446,7 @@ if ($resql) if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); if ($search_ref) $param.='&search_ref='.urlencode($search_ref); if ($search_refsupplier) $param.='&search_refsupplier='.urlencode($search_refsupplier); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); if ($search_label) $param.='&search_label='.urlencode($search_label); if ($search_company) $param.='&search_company='.urlencode($search_company); if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); @@ -590,6 +603,26 @@ if ($resql) print ''; print ''; } + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print ''; + } // Label if (! empty($arrayfields['f.label']['checked'])) { @@ -741,6 +774,7 @@ if ($resql) print ''; if (! empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'],$_SERVER['PHP_SELF'],'f.ref,f.rowid','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['f.ref_supplier']['label'],$_SERVER["PHP_SELF"],'f.ref_supplier','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.label']['checked'])) print_liste_field_titre($arrayfields['f.label']['label'],$_SERVER['PHP_SELF'],"f.libelle,f.rowid",'',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.datef']['checked'])) print_liste_field_titre($arrayfields['f.datef']['label'],$_SERVER['PHP_SELF'],'f.datef,f.rowid','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); @@ -767,7 +801,7 @@ if ($resql) print $hookmanager->resPrint; if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; @@ -843,6 +877,15 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } + + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print '"; + if (! $i) $totalarray['nbfield']++; + } // Label if (! empty($arrayfields['f.label']['checked'])) From 7ca5ac03ccb5a758434b70b7537bf8676dcda968 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 26 Feb 2018 17:40:31 +0100 Subject: [PATCH 22/91] FIX: discount card: only display relevant discounts types (customer/supplier) --- htdocs/comm/remx.php | 663 ++++++++++++++++-------------- htdocs/langs/en_US/companies.lang | 1 + 2 files changed, 351 insertions(+), 313 deletions(-) diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 177b4456912..92e2f1d5d71 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -235,12 +235,17 @@ if ($socid > 0) $object = new Societe($db); $object->fetch($socid); + $isCustomer = $object->client == 1 || $object->client == 3; + $isSupplier = $object->fournisseur == 1; + + $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; + $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; + /* * Display tabs */ $head = societe_prepare_head($object); - print ''; print ''; print ''; @@ -253,39 +258,54 @@ if ($socid > 0) print '
'; print '
'; + + if(! $displayCustomer && ! $displaySupplier) { + print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; + + dol_fiche_end(); + + print ''; + + llxFooter(); + $db->close(); + exit; + } + + print '
'.$langs->trans('Discounts').''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; - $absolute_discount=$soc->getAvailableDiscounts('','fk_facture_source IS NULL'); - $absolute_creditnote=$soc->getAvailableDiscounts('','fk_facture_source IS NOT NULL'); + $absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount); + $absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); if ($absolute_discount) @@ -346,7 +354,7 @@ if ($id > 0 || ! empty($ref)) else { // Remise dispo de type non avoir - $filter='fk_facture_source IS NULL'; + $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filter, 0, '', 1); } diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 6cd17690c24..0111a8d11c7 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1888,8 +1888,8 @@ elseif (! empty($object->id)) $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index fa52c73f597..49901c420f0 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -83,8 +83,14 @@ class Thirdparties extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + $absolute_discount = $this->company->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $this->company->getAvailableDiscounts('', $filtercreditnote); $this->company->absolute_discount = price2num($absolute_discount, 'MT'); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 17e5a2be199..259d3d0a5ca 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1418,8 +1418,8 @@ if ($action == 'create') $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (fk_invoice_supplier_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; From d3f848b7bc7b3a957bc522eba8aecd934467033e Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 09:30:39 +0100 Subject: [PATCH 18/91] FIX: supplier credit notes: harmonize discount filters part 2 --- htdocs/compta/facture/prelevement.php | 6 ++---- htdocs/expedition/shipment.php | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 6065ad9cd6f..01f2ff6aa27 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -290,9 +290,8 @@ if ($object->id > 0) else { // Remise dispo de type non avoir - $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filter,$resteapayer,'',1); + $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filterabsolutediscount,$resteapayer,'',1); } } if ($absolute_creditnote > 0) @@ -310,9 +309,8 @@ if ($object->id > 0) else { // Remise dispo de type avoir - $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NOT NULL':"fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; if (! $absolute_discount) print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filter,$resteapayer,'',1); + $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filtercreditnote,$resteapayer,'',1); } } if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index cf0cc1d6d24..7b0cca64a30 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -354,9 +354,8 @@ if ($id > 0 || ! empty($ref)) else { // Remise dispo de type non avoir - $filter=!empty($cong->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)?'fk_facture_source IS NULL':"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filter, 0, '', 1); + $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filterabsolutediscount, 0, '', 1); } } if ($absolute_creditnote) From cfdbef6bc30f38b8a945bb9e5a826d05854b66d0 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 09:31:01 +0100 Subject: [PATCH 19/91] NEW: supplier credit notes: display supplier discounts in supplier card --- htdocs/fourn/card.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 588c13ca849..60f745d95c7 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -255,6 +255,28 @@ if ($object->id > 0) } print "
'; + print ''; + print '
'; + print $langs->trans("CustomerAbsoluteDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
'; + print '
'; + $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); + if ($amount_discount < 0) dol_print_error($db,$object->error); + if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; + //else print $langs->trans("DiscountNone"); + print '
'; From 34d84c6d5dde9c664fed7c8726f9df75ed8be61a Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 21 Feb 2018 17:15:16 +0100 Subject: [PATCH 20/91] FIX: supplier credit notes: display link to discount in supplier credit note card --- htdocs/fourn/facture/card.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 0344890458b..c1c04489f1d 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2409,6 +2409,13 @@ else $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $discount = new DiscountAbsolute($db); + $result = $discount->fetch(0, 0, $object->id); + if ($result > 0){ + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
'; + } + } print '
'; + $listtype=array( + FactureFournisseur::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), + FactureFournisseur::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), + FactureFournisseur::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), + FactureFournisseur::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), + ); +/* + if (! empty($conf->global->INVOICE_USE_SITUATION)) + { + $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); + } +*/ + //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. + print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); + print '
'; + print $facturestatic->getLibType(); + print "
'; - // Calcul avoirs client en cours - $remise_all=$remise_user=0; - $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND discount_type = 0"; // Exclude supplier discounts - $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; - $sql.= " GROUP BY rc.fk_user"; - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $remise_all+=$obj->amount; - if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; - } - else - { - dol_print_error($db); + if($displayCustomer) { // Calcul avoirs client en cours + $remise_all=$remise_user=0; + $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 0"; // Exclude supplier discounts + $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; + $sql.= " GROUP BY rc.fk_user"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $remise_all+=$obj->amount; + if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + } + else + { + dol_print_error($db); + } + + print ''; + print ''; + + if (! empty($user->fk_soc)) // No need to show this for external users + { + print ''; + print ''; + } } - print ''; - print ''; - - if (! empty($user->fk_soc)) // No need to show this for external users - { - print ''; - print ''; - } - - if($conf->global->MAIN_FEATURES_LEVEL > 0) { + if($displaySupplier) { // Calcul avoirs fournisseur en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; @@ -328,9 +348,18 @@ if ($socid > 0) print load_fiche_titre($langs->trans("NewGlobalDiscount"),'',''); print '
'; + + if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + print ''; + } + + if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + print ''; + } + print '
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'; - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; + if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + print ''; print ''; @@ -378,144 +407,147 @@ if ($socid > 0) */ print load_fiche_titre($langs->trans("DiscountStillRemaining")); - - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print '
'; - print '
'; - } - $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql.= " rc.datec as dc, rc.description,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " fa.facnumber as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user"; - $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; - $sql.= " ORDER BY rc.datec DESC"; - - $resql=$db->query($sql); - if ($resql) - { - if($conf->global->MAIN_FEATURES_LEVEL > 0) { + if($displayCustomer) { + if($displaySupplier) { + print '
'; + print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } - print '
'.$langs->trans('DiscountType').'
'.$langs->trans('DiscountType').' '; print ' '; print '
'; - print ''; - print ''; // Need 120+ for format with AM/PM - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $showconfirminfo=array(); - - $i = 0; - $num = $db->num_rows($resql); - if ($num > 0) + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description,"; + $sql.= " rc.fk_facture_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " fa.facnumber as ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) { - while ($i < $num) - { - $obj = $db->fetch_object($resql); - - print ''; - print ''; - if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - if ($user->rights->societe->creer || $user->rights->facture->creer) - { - print ''; - } - else print ''; - print ''; - - if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) - { - $showconfirminfo['rowid']=$obj->rowid; - $showconfirminfo['amount_ttc']=$obj->amount_ttc; - } - $i++; - } + print '
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - print $obj->description; - print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; - print ''; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; - print '   '; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; - print ' 
'; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $showconfirminfo=array(); + + $i = 0; + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + if ($user->rights->societe->creer || $user->rights->facture->creer) + { + print ''; + } + else print ''; + print ''; + + if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + { + $showconfirminfo['rowid']=$obj->rowid; + $showconfirminfo['amount_ttc']=$obj->amount_ttc; + } + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + print $obj->description; + print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print '   '; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print ' 
'.$langs->trans("None").'
"; + + if (count($showconfirminfo)) + { + $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); + $amount2=($showconfirminfo['amount_ttc']-$amount1); + $formquestion=array( + 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), + array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), + array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') + ); + $langs->load("dict"); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + } } else { - print '
'.$langs->trans("None").'
"; - - if (count($showconfirminfo)) - { - $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); - $amount2=($showconfirminfo['amount_ttc']-$amount1); - $formquestion=array( - 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), - array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), - array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') - ); - $langs->load("dict"); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + dol_print_error($db); } } - else - { - dol_print_error($db); - } - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; // class="fichehalfleft" - print '
'; - print '
'; + if($displaySupplier) { + if($displayCustomer) { + print '
'; // class="fichehalfleft" + print '
'; + print '
'; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } /* * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture) @@ -537,7 +569,6 @@ if ($socid > 0) $resql=$db->query($sql); if ($resql) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print ''; print ''; print ''; // Need 120+ for format with AM/PM @@ -646,9 +677,11 @@ if ($socid > 0) dol_print_error($db); } - print ''; // class="ficheaddleft" - print ''; // class="fichehalfright" - print ''; // class="fichecenter" + if($displayCustomer) { + print ''; // class="ficheaddleft" + print ''; // class="fichehalfright" + print ''; // class="fichecenter" + } } print '
'; @@ -659,161 +692,164 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print '
'; - print '
'; - } - - // Remises liees a lignes de factures - $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " f.rowid, f.facnumber,"; - $sql.= " fa.facnumber as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " , ".MAIN_DB_PREFIX."user as u"; - $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; - $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc =". $object->id; - $sql.= " AND rc.fk_facture_line = fc.rowid"; - $sql.= " AND fc.fk_facture = f.rowid"; - $sql.= " AND rc.fk_user = u.rowid"; - $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql.= " ORDER BY dc DESC"; - //$sql.= " UNION "; - // Remises liees a factures - $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql2.= " rc.fk_facture_source,"; - $sql2.= " u.login, u.rowid as user_id,"; - $sql2.= " f.rowid, f.facnumber,"; - $sql2.= " fa.facnumber as ref, fa.type as type"; - $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql2.= " , ".MAIN_DB_PREFIX."user as u"; - $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql2.= " WHERE rc.fk_soc =". $object->id; - $sql2.= " AND rc.fk_facture = f.rowid"; - $sql2.= " AND rc.fk_user = u.rowid"; - $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql2.= " ORDER BY dc DESC"; - - $resql=$db->query($sql); - $resql2=null; - if ($resql) $resql2=$db->query($sql2); - if ($resql2) - { - if($conf->global->MAIN_FEATURES_LEVEL > 0) { + if($displayCustomer) { + if($displaySupplier) { + print '
'; + print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } - print '
'.$langs->trans("Date").'
'; - print ''; - print ''; // Need 120+ for format with AM/PM - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $tab_sqlobj=array(); - $tab_sqlobjOrder=array(); - $num = $db->num_rows($resql); - if ($num > 0) + // Remises liees a lignes de factures + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql.= " rc.fk_facture_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " f.rowid, f.facnumber,"; + $sql.= " fa.facnumber as ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= " , ".MAIN_DB_PREFIX."user as u"; + $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; + $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc =". $object->id; + $sql.= " AND rc.fk_facture_line = fc.rowid"; + $sql.= " AND fc.fk_facture = f.rowid"; + $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql.= " ORDER BY dc DESC"; + //$sql.= " UNION "; + // Remises liees a factures + $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql2.= " rc.fk_facture_source,"; + $sql2.= " u.login, u.rowid as user_id,"; + $sql2.= " f.rowid, f.facnumber,"; + $sql2.= " fa.facnumber as ref, fa.type as type"; + $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql2.= " , ".MAIN_DB_PREFIX."user as u"; + $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql2.= " WHERE rc.fk_soc =". $object->id; + $sql2.= " AND rc.fk_facture = f.rowid"; + $sql2.= " AND rc.fk_user = u.rowid"; + $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql2.= " ORDER BY dc DESC"; + + $resql=$db->query($sql); + $resql2=null; + if ($resql) $resql2=$db->query($sql2); + if ($resql2) { - for ($i = 0;$i < $num; $i++) - { - $sqlobj = $db->fetch_object($resql); - $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); - } - } - $db->free($resql); - - $num = $db->num_rows($resql2); - for ($i = 0;$i < $num;$i++) - { - $sqlobj = $db->fetch_object($resql2); - $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); - } - $db->free($resql2); - array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); - - $num = count($tab_sqlobj); - if ($num > 0) - { - $i = 0 ; - while ($i < $num ) - { - $obj = array_shift($tab_sqlobj); - print ''; - print ''; - if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i++; - } + print '
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - print $obj->description; - print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; - print ' 
'; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $tab_sqlobj=array(); + $tab_sqlobjOrder=array(); + $num = $db->num_rows($resql); + if ($num > 0) + { + for ($i = 0;$i < $num; $i++) + { + $sqlobj = $db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + } + } + $db->free($resql); + + $num = $db->num_rows($resql2); + for ($i = 0;$i < $num;$i++) + { + $sqlobj = $db->fetch_object($resql2); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + } + $db->free($resql2); + array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); + + $num = count($tab_sqlobj); + if ($num > 0) + { + $i = 0 ; + while ($i < $num ) + { + $obj = array_shift($tab_sqlobj); + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + print $obj->description; + print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ' 
'.$langs->trans("None").'
"; } else { - print '
'.$langs->trans("None").'
"; - } - else - { - dol_print_error($db); } - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - print ''; // class="fichehalfleft" - print '
'; - print '
'; + if($displaySupplier) { + if($displayCustomer) { + print '
'; // class="fichehalfleft" + print '
'; + print '
'; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } // Remises liees a lignes de factures $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; @@ -856,7 +892,6 @@ if ($socid > 0) if ($resql) $resql2=$db->query($sql2); if ($resql2) { - print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); print ''; print ''; print ''; // Need 120+ for format with AM/PM @@ -958,10 +993,12 @@ if ($socid > 0) { dol_print_error($db); } - - print ''; // class="ficheaddleft" - print ''; // class="fichehalfright" - print ''; // class="fichecenter" + + if($displayCustomer) { + print ''; // class="ficheaddleft" + print ''; // class="fichehalfright" + print ''; // class="fichecenter" + } } } diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 2eb1ba88e57..dde515c0223 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -79,6 +79,7 @@ VATIsUsed=Sales tax is used VATIsNotUsed=Sales tax is not used CopyAddressFromSoc=Fill address with third party address ThirdpartyNotCustomerNotSupplierSoNoRef=Thirdparty neither customer nor supplier, no available refering objects +ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts=Thirdparty neither customer nor supplier, discounts are not available PaymentBankAccount=Payment bank account OverAllProposals=Proposals OverAllOrders=Orders From 239e83491333c71d705f6666818a98352e7a86b1 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 27 Feb 2018 10:03:51 +0100 Subject: [PATCH 23/91] FIX: supplier credit notes: remove handled TODO --- htdocs/fourn/class/fournisseur.facture.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 570966d8600..7c0159c814f 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -2730,7 +2730,7 @@ class SupplierInvoiceLine extends CommonObjectLine $this->error = $this->db->lasterror(); } } - // TODO free discount linked to line as in customer invoice + if (! $error) { $this->db->commit(); From 9cf45266f5e7849e9b3c3827b7ff9255ddb5901e Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Tue, 27 Feb 2018 16:30:39 +0100 Subject: [PATCH 24/91] NEW: supplier relative discounts --- htdocs/comm/remise.php | 219 ++++++++++++++---- htdocs/core/tpl/objectline_create.tpl.php | 6 +- htdocs/fourn/card.php | 13 ++ htdocs/fourn/commande/card.php | 25 +- htdocs/fourn/facture/card.php | 43 ++-- .../install/mysql/migration/7.0.0-8.0.0.sql | 15 +- htdocs/install/mysql/tables/llx_societe.sql | 1 + .../tables/llx_societe_remise_supplier.sql | 34 +++ htdocs/langs/en_US/companies.lang | 2 + htdocs/societe/card.php | 2 +- .../societe/class/api_thirdparties.class.php | 2 +- htdocs/societe/class/societe.class.php | 65 +++++- htdocs/supplier_proposal/card.php | 24 +- 13 files changed, 351 insertions(+), 100 deletions(-) create mode 100644 htdocs/install/mysql/tables/llx_societe_remise_supplier.sql diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index 1ad4612d879..bc87c2e65fc 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -56,7 +56,14 @@ if (GETPOST('action','aZ09') == 'setremise') { $object = new Societe($db); $object->fetch($id); - $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user); + + $discount_type = GETPOST('discount_type', 'int'); + + if(! empty($discount_type)) { + $result=$object->set_remise_supplier(price2num(GETPOST("remise")),GETPOST("note"),$user); + } else { + $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user); + } if ($result > 0) { @@ -100,6 +107,11 @@ if ($socid > 0) $head = societe_prepare_head($object); + $isCustomer = $object->client == 1 || $object->client == 3; + $isSupplier = $object->fournisseur == 1; + + $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; + $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; print '
'; @@ -114,20 +126,58 @@ if ($socid > 0) print '
'; print '
'; + + if(! $displayCustomer && ! $displaySupplier) { + print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; + + dol_fiche_end(); + + print ''; + + llxFooter(); + $db->close(); + exit; + } + print '
'.$langs->trans("Date").'
'; - // Discount - print '"; + if($displayCustomer) { + // Customer discount + print '"; + } + + if($displaySupplier) { + // Supplier discount + print '"; + } + print '
'; - print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
'; + print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
'; + print $langs->trans("SupplierRelativeDiscount").''.price2num($object->remise_supplier_percent)."%
'; print '
'; print load_fiche_titre($langs->trans("NewRelativeDiscount"),'',''); print '
'; + + if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + print ''; + } + + if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + print ''; + } print ''; + if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + // Discount type + print ''; + print ''; + } + // New value print ''; @@ -155,57 +205,128 @@ if ($socid > 0) print '
'; + if($displayCustomer) { + if($displaySupplier) { + print '
'; + print '
'; + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); + } - /* - * List log of all percent discounts - */ - $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; - $sql.= " u.login, u.rowid as user_id"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user_author"; - $sql.= " ORDER BY rc.datec DESC"; - - $resql=$db->query($sql); - if ($resql) - { - print '
'.$langs->trans('DiscountType').' '; + print ' '; + print '
'; print $langs->trans("NewValue").'%
'; - $tag = !$tag; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $num = $db->num_rows($resql); - if ($num > 0) - { - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i++; - } + /* + * List log of all customer percent discounts + */ + $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; + $sql.= " u.login, u.rowid as user_id"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user_author"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print '
'.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'; + $tag = !$tag; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $num = $db->num_rows($resql); + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'.$langs->trans("None").'
"; } else { - print '
'.$langs->trans("None").'
"; - } - else - { - dol_print_error($db); + dol_print_error($db); + } } + if($displaySupplier) { + if($displayCustomer) { + print ''; // class="fichehalfleft" + print '
'; + print '
'; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } + + /* + * List log of all supplier percent discounts + */ + $sql = "SELECT rc.rowid, rc.remise_supplier as remise_percent, rc.note, rc.datec as dc,"; + $sql.= " u.login, u.rowid as user_id"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_supplier as rc, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user_author"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print ''; + $tag = !$tag; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $num = $db->num_rows($resql); + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'.$langs->trans("None").'
"; + } + else + { + dol_print_error($db); + } + + if($displayCustomer) { + print '
'; // class="ficheaddleft" + print '
'; // class="fichehalfright" + print ''; // class="fichecenter" + } + } } llxFooter(); diff --git a/htdocs/core/tpl/objectline_create.tpl.php b/htdocs/core/tpl/objectline_create.tpl.php index d26a31b3cd2..103e557eb7c 100644 --- a/htdocs/core/tpl/objectline_create.tpl.php +++ b/htdocs/core/tpl/objectline_create.tpl.php @@ -322,8 +322,12 @@ else { print $form->selectUnits($line->fk_unit, "units"); print '
remise_percent); ?>">%">%
'; + print '
'; + print $langs->trans("CustomerRelativeDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
'; + print '
'.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').'
'; print ''; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 0111a8d11c7..88d654a8924 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1398,7 +1398,7 @@ if ($action=='create') $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; @@ -1436,7 +1436,7 @@ if ($action=='create') print ''; print ''; print '' . "\n"; - print ''; + print ''; print ''; print ''; if (!empty($currency_tx)) print ''; @@ -1479,17 +1479,16 @@ if ($action=='create') if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) { -/* // TODO handle supplier relative discount // Discounts for third party print ''; } - + // Label print ''; print ''; diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index bfc2c79a679..4071356c982 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -35,4 +35,17 @@ ALTER TABLE llx_projet ADD COLUMN bill_time integer DEFAULT 0; ALTER TABLE llx_societe ADD COLUMN order_min_amount double(24,8) DEFAULT NULL AFTER outstanding_limit; ALTER TABLE llx_societe ADD COLUMN supplier_order_min_amount double(24,8) DEFAULT NULL AFTER order_min_amount; -ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; \ No newline at end of file +ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; +ALTER TABLE llx_societe ADD COLUMN remise_supplier real DEFAULT 0 AFTER remise_client; +CREATE TABLE llx_societe_remise_supplier +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + fk_soc integer NOT NULL, + tms timestamp, + datec datetime, -- creation date + fk_user_author integer, -- creation user + remise_supplier double(6,3) DEFAULT 0 NOT NULL, -- discount + note text + +)ENGINE=innodb; \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_societe.sql b/htdocs/install/mysql/tables/llx_societe.sql index 9ffb9734d7f..f1714021fb8 100644 --- a/htdocs/install/mysql/tables/llx_societe.sql +++ b/htdocs/install/mysql/tables/llx_societe.sql @@ -78,6 +78,7 @@ create table llx_societe customer_rate real DEFAULT 0, -- taux fiabilite client (0 a 1) supplier_rate real DEFAULT 0, -- taux fiabilite fournisseur (0 a 1) remise_client real DEFAULT 0, -- remise systematique pour le client + remise_supplier real DEFAULT 0, -- remise systematique auprès du fournisseur mode_reglement tinyint, -- mode de reglement cond_reglement tinyint, -- condition de reglement mode_reglement_supplier tinyint, -- mode de reglement fournisseur diff --git a/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql b/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql new file mode 100644 index 00000000000..c1b56f225c7 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql @@ -0,0 +1,34 @@ +-- ======================================================================== +-- Copyright (C) 2000-2004 Rodolphe Quiedeville +-- Copyright (C) 2011-2016 Regis Houssin +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- +-- Historique evolution de la remise relative des tiers +-- ======================================================================== + +create table llx_societe_remise_supplier +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + fk_soc integer NOT NULL, + tms timestamp, + datec datetime, -- creation date + fk_user_author integer, -- creation user + remise_supplier double(6,3) DEFAULT 0 NOT NULL, -- discount + note text + +)ENGINE=innodb; + diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index dde515c0223..aab3ee183da 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -268,6 +268,8 @@ CustomerRelativeDiscountShort=Relative discount CustomerAbsoluteDiscountShort=Absolute discount CompanyHasRelativeDiscount=This customer has a default discount of %s%% CompanyHasNoRelativeDiscount=This customer has no relative discount by default +HasRelativeDiscountFromSupplier=You have a default discount of %s%% from this supplier +HasNoRelativeDiscountFromSupplier=You have no default relative discount from this supplier CompanyHasAbsoluteDiscount=This customer has discount available (credits notes or down payments) for %s %s CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index dcacf89d643..94fe7436041 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -149,7 +149,7 @@ if (empty($reshook)) $listofproperties=array( 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', - 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', + 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', 'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency', 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur', 'model_pdf', 'fk_projet' diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 49901c420f0..1cdfabf7fca 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -314,7 +314,7 @@ class Thirdparties extends DolibarrApi $listofproperties=array( 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', - 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', + 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', 'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency', 'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur', 'model_pdf', 'fk_projet' diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 4bf2dbd0dab..ddf6f5c509a 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -234,6 +234,7 @@ class Societe extends CommonObject var $forme_juridique; var $remise_percent; + var $remise_supplier_percent; var $mode_reglement_supplier_id; var $cond_reglement_supplier_id; var $fk_prospectlevel; @@ -1143,7 +1144,7 @@ class Societe extends CommonObject $sql .= ', s.fk_forme_juridique as forme_juridique_code'; $sql .= ', s.webservices_url, s.webservices_key'; $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode'; - $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj'; + $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj'; $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo'; $sql .= ', s.fk_shipping_method'; $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms'; @@ -1275,6 +1276,7 @@ class Societe extends CommonObject $this->prefix_comm = $obj->prefix_comm; $this->remise_percent = $obj->remise_client; + $this->remise_supplier_percent = $obj->remise_supplier; $this->mode_reglement_id = $obj->mode_reglement; $this->cond_reglement_id = $obj->cond_reglement; $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier; @@ -1657,6 +1659,67 @@ class Societe extends CommonObject return 1; } } + + /** + * Definit la societe comme un client + * + * @param float $remise Valeur en % de la remise + * @param string $note Note/Motif de modification de la remise + * @param User $user Utilisateur qui definie la remise + * @return int <0 if KO, >0 if OK + */ + function set_remise_supplier($remise, $note, User $user) + { + global $conf, $langs; + + // Nettoyage parametres + $note=trim($note); + if (! $note) + { + $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason")); + return -2; + } + + dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id); + + if ($this->id) + { + $this->db->begin(); + + $now=dol_now(); + + // Positionne remise courante + $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; + $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'"; + $sql.= " WHERE rowid = " . $this->id; + $resql=$this->db->query($sql); + if (! $resql) + { + $this->db->rollback(); + $this->error=$this->db->error(); + return -1; + } + + // Ecrit trace dans historique des remises + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier"; + $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)"; + $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; + $sql.= " '".$this->db->escape($note)."',"; + $sql.= " ".$user->id; + $sql.= ")"; + + $resql=$this->db->query($sql); + if (! $resql) + { + $this->db->rollback(); + $this->error=$this->db->lasterror(); + return -1; + } + + $this->db->commit(); + return 1; + } + } /** * Add a discount for third party diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 259d3d0a5ca..93bf576ef71 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -995,7 +995,7 @@ if ($action == 'create') $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); // Replicate extrafields @@ -1052,15 +1052,15 @@ if ($action == 'create') { // Discounts for third party print ''; print ""; - print '"; + print '"; print '"; print ""; //} @@ -972,7 +972,7 @@ if (empty($action) || $action == 'view') { print "'; print ""; - print '"; + print '"; print '"; print ""; } From e07177fec2367c56ad60ee2980993625d81b05dd Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Thu, 1 Mar 2018 12:31:33 +0100 Subject: [PATCH 26/91] FIX: supplier relativ discounts: pre-fill newlines with qty/discount --- htdocs/core/class/html.form.class.php | 4 ++++ htdocs/core/tpl/objectline_create.tpl.php | 11 +++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 8648787bedf..16f72b2d837 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -2482,6 +2482,10 @@ class Form $opt = ''; } @@ -1884,29 +1880,17 @@ if ($action == 'create') } print ''; // Date of proposal diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index dabd44ae448..cf70d422130 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1558,17 +1558,14 @@ if ($action == 'create' && $user->rights->commande->creer) // Ligne info remises tiers print ''; } // Date @@ -2052,29 +2049,17 @@ if ($action == 'create' && $user->rights->commande->creer) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print ''; // Date diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 5062bc88f99..4ee9658c456 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2699,19 +2699,12 @@ if ($action == 'create') { // Discounts for third party print ''; } @@ -3363,84 +3356,14 @@ else if ($id > 0 || ! empty($ref)) print ''; // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - print ''; // Date invoice diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 01f2ff6aa27..e665eaf77d1 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -261,59 +261,13 @@ if ($object->id > 0) // Discounts print ''; // Date invoice diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 16f72b2d837..a98729ac055 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4239,26 +4239,27 @@ class Form if(! empty($discount_type)) { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice + else $translationKey = 'HasCreditNoteFromSupplier'; } else { - if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier'; + else $translationKey = 'HasCreditNoteFromSupplier'; } } else { if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice + else $translationKey = 'CompanyHasCreditNote'; } else { - if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount'; + else $translationKey = 'CompanyHasCreditNote'; } } + print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency)); if (empty($hidelist)) print ': '; print ''; if (empty($hidelist)) diff --git a/htdocs/core/tpl/object_discounts.tpl.php b/htdocs/core/tpl/object_discounts.tpl.php new file mode 100644 index 00000000000..e8accdc4d26 --- /dev/null +++ b/htdocs/core/tpl/object_discounts.tpl.php @@ -0,0 +1,104 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Needs the following variables defined: + * $object Proposal, order, invoice (including supplier versions) + * $thirdparty Thirdparty of object + * $absolute_discount Amount of fixed discounts available + * $absolute_creditnote Amount of credit notes available + * $discount_type 0 => Customer discounts, 1 => Supplier discounts + * $cannotApplyDiscount Set it to prevent form to apply discount + * $backtopage URL to come back to from discount modification pages + */ + +$classname = get_class($object); +$isInvoice = in_array($object->element, array('facture', 'invoice', 'facture_fourn', 'invoice_supplier')); +$isNewObject = empty($object->id) && empty($object->rowid); + +// Relative and absolute discounts +$addrelativediscount = '' . $langs->trans("EditRelativeDiscount") . ''; +$addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; +$viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; + +$fixedDiscount = $thirdparty->remise_percent; + +if(! empty($discount_type)) { + $fixedDiscount = $thirdparty->remise_supplier_percent; +} + +$translationKey = ! empty($discount_type) ? 'HasRelativeDiscountFromSupplier' : 'CompanyHasRelativeDiscount'; +if ($fixedDiscount > 0) + print $langs->trans($translationKey, $fixedDiscount).'.'; +else + print $langs->trans($translationKey).'.'; +if($isNewObject) print ' ('.$addrelativediscount.')'; + +// Is there is commercial discount or down payment available ? +if ($absolute_discount > 0) { + + if ($cannotApplyDiscount || ! $isInvoice || $isNewObject || $object->statut > $classname::STATUS_DRAFT || $object->type == $classname::TYPE_CREDIT_NOTE || $object->type == $classname::TYPE_DEPOSIT) { + $translationKey = ! empty($discount_type) ? 'HasAbsoluteDiscountFromSupplier' : 'CompanyHasAbsoluteDiscount'; + $text = $langs->trans($translationKey, price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)).'.'; + + if ($isInvoice && ! $isNewObject && $object->statut > $classname::STATUS_DRAFT && $object->type != $classname::TYPE_CREDIT_NOTE && $object->type != $classname::TYPE_DEPOSIT) { + $text = $form->textwithpicto($text, $langs->trans('AbsoluteDiscountUse')); + } + + if ($isNewObject) { + $text.= ' ('.$addabsolutediscount.')'; + } + + print '
'.$text; + } else { + // Discount available of type fixed amount (not credit note) + $more = '(' . $addabsolutediscount . ')'; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $thirdparty->id, $absolute_discount, $filterabsolutediscount, $resteapayer, $more, 0, $discount_type); + } +} + +// Is there credit notes availables ? +if ($absolute_creditnote > 0) { + + // If validated, we show link "add credit note to payment" + if ($cannotApplyDiscount || ! $isInvoice || $isNewObject || $object->statut != $classname::STATUS_VALIDATED || $object->type == $classname::TYPE_CREDIT_NOTE) { + $translationKey = ! empty($discount_type) ? 'HasCreditNoteFromSupplier' : 'CompanyHasCreditNote'; + $text = $langs->trans($translationKey, price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; + + if ($isInvoice && ! $isNewObject && $object->statut == $classname::STATUS_DRAFT && $object->type != $classname::TYPE_DEPOSIT) { + $text = $form->textwithpicto($text, $langs->trans('CreditNoteDepositUse')); + } + + if ($absolute_discount <= 0 || $isNewObject) { + $text.= '('.$addabsolutediscount.')'; + } + + print '
'.$text; + } else { // We can add a credit note on a down payment or standard invoice or situation invoice + // There is credit notes discounts available + $more = $isInvoice && ! $isNewObject ? ' (' . $viewabsolutediscount . ')' : ''; + $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $thirdparty->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, $discount_type); // We allow credit note even if amount is higher + } +} + +if($absolute_discount <= 0 && $absolute_creditnote <= 0) { + $translationKey = ! empty($discount_type) ? 'HasNoAbsoluteDiscountFromSupplier' : 'CompanyHasNoAbsoluteDiscount'; + print '
'.$langs->trans($translationKey).'.'; + + if ($isInvoice && $object->statut == $classname::STATUS_DRAFT && $object->type != $classname::TYPE_CREDIT_NOTE && $object->type != $classname::TYPE_DEPOSIT) { + print ' (' . $addabsolutediscount . ')'; + } +} + diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index f16ee1eac48..a9bb706c4d8 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -340,31 +340,17 @@ if ($id > 0 || ! empty($ref)) } print '
'; // Date diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 0026bfe8fe7..c7487f4cc51 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1483,22 +1483,14 @@ if ($action=='create') { // Discounts for third party print ''; } @@ -1892,37 +1884,19 @@ elseif (! empty($object->id)) $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 9f2610d093b..14909a1fc2e 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1920,20 +1920,11 @@ if ($action == 'create') // Discounts for third party print ''; } @@ -2421,89 +2412,15 @@ else print ''; if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - print ''; } diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index aab3ee183da..5a6d2d1fc52 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -273,6 +273,10 @@ HasNoRelativeDiscountFromSupplier=You have no default relative discount from thi CompanyHasAbsoluteDiscount=This customer has discount available (credits notes or down payments) for %s %s CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s +HasNoAbsoluteDiscountFromSupplier=You have no discount credit available from this supplier +HasAbsoluteDiscountFromSupplier=You have discounts available (credits notes or down payments) for %s %s from this supplier +HasDownPaymentOrCommercialDiscountFromSupplier=You have discounts available (commercial, down payments) for %s %s from this supplier +HasCreditNoteFromSupplier=You have credit notes for %s %s from this supplier CompanyHasNoAbsoluteDiscount=This customer has no discount credit available CustomerAbsoluteDiscountAllUsers=Absolute customer discounts (granted by all users) CustomerAbsoluteDiscountMy=Absolute customer discounts (granted by yourself) diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 75575bf087b..4e4611d4fd5 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1055,22 +1055,13 @@ if ($action == 'create') // Discounts for third party print ''; } @@ -1423,37 +1414,19 @@ if ($action == 'create') $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - - print ''; } From 6a4a3c9e824dc3ca2596929a9e5391589ea46085 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 10:58:19 +0100 Subject: [PATCH 28/91] NEW: supplier credit notes: remove MAIN_FEATURES_LEVEL --- htdocs/comm/remise.php | 26 ++-- htdocs/comm/remx.php | 35 +++--- htdocs/fourn/card.php | 64 +++++----- htdocs/fourn/commande/card.php | 47 ++++---- htdocs/fourn/facture/card.php | 194 +++++++++++++++--------------- htdocs/supplier_proposal/card.php | 47 ++++---- 6 files changed, 196 insertions(+), 217 deletions(-) diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index c961f6f43a7..8fb75c908d4 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -109,10 +109,6 @@ if ($socid > 0) $isCustomer = $object->client == 1 || $object->client == 3; $isSupplier = $object->fournisseur == 1; - - $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; - $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; - print '
'; print ''; @@ -127,7 +123,7 @@ if ($socid > 0) print '
'; - if(! $displayCustomer && ! $displaySupplier) { + if(! $isCustomer && ! $isSupplier) { print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; dol_fiche_end(); @@ -141,13 +137,13 @@ if ($socid > 0) print '
' . $langs->trans('Discounts') . ''; - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; -*/ + $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1897,13 +1896,13 @@ elseif (! empty($object->id)) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print '. '; -*/ + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1913,7 +1912,7 @@ elseif (! empty($object->id)) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) -// print '
'; + print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index c1c04489f1d..b1efc5cbfa5 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1625,7 +1625,7 @@ if ($action == 'create') $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; @@ -1917,15 +1917,15 @@ if ($action == 'create') { // Discounts for third party print '
' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $societe->remise_percent . ''); + + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; -*/ + if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); else @@ -2428,17 +2428,17 @@ else print '
' . $langs->trans('Discounts'); print ''; -/* // TODO handle supplier relative discount - if ($societe->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $societe->remise_percent); + + if ($societe->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print ' ('.$addrelativediscount.')'; -*/ + print $langs->trans("HasNoRelativeDiscountFromSupplier"); + // print ' ('.$addrelativediscount.')'; + // Is there is commercial discount or down payment available ? if ($absolute_discount > 0) { -// print '. '; + print '. '; if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { if ($object->statut == 0) { print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); @@ -2446,7 +2446,7 @@ else } else { if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '' . $text . '.
'; + print '
' . $text . '.
'; } else { $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); $text2 = $langs->trans("AbsoluteDiscountUse"); @@ -2455,7 +2455,7 @@ else } } else { // Discount available of type fixed amount (not credit note) -// print '
'; + print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); } } else { @@ -2463,10 +2463,11 @@ else { if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) print ' (' . $addabsolutediscount . ')
'; -// else -// print '. '; - } else - print '. '; + else + print '. '; + } + else + print '. '; } // Is there credit notes availables ? if ($absolute_creditnote > 0) @@ -2481,7 +2482,7 @@ else } } else { // We can add a credit note on a down payment or standard invoice or situation invoice // There is credit notes discounts available -// if (! $absolute_discount) print '
'; + if (! $absolute_discount) print '
'; // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher @@ -2503,7 +2504,7 @@ else // } print '
'.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'
' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + + if ($soc->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", '' . $soc->remise_supplier_percent . ''); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print ' (' . $langs->trans("EditRelativeDiscount") . ')'; print '. '; print '
'; -*/ + $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); if ($absolute_discount) @@ -1427,13 +1427,13 @@ if ($action == 'create') $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
' . $langs->trans('Discounts') . ''; -/* // TODO handle supplier relative discount - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + + if ($soc->remise_supplier_percent) + print $langs->trans("HasRelativeDiscountFromSupplier", $soc->remise_supplier_percent); else - print $langs->trans("CompanyHasNoRelativeDiscount"); + print $langs->trans("HasNoRelativeDiscountFromSupplier"); print '. '; -*/ + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -1443,7 +1443,7 @@ if ($action == 'create') print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); } else { // Remise dispo de type remise fixe (not credit note) -// print '
'; + print '
'; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); } } From 24ffce0be5393216186470e168db83be8371ec9b Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Thu, 1 Mar 2018 11:20:42 +0100 Subject: [PATCH 25/91] FIX: supplier credit notes: accounting display in purchases journal --- htdocs/accountancy/journal/purchasesjournal.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index ec21937c8ff..698b121ea7c 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -878,7 +878,7 @@ if (empty($action) || $action == 'view') { else print $accountoshow; print '
" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->ref_supplier . ' - ' . $langs->trans("SubledgerAccount") . "' . ($mt < 0 ? - price(- $mt) : '') . "'. ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; print '" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->ref_supplier . ' - ' . $langs->trans("VAT") . " NPR (counterpart)' . ($mt < 0 ? - price(- $mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); + $absolute_discount = $soc->getAvailableDiscounts(); - print '. '; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 1, -1, -1, $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > Propal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 0, 0, -1, $conf->currency)); - } else { - // Remise dispo de type non avoir - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote, 0, $langs, 0, 0, -1, $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts(); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > Commande::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
'; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts'); - print ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - // print ' ('.$addrelativediscount.')'; - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { - print '. '; - if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
' . $text . '.
'; - } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); - } - } - } else { - // Discount available of type fixed amount (not credit note) - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')'); - } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later - { - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available - if (! $absolute_discount) print '
'; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0, $more); // We allow credit note even if amount is higher - } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
'; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } + print '
'; + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
'.$langs->trans('Discounts').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; - if ($absolute_discount > 0) - { - if ($object->statut > Facture::STATUS_DRAFT || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - if ($object->statut == Facture::STATUS_DRAFT) - { - print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)).'. '; - } - else - { - if ($object->statut < Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - print '
'.$text.'.
'; - } - else - { - $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - $text2=$langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text,$text2); - } - } - } - else - { - // Remise dispo de type non avoir - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filterabsolutediscount,$resteapayer,'',1); - } - } - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_CREDIT_NOTE) - { - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_DEPOSIT) - { - $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)); - print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse")); - } - else print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.'; - } - else - { - // Remise dispo de type avoir - if (! $absolute_discount) print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filtercreditnote,$resteapayer,'',1); - } - } - if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; + + $thirdparty = $object->thirdparty; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + $cannotApplyDiscount = 1; + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
'.$langs->trans('Discounts').''; - if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount=$soc->getAvailableDiscounts('',$filterabsolutediscount); $absolute_creditnote=$soc->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); - if ($absolute_discount) - { - if ($object->statut > Commande::STATUS_DRAFT) - { - print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - } - else - { - // Remise dispo de type non avoir - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) - { - print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'. '; - } - if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + $cannotApplyDiscount = 1; + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
' . $langs->trans('Discounts') . ''; - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
'; $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts') . ''; - - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print '. '; $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > CommandeFournisseur::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + print '
' . $langs->trans('Discounts') . ''; + + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts') . ''; - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", '' . $societe->remise_supplier_percent . ''); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
'; + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $societe->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; print '
' . $langs->trans('Discounts'); print ''; - if ($societe->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", $societe->remise_supplier_percent); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - // print ' ('.$addrelativediscount.')'; + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { - print '. '; - if ($object->statut > 0 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
' . $text . '.
'; - } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); - } - } - } else { - // Discount available of type fixed amount (not credit note) - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $societe->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')', 0, 1); - } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later - { - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } - else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != FactureFournisseur::STATUS_VALIDATED || $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != FactureFournisseur::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available - if (! $absolute_discount) print '
'; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, $resteapayer, '', 0, 1); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $societe->id, $absolute_creditnote, $filtercreditnote, 0, $more, 0, 1); // We allow credit note even if amount is higher - } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
'; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", '' . $soc->remise_supplier_percent . ''); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print ' (' . $langs->trans("EditRelativeDiscount") . ')'; - print '. '; - print '
'; - $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; - print '.'; + $thirdparty = $soc; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_supplier_percent) - print $langs->trans("HasRelativeDiscountFromSupplier", $soc->remise_supplier_percent); - else - print $langs->trans("HasNoRelativeDiscountFromSupplier"); - print '. '; + print '
' . $langs->trans('Discounts') . ''; $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > SupplierProposal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1, 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
'; - if($displayCustomer) { + if($isCustomer) { // Customer discount print '"; } - if($displaySupplier) { + if($isSupplier) { // Supplier discount print '"; @@ -160,17 +156,17 @@ if ($socid > 0) print '
'; - if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + if($isCustomer && ! $isSupplier) { print ''; } - if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + if(! $isCustomer && $isSupplier) { print ''; } print '
'; print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
'; print $langs->trans("SupplierRelativeDiscount").''.price2num($object->remise_supplier_percent)."%
'; - if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + if($isCustomer && $isSupplier) { // Discount type print ''; print '\n"; + // Type + print ''; + // Amount + print ""; + print ""; + print "\n"; + } + print "
'.$langs->trans('DiscountType').' '; @@ -205,8 +201,8 @@ if ($socid > 0) print '
'; - if($displayCustomer) { - if($displaySupplier) { + if($isCustomer) { + if($isSupplier) { print '
'; print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -263,8 +259,8 @@ if ($socid > 0) } } - if($displaySupplier) { - if($displayCustomer) { + if($isSupplier) { + if($isCustomer) { print '
'; // class="fichehalfleft" print '
'; print '
'; @@ -321,7 +317,7 @@ if ($socid > 0) dol_print_error($db); } - if($displayCustomer) { + if($isCustomer) { print '
'; // class="ficheaddleft" print '
'; // class="fichehalfright" print '
'; // class="fichecenter" diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 92e2f1d5d71..b580684af7e 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -238,9 +238,6 @@ if ($socid > 0) $isCustomer = $object->client == 1 || $object->client == 3; $isSupplier = $object->fournisseur == 1; - $displayCustomer = $conf->global->MAIN_FEATURES_LEVEL <= 0 || $isCustomer; - $displaySupplier = $conf->global->MAIN_FEATURES_LEVEL > 0 && $isSupplier; - /* * Display tabs */ @@ -259,7 +256,7 @@ if ($socid > 0) print '
'; - if(! $displayCustomer && ! $displaySupplier) { + if(! $isCustomer && ! $isSupplier) { print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; dol_fiche_end(); @@ -274,7 +271,7 @@ if ($socid > 0) print ''; - if($displayCustomer) { // Calcul avoirs client en cours + if($isCustomer) { // Calcul avoirs client en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; @@ -305,7 +302,7 @@ if ($socid > 0) } } - if($displaySupplier) { + if($isSupplier) { // Calcul avoirs fournisseur en cours $remise_all=$remise_user=0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; @@ -349,16 +346,16 @@ if ($socid > 0) print '
'; - if($conf->global->MAIN_FEATURES_LEVEL <= 0 || ($isCustomer && ! $isSupplier)) { + if($isCustomer && ! $isSupplier) { print ''; } - if($conf->global->MAIN_FEATURES_LEVEL > 0 && (! $isCustomer && $isSupplier)) { + if(! $isCustomer && $isSupplier) { print ''; } print '
'; - if($conf->global->MAIN_FEATURES_LEVEL > 0 && $isCustomer && $isSupplier) { + if($isCustomer && $isSupplier) { print ''; print '"; print ''; - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - // Relative discounts (Discounts-Drawbacks-Rebates) - print ''; - print ''; - - // Absolute discounts (Discounts-Drawbacks-Rebates) - print ''; - print ''; - print ''; + // Relative discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + + // Absolute discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + print ''; print ''; print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) + if ($societe->id > 0) { // Discounts for third party print ''; print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; - } - - $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - - print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + + print ''; + // Conditions de reglement par defaut $langs->load('bills'); print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $societe->id > 0) + if ($societe->id > 0) { // Discounts for third party print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - // Relative and absolute discounts - print ''; - } + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + + print ''; // Label print ''; @@ -2782,41 +2778,39 @@ else $creditnoteamount = 0; $depositamount = 0; - if($conf->global->MAIN_FEATURES_LEVEL > 0) { - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_invoice_supplier_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_invoice_supplier = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new FactureFournisseur($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_invoice_supplier_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; - } - } else { - dol_print_error($db); - } - } + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_invoice_supplier_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new FactureFournisseur($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_invoice_supplier_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); + } // Paye partiellement 'escompte' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { @@ -3029,7 +3023,7 @@ else } // Reverse back money or convert to reduction - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD)) { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { // For credit note only if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 4e4611d4fd5..e906fea4041 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -1050,7 +1050,7 @@ if ($action == 'create') } print '' . "\n"; - if ($conf->global->MAIN_FEATURES_LEVEL > 0 && $soc->id > 0) + if ($soc->id > 0) { // Discounts for third party print ''; -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // autodecrement selected web stock when generate invoice or paid an order->generate linked invoice as in a POS module for a full automatic functionality (useful when there is a lot of payment) -{ - // Stock for automatic decrement - print ''; +print ''; - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? - { - print ''; - } +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? +{ + print ''; } if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ? @@ -297,7 +283,7 @@ print ''; +print ''; // Payment token for URL print '\n"; print "\n"; - -$list=\Stripe\Charge::all(array("limit" => $limit),array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); -//print $list; -foreach ($list->data as $charge) { - print ''; - $societestatic->fetch($charge->metadata->idcustomer); - $societestatic->id=$charge->metadata->idcustomer; - $societestatic->lastname=$obj->lastname; - $societestatic->firstname=$obj->firstname; - $societestatic->admin=$obj->admin; - $societestatic->login=$obj->login; - $societestatic->email=$obj->email; - $societestatic->societe_id=$obj->fk_soc; - // Ref + + $list=\Stripe\Charge::all(array("limit" => $limit), array("stripe_account" => $stripeaccount)); + + //print $list; + foreach ($list->data as $charge) + { + print ''; + $societestatic->fetch($charge->metadata->idcustomer); + $societestatic->id=$charge->metadata->idcustomer; + $societestatic->lastname=$obj->lastname; + $societestatic->firstname=$obj->firstname; + $societestatic->admin=$obj->admin; + $societestatic->login=$obj->login; + $societestatic->email=$obj->email; + $societestatic->societe_id=$obj->fk_soc; + // Ref print "\n"; // Employee print "\n"; - // Origine + // Origine print "\n"; - // Date payment - print '\n"; - // Label payment - print "\n"; - // Type - print ''; - // Amount - print ""; - print "\n"; - } + if ($charge->metadata->source=="order"){ + $object = new Commande($db); + $object->fetch($charge->metadata->idsource); + print "".img_picto('', 'object_order')." ".$object->ref.""; + } elseif ($charge->metadata->source=="invoice"){ + $object = new Facture($db); + $object->fetch($charge->metadata->idsource); + print "".img_picto('', 'object_invoice')." ".$object->ref.""; + } + print "\n"; + // Date payment + print '\n"; + // Label payment + print "\n"; + // Type + print ''; + // Amount + print ""; + print "\n"; + } } else { -} +} llxFooter(); $db->close(); diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index a1eefd6ecb7..4ea45b7a4b3 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -21,23 +21,24 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; -/** - * \class Rewards - * \brief Class for Rewards + + +/** + * Stripe class */ class Stripe extends CommonObject { public $rowid; - public $fk_soc; - public $fk_key; - public $id; - public $mode; - public $entity; - public $statut; - public $type; - public $code; - public $message; - + public $fk_soc; + public $fk_key; + public $id; + public $mode; + public $entity; + public $statut; + public $type; + public $code; + public $message; + /** * Constructor * @@ -48,273 +49,306 @@ class Stripe extends CommonObject $this->db = $db; } - -public function GetStripeAccount($id) // TODO: move /transforme optimize function/data + + /** + * GetStripeAccount + * + * @param string $mode 'StripeTest' or 'StripeLive' + * @return int ??? + */ + public function GetStripeAccount($mode='StripeTest') { global $conf; - $sql = "SELECT key_account"; - $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity"; - $sql.= " WHERE entity = ".$id.""; + $sql = "SELECT tokenstring"; + $sql.= " FROM ".MAIN_DB_PREFIX."oauth_token"; + $sql.= " WHERE entity = ".$conf->entity; + $sql.= " AND service = '".$mode."'"; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) + if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $key=$obj->key_account; - } - else {$key=0;} - } - else {$key=0;} - -return $key; - } - -public function GetStripeCustomerAccount($id) + $tokenstring=$obj->tokenstring; + + $tmparray = dol_json_decode($tokenstring); + $key = $tmparray->stripe_user_id; + } + else { + $tokenstring=''; + } + } + else { + dol_print_error($this->db); + } + + return $key; + } + + /** + * GetStripeCustomerAccount + * + * @param int $id ??? + * @return int ??? + */ + public function GetStripeCustomerAccount($id) { global $conf; $sql = "SELECT s.key_account as key_account, s.entity, e.fk_object"; - $sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity as s"; - $sql.= " JOIN ".MAIN_DB_PREFIX."entity_extrafields as e ON s.entity=e.fk_object"; - $sql.= " WHERE e.fk_soc=".$id." "; + $sql .= " FROM " . MAIN_DB_PREFIX . "stripe_entity as s"; + $sql .= " JOIN " . MAIN_DB_PREFIX . "entity_extrafields as e ON s.entity=e.fk_object"; + $sql .= " WHERE e.fk_soc=" . $id . " "; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $key=$obj->key_account; - } - else {$key=NULL;} - } - else {$key=NULL;} - -return $key; - } - -public function CustomerStripe($id,$key) + $key = $obj->key_account; + } else { + $key = NULL; + } + } else { + $key = NULL; + } + + return $key; + } + + + /** + * CustomerStripe + * + * @param int $id ??? + * @param string $key ??? + * @return \Stripe\StripeObject|\Stripe\ApiResource + */ + public function CustomerStripe($id,$key) { -global $conf; -if (empty($conf->global->STRIPECONNECT_LIVE)) -{ -$mode=0; -} -else -{ -if (empty($conf->global->STRIPE_LIVE)) -{ -$mode=0; -} -else -{ -$mode=$conf->global->STRIPE_LIVE; -} -} + global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } $sql = "SELECT rowid,fk_soc,fk_key,mode,entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe"; - $sql.= " WHERE fk_soc = ".$id." "; - $sql.= " AND mode=".$mode." AND entity IN (" . getEntity('stripe') . ")"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; + $sql .= " WHERE fk_soc = " . $id . " "; + $sql .= " AND mode=" . $mode . " AND entity IN (" . getEntity('stripe') . ")"; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $soc = new Societe($this->db); - $soc->fetch($id); - $num=$this->db->num_rows($resql); + $soc = new Societe($this->db); + $soc->fetch($id); + $num = $this->db->num_rows($resql); if ($num) { - $obj = $this->db->fetch_object($resql); - $tiers = $obj->fk_key; - if ($conf->entity==1){ - $customer = \Stripe\Customer::retrieve("$tiers"); - }else{ - $customer = \Stripe\Customer::retrieve("$tiers",array("stripe_account" => $key)); - }} - else { - if ($conf->entity==1){ - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "description" => $soc->name - )); - }else{ - $customer = \Stripe\Customer::create(array( - "email" => $soc->email, - "description" => $soc->name - ), array("stripe_account" => $key)); - } - $customer_id = "".$customer->id.""; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_stripe (fk_soc,fk_key,mode,entity)"; - $sql .= " VALUES ($id,'$customer_id',".$mode.",".$conf->entity.")"; - dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); - $resql = $this->db->query($sql); - }} -return $customer; + $obj = $this->db->fetch_object($resql); + $tiers = $obj->fk_key; + if ($conf->entity == 1) { + $customer = \Stripe\Customer::retrieve("$tiers"); + } else { + $customer = \Stripe\Customer::retrieve("$tiers", array( + "stripe_account" => $key + )); + } + } else { + if ($conf->entity == 1) { + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + )); + } else { + $customer = \Stripe\Customer::create(array( + "email" => $soc->email, + "description" => $soc->name + ), array( + "stripe_account" => $key + )); + } + $customer_id = "" . $customer->id . ""; + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_stripe (fk_soc,fk_key,mode,entity)"; + $sql .= " VALUES ($id,'$customer_id'," . $mode . "," . $conf->entity . ")"; + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + } + } + return $customer; } - -public function CreatePaymentStripe($amount,$currency,$origin,$item,$source,$customer,$account) -{ -global $conf; -if (empty($conf->global->STRIPECONNECT_LIVE)) -{ -$mode=0; -} -else -{ -if (empty($conf->global->STRIPE_LIVE)) -{ -$mode=0; -} -else -{ -$mode=$conf->global->STRIPE_LIVE; -} -} + + /** + * CreatePaymentStripe + * + * @param unknown $amount ??? + * @param unknown $currency ??? + * @param unknown $origin ??? + * @param unknown $item ??? + * @param unknown $source ??? + * @param unknown $customer ??? + * @param unknown $account ??? + * @return Stripe + */ + public function CreatePaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) + { + global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { + $mode = 0; + } else { + if (empty($conf->global->STRIPE_LIVE)) { + $mode = 0; + } else { + $mode = $conf->global->STRIPE_LIVE; + } + } $sql = "SELECT fk_soc,fk_key,mode,entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe"; - $sql.= " WHERE fk_key = '$customer' "; - $sql.= " AND mode=".$mode." "; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe"; + $sql .= " WHERE fk_key = '$customer' "; + $sql .= " AND mode=" . $mode . " "; dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $entite=$obj->entity; - $fksoc=$obj->fk_soc; - } - } -$stripeamount=round($amount*100); -$societe = new Societe($this->db); -$societe->fetch($fksoc); + $entite = $obj->entity; + $fksoc = $obj->fk_soc; + } + } + $stripeamount = round($amount * 100); + $societe = new Societe($this->db); + $societe->fetch($fksoc); -if ($origin==order){ -$order=new Commande($this->db); -$order->fetch($item); -$ref=$order->ref; -$description="ORD=".$ref.".CUS=".$societe->code_client; -} -elseif ($origin==invoice) { -$invoice=new Facture($this->db); -$invoice->fetch($item); -$ref=$invoice->ref; -$description="INV=".$ref.".CUS=".$societe->code_client; -} + if ($origin == order) { + $order = new Commande($this->db); + $order->fetch($item); + $ref = $order->ref; + $description = "ORD=" . $ref . ".CUS=" . $societe->code_client; + } elseif ($origin == invoice) { + $invoice = new Facture($this->db); + $invoice->fetch($item); + $ref = $invoice->ref; + $description = "INV=" . $ref . ".CUS=" . $societe->code_client; + } -$metadata = array( - "source" => "".$origin."", - "idsource" => "".$item."", - "idcustomer" => "".$societe->id."" - ); -$return = new Stripe($this->db); -try { -if ($stripeamount>=100) { -if ($entite=='1' or empty($conf->stripeconnect->enabled)){ -if (preg_match('/acct_/i',$source)){ - $charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", -// "statement_descriptor" => " ", - "metadata" => $metadata, - "source" => "$source" -) -); -} else { -$charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", -// "statement_descriptor" => " ", - "description" => "$description", - "metadata" => $metadata, - "receipt_email" => $societe->email, - "source" => "$source", - "customer" => "$customer") - ,array("idempotency_key" => "$ref") -); -}}else{ -$fee=round(($amount*($conf->global->STRIPE_APPLICATION_FEE_PERCENT/100)+$conf->global->STRIPE_APPLICATION_FEE)*100); -if ($fee<($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100)){ -$fee=round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100); -} -$charge = \Stripe\Charge::create(array( - "amount" => "$stripeamount", - "currency" => "$currency", -// "statement_descriptor" => " ", - "description" => "$description", - "metadata" => $metadata, - "source" => "$source", - "customer" => "$customer", - "application_fee" => "$fee" -), array("idempotency_key" => "$ref","stripe_account" => "$account")); -} -if (isset($charge->id)){ + $metadata = array( + "source" => "" . $origin . "", + "idsource" => "" . $item . "", + "idcustomer" => "" . $societe->id . "" + ); + $return = new Stripe($this->db); + try { + if ($stripeamount >= 100) { + if ($entite == '1' or empty($conf->stripeconnect->enabled)) { + if (preg_match('/acct_/i', $source)) { + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "metadata" => $metadata, + "source" => "$source" + )); + } else { + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "receipt_email" => $societe->email, + "source" => "$source", + "customer" => "$customer" + ), array( + "idempotency_key" => "$ref" + )); + } + } else { + $fee = round(($amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE) * 100); + if ($fee < ($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100)) { + $fee = round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100); + } + $charge = \Stripe\Charge::create(array( + "amount" => "$stripeamount", + "currency" => "$currency", + // "statement_descriptor" => " ", + "description" => "$description", + "metadata" => $metadata, + "source" => "$source", + "customer" => "$customer", + "application_fee" => "$fee" + ), array( + "idempotency_key" => "$ref", + "stripe_account" => "$account" + )); + } + if (isset($charge->id)) {} + } + + $return->statut = 'success'; + $return->id = $charge->id; + if ($charge->source->type == 'card') { + $return->message = $charge->source->card->brand . " ****" . $charge->source->card->last4; + } elseif ($charge->source->type == 'three_d_secure') { + $stripe = new Stripe($this->db); + $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( + "stripe_account" => $stripe->GetStripeAccount($conf->entity) + )); + $return->message = $src->card->brand . " ****" . $src->card->last4; + } else { + $return->message = $charge->id; + } + } catch (\Stripe\Error\Card $e) { + // Since it's a decline, \Stripe\Error\Card will be caught + $body = $e->getJsonBody(); + $err = $body['error']; + + $return->statut = 'error'; + $return->id = $err['charge']; + $return->type = $err['type']; + $return->code = $err['code']; + $return->message = $err['message']; + $body = "Une erreur de paiement est survenue. Voici le code d'erreur:
" . $return->id . " " . $return->message . " "; + $subject = '[NOTIFICATION] Erreur de paiement'; + $headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; + mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers); + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\RateLimit $e) { + // Too many requests made to the API too quickly + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\InvalidRequest $e) { + // Invalid parameters were supplied to Stripe's API + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Authentication $e) { + // Authentication with Stripe's API failed + // (maybe you changed API keys recently) + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\ApiConnection $e) { + // Network communication with Stripe failed + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (\Stripe\Error\Base $e) { + // Display a very generic error to the user, and maybe send + // yourself an email + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } catch (Exception $e) { + // Something else happened, completely unrelated to Stripe + $error ++; + dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); + } + return $return; + } } -} - -$return->statut = 'success'; -$return->id = $charge->id; -if ($charge->source->type=='card'){ -$return->message = $charge->source->card->brand." ****".$charge->source->card->last4; -}elseif ($charge->source->type=='three_d_secure'){ -$stripe=new Stripe($this->db); -$src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card."",array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); -$return->message = $src->card->brand." ****".$src->card->last4; -}else { -$return->message = $charge->id; -} - -} catch(\Stripe\Error\Card $e) { - // Since it's a decline, \Stripe\Error\Card will be caught - $body = $e->getJsonBody(); - $err = $body['error']; - -$return->statut = 'error'; -$return->id = $err['charge']; -$return->type = $err['type']; -$return->code = $err['code']; -$return->message = $err['message']; -$body = "Une erreur de paiement est survenue. Voici le code d'erreur:
".$return->id." ".$return->message." "; -$subject = '[NOTIFICATION] Erreur de paiement'; -$headers = 'From: "ptibogxiv.net" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; -mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers); - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\RateLimit $e) { - // Too many requests made to the API too quickly - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\InvalidRequest $e) { - // Invalid parameters were supplied to Stripe's API - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\Authentication $e) { - // Authentication with Stripe's API failed - // (maybe you changed API keys recently) - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\ApiConnection $e) { - // Network communication with Stripe failed - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (\Stripe\Error\Base $e) { - // Display a very generic error to the user, and maybe send - // yourself an email - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } catch (Exception $e) { - // Something else happened, completely unrelated to Stripe - $error++; - dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); - } - return $return; -} - -} diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index 2a37b5a55a5..143c34f7530 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -46,94 +46,109 @@ $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -/* -* View -*/ + /* + * View + */ llxHeader('', $langs->trans("StripeTransactionList")); $form = new Form($db); $societestatic = new societe($db); $acc = new Account($db); -$stripe=new Stripe($db); -if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) +$stripe = new Stripe($db); + +if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox', 'alpha'))) { - dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); + $service = 'StripeTest'; + dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); +} +else +{ + $servie = 'StripeLive'; } -if (!$rowid){ - print ''; - if ($optioncss != '') print ''; - print ''; +$stripeaccount = $stripe->GetStripeAccount($service); +if (empty($stripeaccount)) +{ + print $langs->trans('ErrorStripeAccountNotDefined'); +} + +if (! $rowid && $stripeaccount) { + + print ''; + if ($optioncss != '') + print ''; + print ''; print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print_barre_liste($langs->trans("StripeTransactionList"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans("StripeTransactionList"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); - print '
'; - print '
'.$langs->trans('DiscountType').' '; print ' '; @@ -408,8 +405,8 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountStillRemaining")); - if($displayCustomer) { - if($displaySupplier) { + if($isCustomer) { + if($isSupplier) { print '
'; print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -541,8 +538,8 @@ if ($socid > 0) } } - if($displaySupplier) { - if($displayCustomer) { + if($isSupplier) { + if($isCustomer) { print '
'; // class="fichehalfleft" print '
'; print '
'; @@ -677,7 +674,7 @@ if ($socid > 0) dol_print_error($db); } - if($displayCustomer) { + if($isCustomer) { print '
'; // class="ficheaddleft" print '
'; // class="fichehalfright" print '
'; // class="fichecenter" @@ -692,8 +689,8 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - if($displayCustomer) { - if($displaySupplier) { + if($isCustomer) { + if($isSupplier) { print '
'; print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -843,8 +840,8 @@ if ($socid > 0) } } - if($displaySupplier) { - if($displayCustomer) { + if($isSupplier) { + if($isCustomer) { print '
'; // class="fichehalfleft" print '
'; print '
'; @@ -994,7 +991,7 @@ if ($socid > 0) dol_print_error($db); } - if($displayCustomer) { + if($isCustomer) { print '
'; // class="ficheaddleft" print '
'; // class="fichehalfright" print '
'; // class="fichecenter" diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index a5d5490e660..877ba0f6e14 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -258,40 +258,38 @@ if ($object->id > 0) print "
'; - print '
'; - print $langs->trans("CustomerRelativeDiscountShort"); - print ''; - if ($user->rights->societe->creer && !$user->societe_id > 0) - { - print ''.img_edit($langs->trans("Modify")).''; - } - print '
'; - print '
'.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').'
'; - print ''; - print '
'; - print $langs->trans("CustomerAbsoluteDiscountShort"); - print ''; - if ($user->rights->societe->creer && !$user->societe_id > 0) - { - print ''.img_edit($langs->trans("Modify")).''; - } - print '
'; - print '
'; - $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); - if ($amount_discount < 0) dol_print_error($db,$object->error); - if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; - //else print $langs->trans("DiscountNone"); - print '
'; + print '
'; + print $langs->trans("CustomerRelativeDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; } + print '
'; + print '
'.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').'
'; + print ''; + print '
'; + print $langs->trans("CustomerAbsoluteDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->societe_id > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
'; + print '
'; + $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); + if ($amount_discount < 0) dol_print_error($db,$object->error); + if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; + //else print $langs->trans("DiscountNone"); + print '
'; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index c7487f4cc51..4225646a3af 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1479,7 +1479,7 @@ if ($action=='create') } print '
' . $langs->trans('Discounts') . ''; @@ -1874,32 +1874,29 @@ elseif (! empty($object->id)) print ''.$author->getNomUrl(1, '', 0, 0, 0).'
' . $langs->trans('Discounts') . ''; - - $thirdparty = $societe; - $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - - print '
' . $langs->trans('Discounts') . ''; + + $thirdparty = $societe; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + + print '
'; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 14909a1fc2e..8069f6cf520 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1848,74 +1848,71 @@ if ($action == 'create') if (empty($origin)) { - if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note + if ($societe->id > 0) { - if ($societe->id > 0) - { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
'; - $tmp=' - jQuery(document).ready(function() { - if (! jQuery("#radio_creditnote").is(":checked")) - { - jQuery("#credit_note_options").hide(); - } - jQuery("#radio_creditnote").click(function() { - jQuery("#credit_note_options").show(); - }); - jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() { - jQuery("#credit_note_options").hide(); - }); - }); - '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; - - print '
'; - print '    0 ? 'checked':'').' /> "; - print '
    0 ? 'checked':'').' /> "; - print '
'; - - print '
'; - } - } - else + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { print '
'; - $tmp=' '; - $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $tmp=' + jQuery(document).ready(function() { + if (! jQuery("#radio_creditnote").is(":checked")) + { + jQuery("#credit_note_options").hide(); + } + jQuery("#radio_creditnote").click(function() { + jQuery("#credit_note_options").show(); + }); + jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() { + jQuery("#credit_note_options").hide(); + }); + }); + '; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); print $desc; - print '
' . "\n"; + + print '
'; + print '    0 ? 'checked':'').' /> "; + print '
    0 ? 'checked':'').' /> "; + print '
'; + + print ''; } } + else + { + print '
'; + $tmp=' '; + $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; + $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
' . "\n"; + } } print ''; print '
' . $langs->trans('Discounts') . ''; @@ -2411,18 +2408,17 @@ else } print '
' . $langs->trans('Discounts'); - print ''; - $thirdparty = $societe; - $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + // Relative and absolute discounts + print '
' . $langs->trans('Discounts'); + print ''; - print '
'; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
'; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
' . $langs->trans('Discounts') . ''; @@ -1404,32 +1404,29 @@ if ($action == 'create') print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 0) { - - // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice - } else { - $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; - $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; - } - - print ''; + // Relative and absolute discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; + $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } + print ''; + // Payment term print ''; + $thirdpartystatic->fetch($objp->socid); - $invoice=new Facture($db); - $invoice->fetch($objp->facid); - $paiement = $invoice->getSommePaiement(); - $creditnotes=$invoice->getSumCreditNotesUsed(); - $deposits=$invoice->getSumDepositsUsed(); - $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); - $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); + $invoice=new Facture($db); + $invoice->fetch($objp->facid); + + $paiement = $invoice->getSommePaiement(); + $creditnotes=$invoice->getSumCreditNotesUsed(); + $deposits=$invoice->getSumDepositsUsed(); + $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); + $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); + + print ''; // Invoice print ''; From 78259db0ee701f9f97a732297a111f84c38bf566 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 17:22:38 +0100 Subject: [PATCH 41/91] Intorduce dolDecodeBlockedData --- htdocs/blockedlog/admin/blockedlog_list.php | 2 +- htdocs/blockedlog/ajax/block-info.php | 6 +++ htdocs/blockedlog/class/blockedlog.class.php | 41 +++++++++++++++++++- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index 9410ef9be5e..e8b2dc8b73b 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -196,7 +196,7 @@ else if (GETPOST('downloadcsv','alpha')) $block_static->user_fullname = $obj->user_fullname; $block_static->fk_user = $obj->fk_user; $block_static->signature = $obj->signature; - $block_static->object_data = unserialize($obj->object_data); + $block_static->object_data = $block_static->dolDecodeBlockedData($obj->object_data); $checksignature = $block_static->checkSignature($previoushash); // If $previoushash is not defined, checkSignature will search it diff --git a/htdocs/blockedlog/ajax/block-info.php b/htdocs/blockedlog/ajax/block-info.php index a092b13ca99..d4d4eef4e07 100644 --- a/htdocs/blockedlog/ajax/block-info.php +++ b/htdocs/blockedlog/ajax/block-info.php @@ -85,10 +85,16 @@ function formatObject($objtoshow, $prefix) { if (! is_object($val) && ! is_array($val)) { + // TODO $val can be '__PHP_Incomplete_Class', the is_object return false $s.=''; $s.=''; } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index fae976dec80..5a713168c48 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -686,6 +686,35 @@ if ($massaction == 'confirm_createbills') { $db->commit(); setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + + // Make a redirect to avoid to bill twice if we make a refresh or back + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); + if ($sall) $param.='&sall='.urlencode($sall); + if ($socid > 0) $param.='&socid='.urlencode($socid); + if ($viewstatut != '') $param.='&viewstatut='.urlencode($viewstatut); + if ($search_orderday) $param.='&search_orderday='.urlencode($search_orderday); + if ($search_ordermonth) $param.='&search_ordermonth='.urlencode($search_ordermonth); + if ($search_orderyear) $param.='&search_orderyear='.urlencode($search_orderyear); + if ($search_deliveryday) $param.='&search_deliveryday='.urlencode($search_deliveryday); + if ($search_deliverymonth) $param.='&search_deliverymonth='.urlencode($search_deliverymonth); + if ($search_deliveryyear) $param.='&search_deliveryyear='.urlencode($search_deliveryyear); + if ($search_ref) $param.='&search_ref='.urlencode($search_ref); + if ($search_company) $param.='&search_company='.urlencode($search_company); + if ($search_ref_customer) $param.='&search_ref_customer='.urlencode($search_ref_customer); + if ($search_user > 0) $param.='&search_user='.urlencode($search_user); + if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); + if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht); + if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat); + if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc); + if ($search_project_ref >= 0) $param.="&search_project_ref=".urlencode($search_project_ref); + if ($show_files) $param.='&show_files=' .urlencode($show_files); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + if ($billed != '') $param.='&billed='.urlencode($billed); + + header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); + exit; } else { From cab61724f28e044922309ee1cfc14f407b4a9452 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 19:33:43 +0100 Subject: [PATCH 43/91] Fix phpcs --- htdocs/blockedlog/class/blockedlog.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index ee41a139152..8c35ec11834 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -675,8 +675,9 @@ class BlockedLog /** * Decode data * + * @param string $data Data to unserialize * @param string $mode 0=unserialize, 1=json_decode - * @return string Value unserialized + * @return string Value unserialized */ public function dolDecodeBlockedData($data, $mode=0) { From d8dcebfa9aec5eb867bf9ff3d679019c50c3ceef Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 20:12:40 +0100 Subject: [PATCH 44/91] FIX Do not lose filter when editing comment of a time spent in task view --- htdocs/projet/tasks/time.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index cbfdc48eae9..79ff8f9d9b0 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -987,13 +987,14 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) { if ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids) || $user->rights->projet->all->creer) { + //$param = ($projectidforalltimes?'projectid='.$projectidforalltimes.'&':'').'.($withproject?'&withproject=1':''); print ' '; - print 'rowid.($withproject?'&withproject=1':'').'">'; + print 'rowid.$param.'">'; print img_edit(); print ''; print ' '; - print 'rowid.($withproject?'&withproject=1':'').'">'; + print 'rowid.$param.'">'; print img_delete(); print ''; } From 7a7c4b8f14e8ca1c3ef5a1e1820171562c3f5d2c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 14:41:13 +0100 Subject: [PATCH 45/91] Fix invalid url --- htdocs/public/paybox/paymentok.php | 2 +- htdocs/public/payment/paymentok.php | 2 +- htdocs/public/paypal/paymentok.php | 2 +- htdocs/public/stripe/paymentok.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/public/paybox/paymentok.php b/htdocs/public/paybox/paymentok.php index 63c15b035f2..9e711ade51b 100644 --- a/htdocs/public/paybox/paymentok.php +++ b/htdocs/public/paybox/paymentok.php @@ -157,7 +157,7 @@ if (! empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
\n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
\n"; $content.=$langs->trans("Link").': '.$url.''."
\n"; diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index d74305890df..6f01ed9f991 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -322,7 +322,7 @@ if ($ispaymentok) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
\n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
\n"; $content.=$langs->trans("Link").': '.$url.''."
\n"; diff --git a/htdocs/public/paypal/paymentok.php b/htdocs/public/paypal/paymentok.php index 80ec1d8ec2b..1e6adb7ca51 100644 --- a/htdocs/public/paypal/paymentok.php +++ b/htdocs/public/paypal/paymentok.php @@ -212,7 +212,7 @@ if ($PAYPALTOKEN) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
\n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
\n"; $content.=$langs->trans("Link").': '.$url.''."
\n"; diff --git a/htdocs/public/stripe/paymentok.php b/htdocs/public/stripe/paymentok.php index d0ce82d1ca8..52b3dac8a7f 100644 --- a/htdocs/public/stripe/paymentok.php +++ b/htdocs/public/stripe/paymentok.php @@ -158,7 +158,7 @@ if ($ispaymentok) if (! empty($tmptag['MEM'])) { $langs->load("members"); - $url=$urlwithroot."/adherents/card_subscriptions.php?rowid=".$tmptag['MEM']; + $url=$urlwithroot."/adherents/subscription.php?rowid=".$tmptag['MEM']; $content.=$langs->trans("PaymentSubscription")."
\n"; $content.=$langs->trans("MemberId").': '.$tmptag['MEM']."
\n"; $content.=$langs->trans("Link").': '.$url.''."
\n"; From 88e47e11a4a254fda2bb201f07b7f2940e0a931c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 17:44:51 +0100 Subject: [PATCH 46/91] Fix rename file --- htdocs/stripe/{charge => charge.php} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename htdocs/stripe/{charge => charge.php} (100%) diff --git a/htdocs/stripe/charge b/htdocs/stripe/charge.php similarity index 100% rename from htdocs/stripe/charge rename to htdocs/stripe/charge.php From 235db1f40515758acf6d616b6c5b1def855374d1 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 19:50:41 +0100 Subject: [PATCH 47/91] Enhance OAuth module to store the stripe account in llx_oauth_token --- htdocs/admin/oauth.php | 1 + htdocs/admin/oauthlogintokens.php | 32 +- htdocs/core/lib/oauth.lib.php | 23 +- .../modules/oauth/github_oauthcallback.php | 6 +- .../modules/oauth/google_oauthcallback.php | 2 +- .../oauth/stripetest_oauthcallback.php | 180 ++++++ .../install/mysql/migration/7.0.0-8.0.0.sql | 2 + .../install/mysql/tables/llx_oauth_token.sql | 5 +- htdocs/langs/en_US/stripe.lang | 4 +- htdocs/stripe/admin/stripe.php | 116 ++-- htdocs/stripe/charge.php | 137 +++-- htdocs/stripe/class/stripe.class.php | 528 ++++++++++-------- htdocs/stripe/transaction.php | 157 +++--- 13 files changed, 728 insertions(+), 465 deletions(-) create mode 100644 htdocs/core/modules/oauth/stripetest_oauthcallback.php diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php index 3e6f165161c..99ade75fdfe 100644 --- a/htdocs/admin/oauth.php +++ b/htdocs/admin/oauth.php @@ -95,6 +95,7 @@ print '
' . $langs->trans('Discounts') . ''; - - $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); - $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); - $absolute_discount = price2num($absolute_discount, 'MT'); - $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - - $thirdparty = $soc; - $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; - - print '
' . $langs->trans('Discounts') . ''; + + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1); + $absolute_discount = price2num($absolute_discount, 'MT'); + $absolute_creditnote = price2num($absolute_creditnote, 'MT'); + + $thirdparty = $soc; + $discount_type = 1; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + + print '
'; print ''; print ''; From 884b74a6bb322a44e129ea54cf77e4399ad54536 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Wed, 7 Mar 2018 17:12:59 +0100 Subject: [PATCH 38/91] FIX: warning when adding ECM files using old photo path --- htdocs/core/class/html.formfile.class.php | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index a48ae7477fc..d84357c3559 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -1018,7 +1018,17 @@ class FormFile // Get list of files stored into database for same relative directory if ($relativedir) { - $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC); + $filearrayindatabase = dol_dir_list_in_database($relativedir, '', null, 'name', SORT_ASC); + + if($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && ! empty($object->id)) { + if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos"; + else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2),1,1).'/'.substr(substr("000".$object->id, -2),0,1).'/'.$object->id."/photos"; + + $relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dirold); + $relativedirold = preg_replace('/^[\\/]/','',$relativedirold); + + $filearrayindatabase = array_merge($filearrayindatabase, dol_dir_list_in_database($relativedirold, '', null, 'name', SORT_ASC)); + } //var_dump($filearray); //var_dump($filearrayindatabase); From c02e8e9831d6920132356b3c06bce20439f05019 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 19:13:15 +0100 Subject: [PATCH 39/91] Css --- htdocs/core/lib/functions.lib.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 7fffee21b05..7cb2236524a 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -1226,7 +1226,7 @@ function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $pi $tabsname=str_replace("@", "", $picto); $out.='
'; - $out.=''.$langs->trans("More").'... ('.$nbintab.')'; + $out.=''.$langs->trans("More").'... ('.$nbintab.')'; $out.='
'; $out.=$outmore; $out.='
'; @@ -3733,7 +3733,7 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', } if (dol_strlen($morehtmlright)) { - $return.= '
'; + $return.= ''; } $return.= '
'; From 480d756090a06699a47f61cd89e807a61c8c69ce Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 11:30:18 +0100 Subject: [PATCH 29/91] FIX: supplier discounts: typo --- htdocs/core/class/discount.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index b71d84130a1..c8237a839c7 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -46,7 +46,7 @@ class DiscountAbsolute public $fk_facture; // Id invoice when a discount line is used into an invoice (for credit note) public $fk_facture_source; // Id facture avoir a l'origine de la remise public $ref_facture_source; // Ref facture avoir a l'origine de la remise - public $ref_invoive_supplier_source; + public $ref_invoice_supplier_source; /** * Constructor From f1faf155fc8d3154cb6a06fba3d3036e85a1639d Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 11:41:06 +0100 Subject: [PATCH 30/91] FIX: supplier discounts: wrong link to source supplier invoice --- htdocs/core/class/discount.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index c8237a839c7..2813a0d46b1 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -570,8 +570,9 @@ class DiscountAbsolute if ($option == 'invoice') { $facid=! empty($this->discount_type)?$this->fk_invoice_supplier_source:$this->fk_facture_source; + $link=! empty($this->discount_type)?'/fourn/facture/card.php':'/compta/facture/card.php'; $label=$langs->trans("ShowDiscount").': '.$this->ref_facture_source; - $link = ''; + $link = ''; $linkend=''; $ref=! empty($this->discount_type)?$this->ref_invoice_supplier_source:$this->ref_facture_source; $picto='bill'; From c4950d4f0c193fe7618a434ee5ea0078054f3a37 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 11:49:04 +0100 Subject: [PATCH 31/91] FIX: supplier discounts: wrong source invoice ref in DOCs --- htdocs/core/lib/doc.lib.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 447c7c2149e..ae8410bd188 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -73,15 +73,15 @@ function doc_getlinedesc($line,$outputlangs,$hideref=0,$hidedesc=0,$issupplierli { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); - $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromCreditNote",$sourceref); } elseif ($desc == '(DEPOSIT)' && $line->fk_remise_except) { $discount=new DiscountAbsolute($db); $discount->fetch($line->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$discount->ref_facture_source); - $sourceref=!empty($discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $sourceref=!empty($discount->discount_type)?$discount->ref_invoive_supplier_source:$discount->ref_facture_source; + $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromDeposit",$sourceref); // Add date of deposit if (! empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice.=' ('.dol_print_date($discount->datec,'day','',$outputlangs).')'; } From fad521d66cbc76ee1fc8f0f302714ac67b9d3e03 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Mon, 5 Mar 2018 12:09:13 +0100 Subject: [PATCH 32/91] FIX: supplier disocunts: add forgotten index to migration script --- htdocs/install/mysql/migration/7.0.0-8.0.0.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 08d7d362ec5..f23c095dca6 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -59,6 +59,7 @@ ALTER TABLE llx_c_type_container ADD UNIQUE INDEX uk_c_type_container_id (code, ALTER TABLE llx_societe_remise_except ADD COLUMN discount_type integer DEFAULT 0 NOT NULL AFTER fk_soc; +ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_discount_type (discount_type); ALTER TABLE llx_societe ADD COLUMN remise_supplier real DEFAULT 0 AFTER remise_client; CREATE TABLE llx_societe_remise_supplier ( From 0f574579eb71e95969d6dd2b645162016f0c8f1b Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Wed, 7 Mar 2018 12:27:13 +0100 Subject: [PATCH 33/91] Fix: avoid error if type is not numeric --- htdocs/categories/class/categorie.class.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 46063c0f8c4..a8018e2c104 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -1201,6 +1201,8 @@ class Categorie extends CommonObject */ function get_all_categories($type=null, $parent=false) { + if (! is_numeric($type)) $type = $this->MAP_ID[$type]; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql.= " WHERE entity IN (".getEntity('category').")"; if (! is_null($type)) From a0774d523d234e83ef7fb26b3100ae94275c852d Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Wed, 7 Mar 2018 15:24:23 +0100 Subject: [PATCH 34/91] Fix: avoid conflict between invoice and invoicenumber sharings --- htdocs/core/lib/functions2.lib.php | 11 +++++++---- htdocs/core/modules/facture/mod_facture_mars.php | 4 ++-- htdocs/core/modules/facture/mod_facture_terre.php | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 3cbef60f5fd..49a2f12db03 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -715,9 +715,12 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m global $conf,$user; if (! is_object($objsoc)) $valueforccc=$objsoc; - else if($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur; + else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur; else $valueforccc=$objsoc->code_client; + $sharetable = $table; + if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function + // Clean parameters if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers // but we should use local year and month of user @@ -979,7 +982,7 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m $sql.= " WHERE ".$field." LIKE '".$maskLike."'"; $sql.= " AND ".$field." NOT LIKE '(PROV%)'"; if ($bentityon) // only if entity enable - $sql.= " AND entity IN (".getEntity($table, 1).")"; + $sql.= " AND entity IN (".getEntity($sharetable).")"; if ($where) $sql.=$where; if ($sqlwhere) $sql.=' AND '.$sqlwhere; @@ -1027,7 +1030,7 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m $sql.= " WHERE ".$field." LIKE '".$maskLike."'"; $sql.= " AND ".$field." NOT LIKE '%PROV%'"; if ($bentityon) // only if entity enable - $sql.= " AND entity IN (".getEntity($table, 1).")"; + $sql.= " AND entity IN (".getEntity($sharetable).")"; if ($where) $sql.=$where; if ($sqlwhere) $sql.=' AND '.$sqlwhere; @@ -1081,7 +1084,7 @@ function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$m //$sql.= " WHERE ".$field." not like '(%'"; $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'"; if ($bentityon) // only if entity enable - $maskrefclient_sql.= " AND entity IN (".getEntity($table, 1).")"; + $maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")"; if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')"; diff --git a/htdocs/core/modules/facture/mod_facture_mars.php b/htdocs/core/modules/facture/mod_facture_mars.php index 85dff1aa0e1..831dce5d3e4 100644 --- a/htdocs/core/modules/facture/mod_facture_mars.php +++ b/htdocs/core/modules/facture/mod_facture_mars.php @@ -153,7 +153,7 @@ class mod_facture_mars extends ModeleNumRefFactures $sql = "SELECT MAX(CAST(SUBSTRING(facnumber FROM ".$posindice.") AS SIGNED)) as max"; // This is standard SQL $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-%'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; $resql=$db->query($sql); dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); @@ -177,7 +177,7 @@ class mod_facture_mars extends ModeleNumRefFactures $sql = "SELECT facnumber as ref"; $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-".$num."'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); $resql=$db->query($sql); diff --git a/htdocs/core/modules/facture/mod_facture_terre.php b/htdocs/core/modules/facture/mod_facture_terre.php index 4c27340f270..174d8314784 100644 --- a/htdocs/core/modules/facture/mod_facture_terre.php +++ b/htdocs/core/modules/facture/mod_facture_terre.php @@ -169,7 +169,7 @@ class mod_facture_terre extends ModeleNumRefFactures $sql = "SELECT MAX(CAST(SUBSTRING(facnumber FROM ".$posindice.") AS SIGNED)) as max"; // This is standard SQL $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-%'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; $resql=$db->query($sql); dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); @@ -193,7 +193,7 @@ class mod_facture_terre extends ModeleNumRefFactures $sql = "SELECT facnumber as ref"; $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE facnumber LIKE '".$prefix."____-".$num."'"; - $sql.= " AND entity IN (".getEntity('facture').")"; + $sql.= " AND entity IN (".getEntity('invoicenumber').")"; dol_syslog(get_class($this)."::getNextValue", LOG_DEBUG); $resql=$db->query($sql); From b2f6105ae251221a1c291ace826e8f5bca521a1c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 15:52:58 +0100 Subject: [PATCH 35/91] FIX #8277 --- htdocs/core/actions_sendmails.inc.php | 1 - htdocs/societe/card.php | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index eea69e37c13..8a29a268e68 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -319,7 +319,6 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $filename = $attachedfiles['names']; $mimetype = $attachedfiles['mimes']; - // Feature to push mail sent into Sent folder if (! empty($conf->dolimail->enabled)) { diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 217a5367ecf..bfe7db71aca 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -790,8 +790,10 @@ if (empty($reshook)) $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } - // Actions to send emails $id=$socid; + $object->fetch($socid); + + // Actions to send emails $trigger_name='COMPANY_SENTBYMAIL'; $paramname='socid'; $mode='emailfromthirdparty'; From f4f009d877dfcda54b5ba6ce9870f72698acf4f0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 16:10:40 +0100 Subject: [PATCH 36/91] FIX #8269 --- htdocs/fourn/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 5b1148cd885..99a50e08af8 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -2928,7 +2928,7 @@ else } // Presend form - $modelmail='supplier_order_send'; + $modelmail='order_supplier_send'; $defaulttopic='SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $trackid = 'sin'.$object->id; From acc29ea1639ac0daa4f31f98822422e8b97abc8b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 16:19:13 +0100 Subject: [PATCH 37/91] FIX #8219 --- htdocs/fourn/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 8d10d55b3bd..817eb99d8f7 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -587,7 +587,7 @@ if ($object->id > 0) print '
'; print ''; - print ''; + print ''; print ''; print '
'.$langs->trans("LastSupplierOrders",($num<$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''.$langs->trans("AllOrders").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
'; print '
'.$morehtmlright.''.$morehtmlright.'
'."\n"; From 69ef6a9316363895c8708b4fe2d0529daa823cbe Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 18:32:25 +0100 Subject: [PATCH 40/91] Fix data on thirdparty tooltip --- htdocs/compta/paiement/card.php | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php index 6179fb9ac22..3a6727b4299 100644 --- a/htdocs/compta/paiement/card.php +++ b/htdocs/compta/paiement/card.php @@ -338,15 +338,18 @@ if ($resql) { $objp = $db->fetch_object($resql); - print '
'; @@ -355,8 +358,6 @@ if ($resql) // Third party print ''; - $thirdpartystatic->id=$objp->socid; - $thirdpartystatic->name=$objp->name; print $thirdpartystatic->getNomUrl(1); print '
'.($prefix?$prefix.' > ':'').$key.''; if (in_array($key, array('date','datef','dateh','datec','datem','datep'))) { + /*var_dump(is_object($val)); + var_dump(is_array($val)); + var_dump(is_array($val)); + var_dump(@get_class($val)); + var_dump($val);*/ $s.=dol_print_date($val, 'dayhour'); } else diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 13a2840e360..ee41a139152 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -18,10 +18,23 @@ * See https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54 */ + + + +/*ini_set('unserialize_callback_func', 'mycallback'); + +function mycallback($classname) +{ + //var_dump($classname); + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + +}*/ + + + /** * Class to manage Blocked Log */ - class BlockedLog { /** @@ -636,7 +649,7 @@ class BlockedLog $this->fk_user = $obj->fk_user; $this->user_fullname = $obj->user_fullname; - $this->object_data = unserialize($obj->object_data); + $this->object_data = $this->dolDecodeBlockedData($obj->object_data); $this->signature = $obj->signature; $this->signature_line = $obj->signature_line; @@ -658,6 +671,30 @@ class BlockedLog } + + /** + * Decode data + * + * @param string $mode 0=unserialize, 1=json_decode + * @return string Value unserialized + */ + public function dolDecodeBlockedData($data, $mode=0) + { + try + { + //include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + //include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $aaa = unserialize($data); + //$aaa = unserialize($data); + } + catch(Exception $e) + { + //print $e->getErrs); + } + return $aaa; + } + + /** * Set block certified by authority * From 317a5f5b2f3aa109fbfb22d9e0b7cd737868c111 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Mar 2018 14:33:29 +0100 Subject: [PATCH 42/91] Fix by adding a redirect to avoid the order2billing being done twice. --- htdocs/commande/list.php | 2 +- htdocs/core/actions_massactions.inc.php | 29 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 29590820b72..4e589aa6529 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -670,7 +670,7 @@ if ($resql) // Status billed if (! empty($arrayfields['c.facture']['checked'])) { - print ''; + print ''; print $form->selectyesno('billed', $billed, 1, 0, 1); print '
'; $i=0; +// $list is defined into oauth.lib.php foreach ($list as $key) { $supported=0; diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php index 15e70897fb6..97b774edf80 100644 --- a/htdocs/admin/oauthlogintokens.php +++ b/htdocs/admin/oauthlogintokens.php @@ -141,13 +141,27 @@ if ($mode == 'setup' && $user->admin) $urltodelete=$urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltocheckperms='https://github.com/settings/applications/'; } - if ($key[0] == 'OAUTH_GOOGLE_NAME') + elseif ($key[0] == 'OAUTH_GOOGLE_NAME') { $OAUTH_SERVICENAME='Google'; $urltorenew=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltodelete=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltocheckperms='https://security.google.com/settings/security/permissions'; } + elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') + { + $OAUTH_SERVICENAME='StripeTest'; + $urltorenew=$urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete=''; + $urltocheckperms=''; + } + else + { + $urltorenew=''; + $urltodelete=''; + $urltocheckperms=''; + } + // Show value of token $tokenobj=null; @@ -204,7 +218,6 @@ if ($mode == 'setup' && $user->admin) print '
'."\n"; - $var=false; print ''; print ''; print ''; @@ -222,7 +235,6 @@ if ($mode == 'setup' && $user->admin) print ''; print ''."\n"; - $var = ! $var; print ''; print ''; //var_dump($key); @@ -237,19 +249,21 @@ if ($mode == 'setup' && $user->admin) if (is_object($tokenobj)) { //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ? - print ''.$langs->trans('DeleteAccess').'

'; + print ''.$langs->trans('DeleteAccess').'
'; } // Request remote token - print ''.$langs->trans('RequestAccess').'

'; + if ($urltorenew) + { + print ''.$langs->trans('RequestAccess').'
'; + } // Check remote access if ($urltocheckperms) { - print $langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; + print '
'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; } print ''; print '
'; - $var = ! $var; print ''; print ''; //var_dump($key); @@ -272,7 +286,6 @@ if ($mode == 'setup' && $user->admin) if (is_object($tokenobj)) { // Token refresh - $var = ! $var; print ''; print ''; //var_dump($key); @@ -283,7 +296,6 @@ if ($mode == 'setup' && $user->admin) print ''; // Token expired - $var = ! $var; print ''; print ''; //var_dump($key); @@ -294,7 +306,6 @@ if ($mode == 'setup' && $user->admin) print ''; // Token expired at - $var = ! $var; print ''; print ''; //var_dump($key); @@ -354,7 +365,6 @@ if ($mode == 'userconf' && $user->admin) print $langs->trans('PrintUserConfDesc'.$driver)."

\n"; print '
'.$langs->trans($key[0]).'
'; - $var=true; print ''; print ''; print ''; diff --git a/htdocs/core/lib/oauth.lib.php b/htdocs/core/lib/oauth.lib.php index 0149b581fa2..a1582cceca5 100644 --- a/htdocs/core/lib/oauth.lib.php +++ b/htdocs/core/lib/oauth.lib.php @@ -27,12 +27,15 @@ $supportedoauth2array=array( 'OAUTH_GOOGLE_NAME'=>'google', ); - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - $supportedoauth2array['OAUTH_GITHUB_NAME']='github'; + $supportedoauth2array['OAUTH_STRIPE_TEST_NAME']='stripetest'; + $supportedoauth2array['OAUTH_STRIPE_LIVE_NAME']='stripelive'; } $supportedoauth2array['OAUTH_GITHUB_NAME']='github'; + + + // API access parameters OAUTH $list = array ( array( @@ -217,7 +220,17 @@ $list = array ( 'OAUTH_STRAVA_ID', 'OAUTH_STRAVA_SECRET', ), - array( + array( + 'OAUTH_STRIPE_TEST_NAME', + 'OAUTH_STRIPE_TEST_ID', + 'STRIPE_TEST_SECRET_KEY', + ), + array( + 'OAUTH_STRIPE_LIVE_NAME', + 'OAUTH_STRIPE_LIVE_ID', + 'STRIPE_LIVE_SECRET_KEY', + ), + array( 'OAUTH_TUMBLR_NAME', 'OAUTH_TUMBLR_ID', 'OAUTH_TUMBLR_SECRET', @@ -266,12 +279,12 @@ function oauthadmin_prepare_head() $head[$h][1] = $langs->trans("OAuthServices"); $head[$h][2] = 'services'; $h++; - + $head[$h][0] = dol_buildpath('/admin/oauthlogintokens.php', 1); $head[$h][1] = $langs->trans("TokenManager"); $head[$h][2] = 'tokengeneration'; $h++; - + complete_head_from_modules($conf, $langs, null, $head, $h, 'oauthadmin'); complete_head_from_modules($conf, $langs, null, $head, $h, 'oauthadmin', 'remove'); diff --git a/htdocs/core/modules/oauth/github_oauthcallback.php b/htdocs/core/modules/oauth/github_oauthcallback.php index a2f6eb08953..052964eca66 100644 --- a/htdocs/core/modules/oauth/github_oauthcallback.php +++ b/htdocs/core/modules/oauth/github_oauthcallback.php @@ -109,7 +109,7 @@ if (! empty($_GET['code'])) // We are coming from oauth provider page // We should have //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16)) - dol_syslog("We are coming fr mthe oauth provider page"); + dol_syslog("We are coming from the oauth provider page"); //llxHeader('',$langs->trans("OAuthSetup")); //$linkback=''.$langs->trans("BackToModuleList").''; @@ -125,14 +125,14 @@ if (! empty($_GET['code'])) // We are coming from oauth provider page //var_dump($_GET['code']); //var_dump($state); //var_dump($apiService); // OAuth\OAuth2\Service\GitHub - + //$token = $apiService->requestAccessToken($_GET['code'], $state); $token = $apiService->requestAccessToken($_GET['code']); // Github is a service that does not need state to be stored. // Into constructor of GitHub, the call // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri) // has not the ending parameter to true like the Google class constructor. - + setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"]; diff --git a/htdocs/core/modules/oauth/google_oauthcallback.php b/htdocs/core/modules/oauth/google_oauthcallback.php index 8584648ba4c..b63aca5bdf6 100644 --- a/htdocs/core/modules/oauth/google_oauthcallback.php +++ b/htdocs/core/modules/oauth/google_oauthcallback.php @@ -109,7 +109,7 @@ if ($action == 'delete') if (! empty($_GET['code'])) // We are coming from oauth provider page { - dol_syslog("We are coming fr mthe oauth provider page"); + dol_syslog("We are coming from the oauth provider page"); //llxHeader('',$langs->trans("OAuthSetup")); //$linkback=''.$langs->trans("BackToModuleList").''; diff --git a/htdocs/core/modules/oauth/stripetest_oauthcallback.php b/htdocs/core/modules/oauth/stripetest_oauthcallback.php new file mode 100644 index 00000000000..3a663cd7162 --- /dev/null +++ b/htdocs/core/modules/oauth/stripetest_oauthcallback.php @@ -0,0 +1,180 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/modules/oauth/stripe_oauthcallback.php + * \ingroup oauth + * \brief Page to get oauth callback + */ + +require '../../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; +use OAuth\Common\Storage\DoliStorage; +use OAuth\Common\Consumer\Credentials; +use OAuth\OAuth2\Service\GitHub; + +// Define $urlwithroot +$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); +$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + + +$action = GETPOST('action', 'alpha'); +$backtourl = GETPOST('backtourl', 'alpha'); + + +/** + * Create a new instance of the URI class with the current URI, stripping the query string + */ +$uriFactory = new \OAuth\Common\Http\Uri\UriFactory(); +//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); +//$currentUri->setQuery(''); +$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripe_oauthcallback.php'); + + +/** + * Load the credential for the service + */ + +/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */ +$serviceFactory = new \OAuth\ServiceFactory(); +$httpClient = new \OAuth\Common\Http\Client\CurlClient(); +// TODO Set options for proxy and timeout +// $params=array('CURLXXX'=>value, ...) +//$httpClient->setCurlParameters($params); +$serviceFactory->setHttpClient($httpClient); + +// Dolibarr storage +$storage = new DoliStorage($db, $conf); + +// Setup the credentials for the requests +$credentials = new Credentials( + $conf->global->OAUTH_STRIPE_TEST_ID, + $conf->global->STRIPE_TEST_SECRET_KEY, + $currentUri->getAbsoluteUri() +); + +$requestedpermissionsarray=array(); +if (GETPOST('state')) $requestedpermissionsarray=explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back +/*if ($action != 'delete' && empty($requestedpermissionsarray)) +{ + print 'Error, parameter state is not defined'; + exit; +}*/ +//var_dump($requestedpermissionsarray);exit; + +// Instantiate the Api service using the credentials, http client and storage mechanism for the token +/** @var $apiService Service */ +//$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray); + +$sql="INSERT INTO ".MAIN_DB_PREFIX."oauth_token set service='StripeTest', entity=".$conf->entity; +$db->query($sql); + +// access type needed to have oauth provider refreshing token +//$apiService->setAccessType('offline'); + +$langs->load("oauth"); + + +/* + * Actions + */ + + +if ($action == 'delete') +{ + $storage->clearToken('StripeTest'); + + setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs'); + + header('Location: ' . $backtourl); + exit(); +} + +if (! empty($_GET['code'])) // We are coming from oauth provider page +{ + // We should have + //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16)) + + dol_syslog("We are coming from the oauth provider page"); + //llxHeader('',$langs->trans("OAuthSetup")); + + //$linkback=''.$langs->trans("BackToModuleList").''; + //print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup'); + + //dol_fiche_head(); + // retrieve the CSRF state parameter + $state = isset($_GET['state']) ? $_GET['state'] : null; + //print '
'.$langs->trans("User").''.$langs->trans("PrintModule").'
'; + + // This was a callback request from service, get the token + try { + //var_dump($_GET['code']); + //var_dump($state); + //var_dump($apiService); // OAuth\OAuth2\Service\GitHub + + //$token = $apiService->requestAccessToken($_GET['code'], $state); + $token = $apiService->requestAccessToken($_GET['code']); + // Github is a service that does not need state to be stored. + // Into constructor of GitHub, the call + // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri) + // has not the ending parameter to true like the Google class constructor. + + setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token + + $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"]; + unset($_SESSION["backtourlsavedbeforeoauthjump"]); + + header('Location: ' . $backtourl); + exit(); + } catch (Exception $e) { + print $e->getMessage(); + } +} +else // If entry on page with no parameter, we arrive here +{ + $_SESSION["backtourlsavedbeforeoauthjump"]=$backtourl; + + // This may create record into oauth_state before the header redirect. + // Creation of record with state in this tables depend on the Provider used (see its constructor). + if (GETPOST('state')) + { + $url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state'))); + } + else + { + //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated + //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write + $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id='.$conf->global->OAUTH_STRIPE_TEST_ID.'&scope=read_write'; + } + + // we go on oauth provider authorization page + header('Location: ' . $url); + exit(); +} + + +/* + * View + */ + +// No view at all, just actions + +$db->close(); + diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 2a86a414dca..dc7b7d083ab 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -80,3 +80,5 @@ ALTER TABLE llx_c_paiement CHANGE COLUMN id id INTEGER AUTO_INCREMENT PRIMARY KE ALTER TABLE llx_c_payment_term DROP INDEX uk_c_payment_term; ALTER TABLE llx_c_payment_term CHANGE COLUMN rowid rowid INTEGER AUTO_INCREMENT PRIMARY KEY; ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code); + +ALTER TABLE llx_oauth_token ADD COLUMN tokenstring text; diff --git a/htdocs/install/mysql/tables/llx_oauth_token.sql b/htdocs/install/mysql/tables/llx_oauth_token.sql index 0ae4fed1ea8..5c7d6d62177 100644 --- a/htdocs/install/mysql/tables/llx_oauth_token.sql +++ b/htdocs/install/mysql/tables/llx_oauth_token.sql @@ -18,8 +18,9 @@ CREATE TABLE llx_oauth_token ( rowid integer AUTO_INCREMENT PRIMARY KEY, service varchar(36), - token text, + token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2 + tokenstring text, -- token in json format '{ "access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write" } fk_user integer, fk_adherent integer, entity integer DEFAULT 1 -)ENGINE=InnoDB; \ No newline at end of file +)ENGINE=InnoDB; diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 9bc202685dd..12b23955bc8 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -43,4 +43,6 @@ ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online pay StripeLiveEnabled=Stripe live enabled (otherwise test/sandbox mode) StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) -StripeGateways=Stripe gateways \ No newline at end of file +StripeGateways=Stripe gateways +OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...) +OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) \ No newline at end of file diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 91d056aa094..80165b00273 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -116,6 +116,7 @@ if ($action=="setlive") } //TODO: import script for stripe account saving in alone or connect mode for stripe.class.php + /* * View */ @@ -169,62 +170,51 @@ else print ''; } print ''; -if (empty($conf->stripeconnect->enabled)) { -print ''; -print ''; - -print ''; - -print ''; - -print ''; - -print ''; -} else { -print ''; -print ''; -} - -if (! empty($conf->banque->enabled)) //deplace here for separate stripe setting of general and common online payment settings +if (empty($conf->stripeconnect->enabled)) { print ''; - if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // target bank account for stripe transfer: automatic banktransfert with stripe webhook from stripe account (receiving funds, payment, debit fee/application fee, payment dispute) to real bank account - { - print ''; - } + print ''; + + print ''; + + print ''; + + print ''; + + print ''; } +else +{ + print ''; + print ''; +} + print '
'; -print ''.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").''; -print ''; -print '   '.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
'; -print ''.$langs->trans("STRIPE_TEST_SECRET_KEY").''; -print ''; -print '   '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
'; -print ''.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").''; -print ''; -print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
'; -print ''.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").''; -print ''; -print '   '.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
'; -print ''.$langs->trans("STRIPE_LIVE_SECRET_KEY").''; -print ''; -print '   '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
'; -print ''.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").''; -print ''; -print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; -print '
'.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
'; - print $langs->trans("BankAccount").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); + print ''.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").''; + print ''; + print '   '.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; print '
'; - print $langs->trans("BankAccountForBankTransfer").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); - print '
'; + print ''.$langs->trans("STRIPE_TEST_SECRET_KEY").''; + print ''; + print '   '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
'; + print ''.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").''; + print ''; + print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
'; + print ''.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").''; + print ''; + print '   '.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
'; + print ''.$langs->trans("STRIPE_LIVE_SECRET_KEY").''; + print ''; + print '   '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
'; + print ''.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").''; + print ''; + print '   '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx'; + print '
'.$langs->trans("StripeConnect").''.$langs->trans("StripeConnect_Mode").'
'; @@ -243,21 +233,17 @@ print 'name; print '
'; - print $langs->trans("ONLINE_PAYMENT_WAREHOUSE").''; - print $formproduct->selectWarehouses($conf->global->ONLINE_PAYMENT_WAREHOUSE,'ONLINE_PAYMENT_WAREHOUSE','',1,$disabled); - print '
'; +print $langs->trans("BankAccount").''; +print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); +print '
'; - print $langs->trans("BankAccountForBankTransfer").''; - print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); - print '
'; + print $langs->trans("BankAccountForBankTransfer").''; + print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1); + print '
'; print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").''; print ''; print '   '.$langs->trans("Example").': myemail@myserver.com'; -print '
'; diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index aaa0b0475f8..d13235c4f01 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -46,20 +46,36 @@ $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; + + /* -* View -*/ + * View + */ + llxHeader('', $langs->trans("StripeChargeList")); + $form = new Form($db); $societestatic = new societe($db); $acc = new Account($db); $stripe=new Stripe($db); if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha'))) { + $service = 'StripeTest'; dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning'); } -if (!$rowid){ +else +{ + $service = 'StripeLive'; +} +$stripeaccount = $stripe->GetStripeAccount($service); +if (empty($stripeaccount)) +{ + print $langs->trans('ErrorStripeAccountNotDefined'); +} + +if (!$rowid && $stripeaccount) +{ print ''; if ($optioncss != '') print ''; print ''; @@ -85,68 +101,71 @@ if (!$rowid){ print "
".$charge->id."".$societestatic->getNomUrl(1).""; -if ($charge->metadata->source=="order"){ -$object = new Commande($db); -$object->fetch($charge->metadata->idsource); - print "".img_picto('', 'object_order')." ".$object->ref.""; -} elseif ($charge->metadata->source=="invoice"){ -$object = new Facture($db); -$object->fetch($charge->metadata->idsource); - print "".img_picto('', 'object_invoice')." ".$object->ref.""; -} - print "'.dol_print_date($charge->created,'%d/%m/%Y %H:%M').""; -if ($charge->refunded=='1'){ - print $langs->trans("refunded"); -} elseif ($charge->paid=='1'){ - print $langs->trans("".$charge->status.""); -} else { -$label="Message: ".$charge->failure_message."
"; -$label.="Réseau: ".$charge->outcome->network_status."
"; -$label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); - print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); -} - print "
'; -if ($charge->source->object=='card'){ - print $langs->trans("card"); -} -elseif ($charge->source->type=='card'){ - print $langs->trans("card"); -} elseif ($charge->source->type=='three_d_secure'){ - print $langs->trans("card3DS"); -} - print '".price(($charge->amount-$charge->amount_refunded)/100)."
'.dol_print_date($charge->created,'%d/%m/%Y %H:%M').""; + if ($charge->refunded=='1'){ + print $langs->trans("refunded"); + } elseif ($charge->paid=='1'){ + print $langs->trans("".$charge->status.""); + } else { + $label="Message: ".$charge->failure_message."
"; + $label.="Réseau: ".$charge->outcome->network_status."
"; + $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); + print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); + } + print "
'; + if ($charge->source->object=='card') + { + print $langs->trans("card"); + } + elseif ($charge->source->type=='card'){ + print $langs->trans("card"); + } elseif ($charge->source->type=='three_d_secure'){ + print $langs->trans("card3DS"); + } + print '".price(($charge->amount-$charge->amount_refunded)/100)."
'."\n"; + print '
'; + print '
' . "\n"; - print ''; - print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("Origin",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"","","",'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"'); - print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"","","",'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Paid",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder); - print_liste_field_titre("Fee",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder); - print "\n"; + print ''; + print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Origin", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "", "", "", 'align="center"', $sortfield, $sortorder); + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "", "", "", 'align="left"'); + print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "", "", "", 'align="left"', $sortfield, $sortorder); + print_liste_field_titre("Paid", $_SERVER["PHP_SELF"], "", "", "", 'align="right"', $sortfield, $sortorder); + print_liste_field_titre("Fee", $_SERVER["PHP_SELF"], "", "", "", 'align="right"', $sortfield, $sortorder); + print "\n"; - print "\n"; - -$txn=\Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripe->GetStripeAccount($conf->entity))); -foreach ($txn->data as $txn) { - print ''; - $societestatic->fetch($charge->metadata->idcustomer); - $societestatic->id=$charge->metadata->idcustomer; - $societestatic->lastname=$obj->lastname; - $societestatic->firstname=$obj->firstname; - $societestatic->admin=$obj->admin; - $societestatic->login=$obj->login; - $societestatic->email=$obj->email; - $societestatic->societe_id=$obj->fk_soc; + print "\n"; - // Ref - print "\n"; + $stripeaccount = $stripe->GetStripeAccount($conf->entity); + + $txn = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeaccount)); + + foreach ($txn->data as $txn) { + print ''; + $societestatic->fetch($charge->metadata->idcustomer); + $societestatic->id = $charge->metadata->idcustomer; + $societestatic->lastname = $obj->lastname; + $societestatic->firstname = $obj->firstname; + $societestatic->admin = $obj->admin; + $societestatic->login = $obj->login; + $societestatic->email = $obj->email; + $societestatic->societe_id = $obj->fk_soc; + + // Ref + print "\n"; // Employee - print "\n"; - // Origine + print "\n"; + // Origine print "\n"; + if ($charge->metadata->source == "order") { + $object = new Commande($db); + $object->fetch($charge->metadata->idsource); + print "" . img_picto('', 'object_order') . " " . $object->ref . ""; + } elseif ($txn->metadata->source == "invoice") { + $object = new Facture($db); + $object->fetch($txn->metadata->idsource); + print "" . img_picto('', 'object_invoice') . " " . $object->ref . ""; + } + print "\n"; // Date payment - print '\n"; - // Label payment - print "\n"; + // Label payment + print "\n"; - // Type - print ''; - // Amount - print ""; - print ""; - print "\n"; - } - print "
".$txn->source."
" . $txn->source . "".$societestatic->getNomUrl(1)."" . $societestatic->getNomUrl(1) . ""; -if ($charge->metadata->source=="order"){ -$object = new Commande($db); -$object->fetch($charge->metadata->idsource); - print "".img_picto('', 'object_order')." ".$object->ref.""; -} elseif ($txn->metadata->source=="invoice"){ -$object = new Facture($db); -$object->fetch($txn->metadata->idsource); - print "".img_picto('', 'object_invoice')." ".$object->ref.""; -} - print "'.dol_print_date($txn->created,'%d/%m/%Y %H:%M').""; + print '' . dol_print_date($txn->created, '%d/%m/%Y %H:%M') . ""; - print "'.$txn->type.'".price(($txn->amount)/100)."".price(($txn->fee)/100)."
"; - print ''; - print ''; -}else{ - -} + print "
' . $txn->type . '" . price(($txn->amount) / 100) . "" . price(($txn->fee) / 100) . "
"; + print ''; + print ''; +} else {} llxFooter(); $db->close(); From b07fdafa656238056b914a918c95eda18bc0c70e Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 19:57:22 +0100 Subject: [PATCH 48/91] Trans --- htdocs/langs/en_US/stripe.lang | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 12b23955bc8..4782294ef78 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -45,4 +45,5 @@ StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) StripeGateways=Stripe gateways OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...) -OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) \ No newline at end of file +OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...) +BankAccountForBankTransfer=Bank account for fund payouts \ No newline at end of file From e0af4f8489720ae7e5524b4b58fe34308beb826c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 19:58:11 +0100 Subject: [PATCH 49/91] Trans --- htdocs/langs/en_US/stripe.lang | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 4782294ef78..5c7b782f593 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -39,7 +39,7 @@ STRIPE_TEST_WEBHOOK_KEY=Webhook test key STRIPE_LIVE_SECRET_KEY=Secret live key STRIPE_LIVE_PUBLISHABLE_KEY=Publishable live key STRIPE_LIVE_WEBHOOK_KEY=Webhook live key -ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online payment is done (TODO When option to decrease stock is done on an action on invoice and the online payment generate itself the invoice ?) +ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online payment is done
(TODO When option to decrease stock is done on an action on invoice and the online payment generate itself the invoice ?) StripeLiveEnabled=Stripe live enabled (otherwise test/sandbox mode) StripeImportPayment=Import Stripe payments ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails) From bf1bada4351481f457c4a68a8b990c46d11de35b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:35:50 +0100 Subject: [PATCH 50/91] Contact tab after main tab --- htdocs/core/lib/fourn.lib.php | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/htdocs/core/lib/fourn.lib.php b/htdocs/core/lib/fourn.lib.php index 44e7774cae6..ac956abf524 100644 --- a/htdocs/core/lib/fourn.lib.php +++ b/htdocs/core/lib/fourn.lib.php @@ -34,7 +34,7 @@ function facturefourn_prepare_head($object) { global $db, $langs, $conf; - + $h = 0; $head = array(); @@ -102,7 +102,7 @@ function facturefourn_prepare_head($object) function ordersupplier_prepare_head($object) { global $db, $langs, $conf, $user; - + $h = 0; $head = array(); @@ -111,15 +111,6 @@ function ordersupplier_prepare_head($object) $head[$h][2] = 'card'; $h++; - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { - $langs->load("stocks"); - $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id; - $head[$h][1] = $langs->trans("OrderDispatch"); - $head[$h][2] = 'dispatch'; - $h++; - } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); @@ -130,7 +121,16 @@ function ordersupplier_prepare_head($object) $h++; } - // Show more tabs from modules + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) + { + $langs->load("stocks"); + $head[$h][0] = DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id; + $head[$h][1] = $langs->trans("OrderDispatch"); + $head[$h][2] = 'dispatch'; + $h++; + } + + // Show more tabs from modules // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab @@ -193,7 +193,7 @@ function supplierorder_admin_prepare_head() $head[$h][1] = $langs->trans("SuppliersInvoice"); $head[$h][2] = 'invoice'; $h++; - + $head[$h][0] = DOL_URL_ROOT."/admin/supplier_payment.php"; $head[$h][1] = $langs->trans("SuppliersPayment"); $head[$h][2] = 'supplierpayment'; From e983e0709f41acefda6e20790e9f67680a2d067d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:49:37 +0100 Subject: [PATCH 51/91] Fix not visible template selector for supplier order/invoice emails --- htdocs/fourn/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 40 +++++++++++++++++----------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index faf0cba82a8..13027312f44 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -2740,7 +2740,7 @@ elseif (! empty($object->id)) } // Presend form - $modelmail='supplier_order_send'; + $modelmail='order_supplier_send'; $defaulttopic='SendOrderRef'; $diroutput = $conf->fournisseur->commande->dir_output; $trackid = 'sor'.$object->id; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index c90336f8a4b..0ae8b0669c8 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -266,7 +266,7 @@ if (empty($reshook)) $action=''; } } - + // Delete link of credit note to invoice else if ($action == 'unlinkdiscount' && $user->rights->fournisseur->facture->creer) { @@ -388,7 +388,7 @@ if (empty($reshook)) elseif ($action == "setabsolutediscount" && $user->rights->fournisseur->facture->creer) { // POST[remise_id] or POST[remise_id_for_payment] - + // We use the credit to reduce amount of invoice if (! empty($_POST["remise_id"])) { $ret = $object->fetch($id); @@ -407,7 +407,7 @@ if (empty($reshook)) require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); - + //var_dump($object->getRemainToPay(0)); //var_dump($discount->amount_ttc);exit; if ($discount->amount_ttc > $object->getRemainToPay(0)) @@ -425,7 +425,7 @@ if (empty($reshook)) } } } - + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; @@ -437,7 +437,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -448,7 +448,7 @@ if (empty($reshook)) $object->fetch($id); $object->fetch_thirdparty(); //$object->fetch_lines(); // Already done into fetch - + // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) $discountcheck=new DiscountAbsolute($db); $result=$discountcheck->fetch(0,0,$object->id); @@ -459,9 +459,9 @@ if (empty($reshook)) if ($canconvert) { $db->begin(); - + $amount_ht = $amount_tva = $amount_ttc = array(); - + // Loop on each vat rate $i = 0; foreach ($object->lines as $line) @@ -474,7 +474,7 @@ if (empty($reshook)) $i ++; } } - + // Insert one discount by VAT rate category $discount = new DiscountAbsolute($db); if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) @@ -489,13 +489,13 @@ if (empty($reshook)) $discount->discount_type = 1; // Supplier discount $discount->fk_soc = $object->socid; $discount->fk_invoice_supplier_source = $object->id; - + $error = 0; - + if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT - + $sql = 'SELECT SUM(pf.amount) as total_paiements'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; @@ -509,7 +509,7 @@ if (empty($reshook)) $res = $db->fetch_object($resql); $total_paiements = $res->total_paiements; - + $discount->amount_ht = $discount->amount_ttc = $total_paiements - $object->total_ttc; $discount->amount_tva = 0; $discount->tva_tx = 0; @@ -519,7 +519,7 @@ if (empty($reshook)) { $error++; } - + } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { @@ -529,7 +529,7 @@ if (empty($reshook)) $discount->amount_tva = abs($amount_tva[$tva_tx]); $discount->amount_ttc = abs($amount_ttc[$tva_tx]); $discount->tva_tx = abs($tva_tx); - + $result = $discount->create($user); if ($result < 0) { @@ -537,9 +537,9 @@ if (empty($reshook)) break; } } - + } - + if (empty($error)) { if($object->type != FactureFournisseur::TYPE_DEPOSIT) { @@ -565,7 +565,7 @@ if (empty($reshook)) } } } - + // Delete payment elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) @@ -2141,7 +2141,7 @@ else $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')"; $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')"; } - + $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1); $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1); $absolute_discount = price2num($absolute_discount, 'MT'); @@ -3166,7 +3166,7 @@ else } // Presend form - $modelmail='order_supplier_send'; + $modelmail='invoice_supplier_send'; $defaulttopic='SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $trackid = 'sin'.$object->id; From ad96229ec420a8f91a0f5f222b05d82616146434 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:49:37 +0100 Subject: [PATCH 52/91] Fix not visible template selector for supplier order/invoice emails Conflicts: htdocs/fourn/facture/card.php --- htdocs/fourn/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index bd2d0591400..f083d71740e 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -2695,7 +2695,7 @@ elseif (! empty($object->id)) } // Presend form - $modelmail='supplier_order_send'; + $modelmail='order_supplier_send'; $defaulttopic='SendOrderRef'; $diroutput = $conf->fournisseur->commande->dir_output; $trackid = 'sor'.$object->id; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 99a50e08af8..0fc05bd7627 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -265,7 +265,7 @@ if (empty($reshook)) $action=''; } } - + elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); @@ -2928,7 +2928,7 @@ else } // Presend form - $modelmail='order_supplier_send'; + $modelmail='invoice_supplier_send'; $defaulttopic='SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $trackid = 'sin'.$object->id; From 2cd0122d3448f3da93332d65b86df9a8de44c105 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 20:59:23 +0100 Subject: [PATCH 53/91] Fix phpcs --- htdocs/stripe/charge.php | 2 +- htdocs/stripe/class/stripe.class.php | 18 +++++++++--------- htdocs/stripe/transaction.php | 6 +++--- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index d13235c4f01..9ba246cf9a8 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -68,7 +68,7 @@ else $service = 'StripeLive'; } -$stripeaccount = $stripe->GetStripeAccount($service); +$stripeaccount = $stripe->getStripeAccount($service); if (empty($stripeaccount)) { print $langs->trans('ErrorStripeAccountNotDefined'); diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 4ea45b7a4b3..a9df01d6acb 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -52,12 +52,12 @@ class Stripe extends CommonObject /** - * GetStripeAccount + * Return stripe account * * @param string $mode 'StripeTest' or 'StripeLive' * @return int ??? */ - public function GetStripeAccount($mode='StripeTest') + public function getStripeAccount($mode='StripeTest') { global $conf; @@ -90,12 +90,12 @@ class Stripe extends CommonObject } /** - * GetStripeCustomerAccount + * getStripeCustomerAccount * * @param int $id ??? * @return int ??? */ - public function GetStripeCustomerAccount($id) + public function getStripeCustomerAccount($id) { global $conf; @@ -122,13 +122,13 @@ class Stripe extends CommonObject /** - * CustomerStripe + * customerStripe * * @param int $id ??? * @param string $key ??? * @return \Stripe\StripeObject|\Stripe\ApiResource */ - public function CustomerStripe($id,$key) + public function customerStripe($id,$key) { global $conf; if (empty($conf->global->STRIPECONNECT_LIVE)) { @@ -186,7 +186,7 @@ class Stripe extends CommonObject } /** - * CreatePaymentStripe + * createPaymentStripe * * @param unknown $amount ??? * @param unknown $currency ??? @@ -197,7 +197,7 @@ class Stripe extends CommonObject * @param unknown $account ??? * @return Stripe */ - public function CreatePaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) + public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) { global $conf; if (empty($conf->global->STRIPECONNECT_LIVE)) { @@ -299,7 +299,7 @@ class Stripe extends CommonObject } elseif ($charge->source->type == 'three_d_secure') { $stripe = new Stripe($this->db); $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( - "stripe_account" => $stripe->GetStripeAccount($conf->entity) + "stripe_account" => $stripe->getStripeAccount($conf->entity) )); $return->message = $src->card->brand . " ****" . $src->card->last4; } else { diff --git a/htdocs/stripe/transaction.php b/htdocs/stripe/transaction.php index 143c34f7530..56d94c36dee 100644 --- a/htdocs/stripe/transaction.php +++ b/htdocs/stripe/transaction.php @@ -62,10 +62,10 @@ if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || emp } else { - $servie = 'StripeLive'; + $service = 'StripeLive'; } -$stripeaccount = $stripe->GetStripeAccount($service); +$stripeaccount = $stripe->getStripeAccount($service); if (empty($stripeaccount)) { print $langs->trans('ErrorStripeAccountNotDefined'); @@ -101,7 +101,7 @@ if (! $rowid && $stripeaccount) { print "
".$charge->id."".$charge->customer."".$societestatic->getNomUrl(1).""; + if ($societestatic->id > 0) + { + print $societestatic->getNomUrl(1); + } + if ($memberstatic->id > 0) + { + print $memberstatic->getNomUrl(1); + } + print ""; + print $FULLTAG; if ($charge->metadata->source=="order"){ $object = new Commande($db); $object->fetch($charge->metadata->idsource); @@ -132,21 +163,8 @@ if (!$rowid && $stripeaccount) print "".img_picto('', 'object_invoice')." ".$object->ref.""; } print "'.dol_print_date($charge->created,'%d/%m/%Y %H:%M').""; - if ($charge->refunded=='1'){ - print $langs->trans("refunded"); - } elseif ($charge->paid=='1'){ - print $langs->trans("".$charge->status.""); - } else { - $label="Message: ".$charge->failure_message."
"; - $label.="Réseau: ".$charge->outcome->network_status."
"; - $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); - print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); - } - print "
'; if ($charge->source->object=='card') @@ -161,6 +179,20 @@ if (!$rowid && $stripeaccount) print '".price(($charge->amount-$charge->amount_refunded)/100).""; + if ($charge->refunded=='1'){ + print $langs->trans("refunded"); + } elseif ($charge->paid=='1'){ + print $langs->trans("".$charge->status.""); + } else { + $label="Message: ".$charge->failure_message."
"; + $label.="Réseau: ".$charge->outcome->network_status."
"; + $label.="Statut: ".$langs->trans("".$charge->outcome->seller_message.""); + print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1); + } + print "
trans('RIB'); ?> rights->societe->creer) { ?> - control->tpl['image_edit']; ?> + control->tpl['image_edit']; ?>   diff --git a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php index 359f4ec7b44..fd9b3487f50 100644 --- a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php @@ -144,7 +144,7 @@ dol_fiche_head($head, 'card', $langs->trans("ThirdParty"),0,'company'); trans('RIB'); ?> rights->societe->creer) { ?> - control->tpl['image_edit']; ?> + control->tpl['image_edit']; ?>   diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index b936a431080..f7098d88478 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1662,7 +1662,7 @@ class Societe extends CommonObject return 1; } } - + /** * Definit la societe comme un client * @@ -1674,7 +1674,7 @@ class Societe extends CommonObject function set_remise_supplier($remise, $note, User $user) { global $conf, $langs; - + // Nettoyage parametres $note=trim($note); if (! $note) @@ -1682,15 +1682,15 @@ class Societe extends CommonObject $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason")); return -2; } - + dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id); - + if ($this->id) { $this->db->begin(); - + $now=dol_now(); - + // Positionne remise courante $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'"; @@ -1702,7 +1702,7 @@ class Societe extends CommonObject $this->error=$this->db->error(); return -1; } - + // Ecrit trace dans historique des remises $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier"; $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)"; @@ -1710,7 +1710,7 @@ class Societe extends CommonObject $sql.= " '".$this->db->escape($note)."',"; $sql.= " ".$user->id; $sql.= ")"; - + $resql=$this->db->query($sql); if (! $resql) { @@ -1718,7 +1718,7 @@ class Societe extends CommonObject $this->error=$this->db->lasterror(); return -1; } - + $this->db->commit(); return 1; } @@ -2037,7 +2037,7 @@ class Societe extends CommonObject else if ($option == 'ban') { $label.= '' . $langs->trans("ShowBan") . ''; - $linkstart = 'setAsDefault($id); // This will make sure there is only one default rib } - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; header('Location: '.$url); exit; } @@ -261,7 +261,7 @@ if (empty($reshook)) { $db->commit(); - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + $url=$_SERVER["PHP_SELF"].'?socid='.$object->id; header('Location: '.$url); exit; } @@ -332,19 +332,23 @@ if (empty($reshook)) $id = $savid; } -if (class_exists('Stripe')) +if (! empty($conf->stripe->enabled) && class_exists('Stripe')) { $stripe=new Stripe($db); - $customerstripe=$stripe->CustomerStripe($socid,$stripe->GetStripeAccount($conf->entity)); + + if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + else $service = 'StripeLive'; + + $customerstripe=$stripe->customerStripe($socid, $stripe->getStripeAccount($service)); if ($customerstripe->id) { - $cu = \Stripe\Customer::retrieve("".$customerstripe->id."");} + $cu = \Stripe\Customer::retrieve("".$customerstripe->id."");} $url=DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; if ($action == 'setassourcedefault') { $cu->default_source = "$source"; // obtained with Stripe.js $cu->save(); - + header('Location: '.$url); exit; } @@ -366,7 +370,7 @@ $form = new Form($db); $formfile = new FormFile($db); llxHeader(); - + $head=societe_prepare_head($object); if (! $id) @@ -381,14 +385,14 @@ if (empty($account->socid)) $account->socid=$object->id; if ($socid && $action == 'edit' && $user->rights->societe->creer) { - print '
'; + print ''; print ''; print ''; print ''; } if ($socid && $action == 'create' && $user->rights->societe->creer) { - print ''; + print ''; print ''; print ''; } @@ -414,9 +418,12 @@ if ($socid && $action != 'edit' && $action != "create") { print load_fiche_titre($langs->trans('StripeGateways'), '', ''); - if (is_object($stripe) && $stripe->GetStripeAccount($conf->entity)) + if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + else $service = 'StripeLive'; + + if (is_object($stripe) && $stripe->getStripeAccount($service)) { - $customerstripe=$stripe->CustomerStripe($object->id,$stripe->GetStripeAccount($conf->entity)); + $customerstripe=$stripe->customerStripe($object->id,$stripe->getStripeAccount($service)); } if ($customerstripe->id) { @@ -538,7 +545,7 @@ if ($socid && $action != 'edit' && $action != "create") // List of bank accounts - $morehtmlright=''.$langs->trans("Add").''; + $morehtmlright=''.$langs->trans("Add").''; print load_fiche_titre($langs->trans("AllRIB"), $morehtmlright, ''); @@ -636,7 +643,7 @@ if ($socid && $action != 'edit' && $action != "create") // Default print '
'; if (!$rib->default_rib) { - print ''; + print ''; print img_picto($langs->trans("Disabled"),'off'); print ''; } else { @@ -704,13 +711,13 @@ if ($socid && $action != 'edit' && $action != "create") print ''; if ($user->rights->societe->creer) { - print ''; + print ''; print img_picto($langs->trans("Modify"),'edit'); print ''; print ' '; - print ''; + print ''; print img_picto($langs->trans("Delete"),'delete'); print ''; } @@ -741,7 +748,7 @@ if ($socid && $action != 'edit' && $action != "create") if ($user->rights->societe->creer) { - print ''.$langs->trans("Add").''; + print ''.$langs->trans("Add").''; } print ''; @@ -879,7 +886,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print '
'.$langs->trans("WithdrawMode").''; $tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR")); - print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur')?GETPOST('frstrecur'):$account->frstrecur), 0); + print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur','alpha')?GETPOST('frstrecur','alpha'):$account->frstrecur), 0); print '
'; diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index a9df01d6acb..4167c6a0d81 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -200,6 +200,7 @@ class Stripe extends CommonObject public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account) { global $conf; + if (empty($conf->global->STRIPECONNECT_LIVE)) { $mode = 0; } else { @@ -292,6 +293,9 @@ class Stripe extends CommonObject if (isset($charge->id)) {} } + if (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')) $service = 'StripeTest'; + else $service = 'StripeLive'; + $return->statut = 'success'; $return->id = $charge->id; if ($charge->source->type == 'card') { @@ -299,7 +303,7 @@ class Stripe extends CommonObject } elseif ($charge->source->type == 'three_d_secure') { $stripe = new Stripe($this->db); $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array( - "stripe_account" => $stripe->getStripeAccount($conf->entity) + "stripe_account" => $stripe->getStripeAccount($service) )); $return->message = $src->card->brand . " ****" . $src->card->last4; } else { From 9f42e1b17238dff317d5c379fcd74171cabb10ce Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 22:33:40 +0100 Subject: [PATCH 56/91] Prepare code to introduce different payment modes than BAN --- .../class/bonprelevement.class.php | 8 ++------ .../class/companybankaccount.class.php | 19 ++++++++++--------- htdocs/societe/class/societe.class.php | 2 +- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index d0aa788fe48..e2517bdfada 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -726,16 +726,12 @@ class BonPrelevement extends CommonObject $sql = "SELECT count(f.rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql.= " WHERE f.fk_statut = 1"; $sql.= " AND f.entity = ".$conf->entity; $sql.= " AND f.rowid = pfd.fk_facture"; $sql.= " AND f.paye = 0"; $sql.= " AND pfd.traite = 0"; $sql.= " AND f.total_ttc > 0"; - //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; dol_syslog(get_class($this)."::SommeAPrelever"); $resql = $this->db->query($sql); @@ -805,9 +801,8 @@ class BonPrelevement extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql.= " WHERE f.rowid = pfd.fk_facture"; - $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.entity IN (".getEntity('facture').')'; $sql.= " AND s.rowid = f.fk_soc"; //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; $sql.= " AND f.fk_statut = 1"; @@ -1340,6 +1335,7 @@ class BonPrelevement extends CommonObject $sql.= " AND soc.rowid = f.fk_soc"; $sql.= " AND rib.fk_soc = f.fk_soc"; $sql.= " AND rib.default_rib = 1"; + $sql.= " AND rib.type = 'ban'"; //print $sql; // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice. diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index 428f5b96f42..97c8871202e 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -72,7 +72,7 @@ class CompanyBankAccount extends Account $now = dol_now(); $error = 0; // Correct default_rib to be sure to have always one default - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1"; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1 AND type = 'ban'"; $result = $this->db->query($sql); if ($result) { @@ -81,8 +81,8 @@ class CompanyBankAccount extends Account if (empty($this->default_rib) && $numrows == 0) $this->default_rib = 1; } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, datec)"; - $sql.= " VALUES (".$this->socid.", '".$this->db->idate($now)."')"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, type, datec)"; + $sql.= " VALUES (".$this->socid.", 'ban', '".$this->db->idate($now)."')"; $resql=$this->db->query($sql); if ($resql) { @@ -204,7 +204,7 @@ class CompanyBankAccount extends Account { if (empty($id) && empty($socid)) return -1; - $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; + $sql = "SELECT rowid, type, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; if ($id) $sql.= " WHERE rowid = ".$id; @@ -220,6 +220,7 @@ class CompanyBankAccount extends Account $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref $this->id = $obj->rowid; + $this->type = $obj->type; $this->socid = $obj->fk_soc; $this->bank = $obj->bank; $this->code_banque = $obj->code_banque; @@ -321,7 +322,7 @@ class CompanyBankAccount extends Account } /** - * Set RIB as Default + * Set a BAN as Default * * @param int $rib RIB id * @return int 0 if KO, 1 if OK @@ -345,13 +346,13 @@ class CompanyBankAccount extends Account $this->db->begin(); - $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0 "; - $sql2.= "WHERE fk_soc = ".$obj->fk_soc; + $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0"; + $sql2.= " WHERE type = 'ban' AND fk_soc = ".$obj->fk_soc; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result2 = $this->db->query($sql2); - $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1 "; - $sql3.= "WHERE rowid = ".$obj->id; + $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1"; + $sql3.= " WHERE rowid = ".$obj->id; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result3 = $this->db->query($sql3); diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index f7098d88478..dbf3015ba1e 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -2433,7 +2433,7 @@ class Societe extends CommonObject function get_all_rib() { require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id; $result = $this->db->query($sql); if (!$result) { $this->error++; From 3ad95e46c0a8a506ea46590161b17cb55834c6fa Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 22:40:42 +0100 Subject: [PATCH 57/91] Fix phpunit --- htdocs/install/mysql/tables/llx_oauth_token.sql | 2 +- test/phpunit/CodingSqlTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/install/mysql/tables/llx_oauth_token.sql b/htdocs/install/mysql/tables/llx_oauth_token.sql index 5c7d6d62177..81ae99c6ce6 100644 --- a/htdocs/install/mysql/tables/llx_oauth_token.sql +++ b/htdocs/install/mysql/tables/llx_oauth_token.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_oauth_token ( rowid integer AUTO_INCREMENT PRIMARY KEY, service varchar(36), token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2 - tokenstring text, -- token in json format '{ "access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write" } + tokenstring text, -- token in json format '{"access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write"} fk_user integer, fk_adherent integer, entity integer DEFAULT 1 diff --git a/test/phpunit/CodingSqlTest.php b/test/phpunit/CodingSqlTest.php index 0b29b29240d..57be8fc62a9 100644 --- a/test/phpunit/CodingSqlTest.php +++ b/test/phpunit/CodingSqlTest.php @@ -163,10 +163,10 @@ class CodingSqlTest extends PHPUnit_Framework_TestCase $result=strpos($filecontent,'"'); if ($result) { - $result=! strpos($filecontent,'["'); + $result=(! strpos($filecontent,'["') && ! strpos($filecontent,'{"')); } print __METHOD__." Result for checking we don't have double quote = ".$result."\n"; - $this->assertTrue($result===false, 'Found double quote that is not [" (used for json content) into '.$file.'. Bad.'); + $this->assertTrue($result===false, 'Found double quote that is not [" neither {" (used for json content) into '.$file.'. Bad.'); $result=strpos($filecontent,'int('); print __METHOD__." Result for checking we don't have 'int(' instead of 'integer' = ".$result."\n"; From b68b66edcb0c08e4799a28b339d4b43cda4938bd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Thu, 8 Mar 2018 23:16:55 +0100 Subject: [PATCH 58/91] Fix phpcs --- htdocs/stripe/class/stripe.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index 4167c6a0d81..a87d80c265e 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -319,9 +319,9 @@ class Stripe extends CommonObject $return->type = $err['type']; $return->code = $err['code']; $return->message = $err['message']; - $body = "Une erreur de paiement est survenue. Voici le code d'erreur:
" . $return->id . " " . $return->message . " "; + $body = "Error:
" . $return->id . " " . $return->message . " "; $subject = '[NOTIFICATION] Erreur de paiement'; - $headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; + $headers = 'From: "noreply" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>'; mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers); $error ++; dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe'); From 82057b35233fa22d72c2f6978647c49531d4f3d2 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 08:11:02 +0100 Subject: [PATCH 59/91] Fix: use code instead id --- htdocs/compta/facture/list.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 8319f42bd97..987ed926986 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -276,7 +276,7 @@ if ($massaction == 'withdrawrequest') $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); } - if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ + if (!($objecttmp->statut > Facture::STATUS_DRAFT)){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); } @@ -298,11 +298,11 @@ if ($massaction == 'withdrawrequest') $numprlv = $db->num_rows($result_sql); } - if($numprlv>0){ + if ($numprlv>0){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); } - if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ + if (!empty($objecttmp->mode_reglement_code ) && $objecttmp->mode_reglement_code != 'PRE'){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); } From ea175cd6c176c3722c627d7be26cf398dfd267a8 Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 09:37:23 +0100 Subject: [PATCH 60/91] Fix: compatibility with multicompany dictionnary sharing --- htdocs/comm/propal/card.php | 2 +- htdocs/commande/card.php | 2 +- htdocs/fourn/facture/card.php | 2 +- htdocs/supplier_proposal/card.php | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 2e9c184dd11..0b5fcd547e7 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1371,7 +1371,7 @@ if ($action == 'create') $soc = $objectsrc->thirdparty; - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index cf70d422130..f11c4778b0b 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1450,7 +1450,7 @@ if ($action == 'create' && $user->rights->commande->creer) $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 0ae8b0669c8..5b1be2239f1 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1626,7 +1626,7 @@ if ($action == 'create') //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 5585d3ba87b..e12e1e34505 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -998,7 +998,7 @@ if ($action == 'create') $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1056,7 +1056,7 @@ if ($action == 'create') if ($soc->id > 0) { // Discounts for third party - print '' . $langs->trans('Discounts') . ''; + print '' . $langs->trans('Discounts') . ''; $absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1); From f4f81482e776010fa42492da348a10d5524da75d Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 09:39:57 +0100 Subject: [PATCH 61/91] Fix: add todo if you use the good id by entities --- htdocs/fourn/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 5b1be2239f1..d69e1be6c3a 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1626,7 +1626,7 @@ if ($action == 'create') //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); // TODO maybe add default value option $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); From 3eeeaf2d2dd59ed4b7527ff360fd9f7c12ff8f2f Mon Sep 17 00:00:00 2001 From: Regis Houssin Date: Fri, 9 Mar 2018 12:54:34 +0100 Subject: [PATCH 62/91] Fix: REST API must be enabled for all entities --- htdocs/api/admin/index.php | 8 ++++---- htdocs/core/modules/modApi.class.php | 29 ++++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index 57efe8d7cb9..7ebff2c5da6 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -1,9 +1,9 @@ +/* Copyright (C) 2004 Rodolphe Quiedeville * Copyright (C) 2005-2016 Laurent Destailleur * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2012 Regis Houssin - * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2012-2018 Regis Houssin + * Copyright (C) 2015 Jean-François Ferry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -41,7 +41,7 @@ if ($action == 'setproductionmode') { $status = GETPOST('status','alpha'); - if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', $conf->entity) > 0) + if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) { $error=0; diff --git a/htdocs/core/modules/modApi.class.php b/htdocs/core/modules/modApi.class.php index 3e27031fd6f..24d784585d3 100644 --- a/htdocs/core/modules/modApi.class.php +++ b/htdocs/core/modules/modApi.class.php @@ -1,7 +1,8 @@ - * Copyright (C) 2004-2012 Laurent Destailleur - * Copyright (C) 2015 Jean-François Ferry +/* Copyright (C) 2003 Rodolphe Quiedeville + * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -60,12 +61,13 @@ class modApi extends DolibarrModules $this->version = 'dolibarr'; // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + // Can be enabled / disabled only in the main company with superadmin account + $this->core_enabled = 1; // Name of image file used for this module. // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' $this->picto='technic'; - $this->module_parts = array(); // Data directories to create when module is enabled. @@ -230,5 +232,24 @@ class modApi extends DolibarrModules return $this->_init($sql, $options); } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted. + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + function remove($options = '') + { + // Remove old constants with entity fields different of 0 + $sql = array( + "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = ".$this->db->encrypt('MAIN_MODULE_API', 1), + "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = ".$this->db->encrypt('API_PRODUCTION_MODE', 1) + ); + + return $this->_remove($sql, $options); + } } From d6b4bc14e4f7e42c784ffb903980d8732dc0cf71 Mon Sep 17 00:00:00 2001 From: Marc de Lima Lucio Date: Fri, 9 Mar 2018 16:52:06 +0100 Subject: [PATCH 63/91] NEW: syslog file autoclean --- htdocs/admin/syslog.php | 17 ++++ htdocs/core/class/utils.class.php | 112 +++++++++++++++++++++++- htdocs/core/modules/modSyslog.class.php | 5 ++ htdocs/langs/en_US/admin.lang | 3 + 4 files changed, 135 insertions(+), 2 deletions(-) diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php index d850e7eeb11..e434f669f45 100644 --- a/htdocs/admin/syslog.php +++ b/htdocs/admin/syslog.php @@ -146,6 +146,16 @@ if ($action == 'setlevel') dol_syslog("admin/syslog: level ".$level); if (! $res > 0) $error++; + + if (! $error) + { + $file_saves = GETPOST("file_saves"); + $res = dolibarr_set_const($db,"SYSLOG_FILE_SAVES",$file_saves,'chaine',0,'',0); + dol_syslog("admin/syslog: file saves ".$file_saves); + + if (! $res > 0) $error++; + } + if (! $error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -284,6 +294,13 @@ print ''; print ''; print ''; + +if(! empty($conf->loghandlers['mod_syslog_file']) && ! empty($conf->cron->enabled)) { + print ''.$langs->trans("SyslogFileNumberOfSaves").''; + print ''; + print ' ('.$langs->trans('ConfigureCleaningCronjobToSetFrequencyOfSaves').')'; +} + print ''; print "\n"; diff --git a/htdocs/core/class/utils.class.php b/htdocs/core/class/utils.class.php index 37ccea748f1..e60070f1179 100644 --- a/htdocs/core/class/utils.class.php +++ b/htdocs/core/class/utils.class.php @@ -93,7 +93,7 @@ class Utils // Define files log if ($dolibarr_main_data_root) { - $filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); + $filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); } $filelog=''; @@ -668,4 +668,112 @@ class Utils return -1; } -} + + /** + * This saves syslog files and compresses older ones + * Used from cronjob + * + * @return int 0 if OK, < 0 if KO + */ + function compressSyslogs() { + global $conf; + + if(empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled + return 0; + } + + if(! function_exists('gzopen')) { + return -1; + } + + dol_include_once('/core/lib/files.lib.php'); + + $nbSaves = ! empty($conf->global->SYSLOG_FILE_SAVES) ? intval($conf->global->SYSLOG_FILE_SAVES) : 14; + + if(empty($conf->global->SYSLOG_FILE)) { + $mainlogdir = DOL_DATA_ROOT; + $mainlog = 'dolibarr.log'; + } else { + $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE); + $mainlogdir = dirname($mainlogfull); + $mainlog = basename($mainlogfull); + } + + $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log + $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir); + + foreach($tabfiles as $file) { + + $logname = $file['name']; + $logpath = $file['path']; + + // Handle already compressed files + + $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$'; + + $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter); + $gzfiles = array(); + + foreach($gzfilestmp as $gzfile) { + $tabmatches = array(); + preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches); + + $numsave = intval($tabmatches[1]); + + $gzfiles[$numsave] = $gzfile; + } + + krsort($gzfiles, SORT_NUMERIC); + + foreach($gzfiles as $numsave => $dummy) { + if(dol_is_file($logpath.'/'.$logname.'.'.($numsave+1).'.gz')) { + return -2; + } + + if($numsave >= $nbSaves) { + dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz'); + } else { + dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave+1).'.gz', 0, 1, 0, 0); + } + } + + // Compress last save + + if(dol_is_file($logpath.'/'.$logname.'.1')) { + if($nbSaves > 1) { + $gzfilehandle = gzopen($logpath.'/'.$logname.'.2.gz', 'wb9'); + + if(empty($gzfilehandle)) { + return -3; + } + + $sourcehandle = fopen($logpath.'/'.$logname.'.1', 'r'); + + if(empty($sourcehandle)) { + return -4; + } + + while(! feof($sourcehandle)) { + gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time + } + + fclose($sourcehandle); + gzclose($gzfilehandle); + } else { + dol_delete_file($logpath.'/'.$logname.'.1'); + } + } + + // Compress current file et recreate it + + if(dol_is_file($logpath.'/'.$logname)) { + if(dol_move($logpath.'/'.$logname, $logpath.'/'.$logname.'.1', 0, 1, 0, 0)) { + $newlog = fopen($logpath.'/'.$logname, 'a+'); + fclose($newlog); + } + } + } + + return 0; + } +} \ No newline at end of file diff --git a/htdocs/core/modules/modSyslog.class.php b/htdocs/core/modules/modSyslog.class.php index 97c7b71ae21..8c84214ca47 100644 --- a/htdocs/core/modules/modSyslog.class.php +++ b/htdocs/core/modules/modSyslog.class.php @@ -79,5 +79,10 @@ class modSyslog extends DolibarrModules // Permissions $this->rights = array(); $this->rights_class = 'syslog'; + + // Cronjobs + $this->cronjobs = array( + 0=>array('label'=>'CompressSyslogs', 'jobtype'=>'method', 'class'=>'core/class/utils.class.php', 'objectname'=>'Utils', 'method'=>'compressSyslogs', 'parameters'=>'', 'comment'=>'PurgeDeleteTemporaryFiles', 'frequency'=>1, 'unitfrequency'=> 3600 * 24, 'priority'=>50, 'status'=>1, 'test'=>true), + ); } } diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index d6514db4d2c..6648e43501e 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -1444,6 +1444,9 @@ SyslogFilename=File name and path YouCanUseDOL_DATA_ROOT=You can use DOL_DATA_ROOT/dolibarr.log for a log file in Dolibarr "documents" directory. You can set a different path to store this file. ErrorUnknownSyslogConstant=Constant %s is not a known Syslog constant OnlyWindowsLOG_USER=Windows only supports LOG_USER +CompressSyslogs=Syslog files compression and backup +SyslogFileNumberOfSaves=Log backups +ConfigureCleaningCronjobToSetFrequencyOfSaves=Configure cleaning scheduled job to set log backup frequency ##### Donations ##### DonationsSetup=Donation module setup DonationsReceiptModel=Template of donation receipt From 164ca682d52282e0f77297c6c1ab7474aeb3a18e Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 17:23:43 +0100 Subject: [PATCH 64/91] fix add "late" invoice into "save last search/backtolist" feature --- htdocs/compta/facture/list.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 880a18d501a..0ed7f28ad54 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -96,7 +96,7 @@ $day_lim = GETPOST('day_lim','int'); $month_lim = GETPOST('month_lim','int'); $year_lim = GETPOST('year_lim','int'); -$option = GETPOST('option'); +$option = GETPOST('search_option'); if ($option == 'late') { $search_status = '1'; } @@ -560,7 +560,7 @@ if ($resql) if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode); if ($show_files) $param.='&show_files=' .$show_files; - if ($option) $param.="&option=".$option; + if ($option) $param.="&search_option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -714,7 +714,7 @@ if ($resql) if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; print ''; $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5, 0, 0, '', 'width75'); - print '
'.$langs->trans("Late"); + print '
'.$langs->trans("Late"); print ''; } // Project From d763bfcbf159d406ca2613537ee419660d921ecd Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Fri, 9 Mar 2018 17:56:49 +0100 Subject: [PATCH 65/91] Fix set time limit to 0 If the dolibarr was installed on a pc and not on server or in the doliwamp. --- htdocs/admin/system/filecheck.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index 38cf0b3f0df..7a0a4745996 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -3,6 +3,7 @@ * Copyright (C) 2007 Rodolphe Quiedeville * Copyright (C) 2007-2012 Regis Houssin * Copyright (C) 2015 Frederic France + * Copyright (C) 2017 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,7 +23,7 @@ * \file htdocs/admin/system/filecheck.php * \brief Page to check Dolibarr files integrity */ - +set_time_limit(0); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; From 5a56e802d9bcdc39409394539a98153b16d18033 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:10:52 +0100 Subject: [PATCH 66/91] FIX #8232 --- htdocs/core/class/commonobject.class.php | 4 +++- htdocs/core/tpl/extrafields_view.tpl.php | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 54eeffdc4b6..a632a29b0f3 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5835,9 +5835,11 @@ abstract class CommonObject jQuery(document).ready(function() { function showOptions(child_list, parent_list) { - var val = $("select[name=\"options_"+parent_list+"\"]").val(); + var val = $("select[name="+parent_list+"]").val(); + var parentVal = parent_list + ":" + val; if(val > 0) { + $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); } else { diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index 3559df44c9c..e7abadac599 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -151,7 +151,7 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ jQuery(document).ready(function() { function showOptions(child_list, parent_list) { - var val = $("select[name=\"options_"+parent_list+"\"]").val(); + var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); From 02beed265eac5f9e6acd27c7fccafe6e96301973 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:14:43 +0100 Subject: [PATCH 67/91] better space --- htdocs/core/class/commonobject.class.php | 3 +-- htdocs/core/tpl/extrafields_view.tpl.php | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index a632a29b0f3..d9e08070f8b 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5836,10 +5836,9 @@ abstract class CommonObject function showOptions(child_list, parent_list) { var val = $("select[name="+parent_list+"]").val(); - var parentVal = parent_list + ":" + val; - if(val > 0) { + if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); } else { diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index e7abadac599..dffd0e739f6 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -153,6 +153,7 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ { var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; + if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); From 42fed5981d2f5617188d55ce0c6be73263255856 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:16:06 +0100 Subject: [PATCH 68/91] bettre syntax --- htdocs/core/class/commonobject.class.php | 1 - htdocs/core/tpl/extrafields_view.tpl.php | 1 - 2 files changed, 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index d9e08070f8b..d55e564d774 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5837,7 +5837,6 @@ abstract class CommonObject { var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; - if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index dffd0e739f6..e7abadac599 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -153,7 +153,6 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ { var val = $("select[name="+parent_list+"]").val(); var parentVal = parent_list + ":" + val; - if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show(); From bb8525614c1dcdbccce8f036bfb874a7231480c9 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 19:37:39 +0100 Subject: [PATCH 69/91] better fix --- htdocs/admin/expensereport.php | 2 +- htdocs/admin/expensereport_extrafields.php | 2 +- htdocs/admin/expensereport_ik.php | 32 ++++++------ htdocs/admin/expensereport_rules.php | 60 +++++++++++----------- 4 files changed, 48 insertions(+), 48 deletions(-) diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php index 3806a17c99f..28ced963f87 100644 --- a/htdocs/admin/expensereport.php +++ b/htdocs/admin/expensereport.php @@ -195,7 +195,7 @@ else if ($action == 'setoptions') $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php index db06f06d84a..a83c9b04194 100644 --- a/htdocs/admin/expensereport_extrafields.php +++ b/htdocs/admin/expensereport_extrafields.php @@ -67,7 +67,7 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; $textobject=$langs->transnoentitiesnoconv("expensereports"); -llxHeader('',$langs->trans("expensereportsSetup")); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("ExpenseReportsSetup"),$linkback,'title_setup'); diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php index a3bb7c4fc91..adf18433caa 100644 --- a/htdocs/admin/expensereport_ik.php +++ b/htdocs/admin/expensereport_ik.php @@ -58,12 +58,12 @@ if ($action == 'updateik') $result = $expIk->fetch($id); if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); } - + $expIk->setValues($_POST); $result = $expIk->create($user); - + if ($result > 0) setEventMessages('SetupSaved', null, 'mesgs'); - + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -74,11 +74,11 @@ elseif ($action == 'delete') // TODO add confirm { $result = $expIk->fetch($id); if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); - + $expIk->delete($user); } - - + + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -89,7 +89,7 @@ $rangesbycateg = ExpenseReportIk::getAllRanges(); * View */ -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -125,23 +125,23 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) echo ''.$langs->trans('expenseReportTotalForFive').''; echo ' '; echo ''; - + if ($Tab['active'] == 0) continue; - + $tranche=1; $var = true; foreach ($Tab['ranges'] as $k => $range) { if (isset($Tab['ranges'][$k+1])) $label = $langs->trans('expenseReportRangeFromTo', $range->range_ik, ($Tab['ranges'][$k+1]->range_ik-1)); else $label = $langs->trans('expenseReportRangeMoreThan', $range->range_ik); - + if ($range->range_active == 0) $label = $form->textwithpicto($label, $langs->trans('expenseReportRangeDisabled'), 1, 'help', '', 0, 3); - + echo ''; - + // Label echo '['.$langs->trans('RangeNum', $tranche++).'] - '.$label.''; - + // Offset echo ''; if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; @@ -152,10 +152,10 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; else echo ($range->ik->id > 0 ? $range->ik->coef : $langs->trans('expenseReportCoefUndefined')); echo ''; - + // Total for one echo ''.$langs->trans('expenseReportPrintExample', price($range->ik->offset + 5 * $range->ik->coef)).''; - + // Action echo ''; if ($range->range_active == 1) @@ -173,7 +173,7 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) } } echo ''; - + echo ''; $var=!$var; } diff --git a/htdocs/admin/expensereport_rules.php b/htdocs/admin/expensereport_rules.php index 26312f708d9..bf615676f81 100644 --- a/htdocs/admin/expensereport_rules.php +++ b/htdocs/admin/expensereport_rules.php @@ -57,17 +57,17 @@ $amount = GETPOST('amount'); $restrictive = GETPOST('restrictive'); $object = new ExpenseReportRule($db); -if (!empty($id)) +if (!empty($id)) { $result = $object->fetch($id); if ($result < 0) dol_print_error('', $object->error, $object->errors); } - + // TODO do action if ($action == 'save') { $error = 0; - + // check parameters if (empty($apply_to)) { $error++; @@ -93,11 +93,11 @@ if ($action == 'save') $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportLimitAmount")), null, 'errors'); } - + if (empty($error)) { $object->setValues($_POST); - + if($apply_to=='U'){ $object->fk_user=$fk_user; $object->fk_usergroup=0; @@ -114,13 +114,13 @@ if ($action == 'save') $object->dates = $dates; $object->datee = $datee; - + $object->entity = $conf->entity; $res = $object->create($user); if ($res > 0) setEventMessages($langs->trans('ExpenseReportRuleSave'), null); else dol_print_error($object->db); - + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -129,7 +129,7 @@ elseif ($action == 'delete') { // TODO add confirm $res = $object->delete($user); - + if ($res < 0) dol_print_error($object->db); header('Location: '.$_SERVER['PHP_SELF']); @@ -145,7 +145,7 @@ $tab_rules_type = array('EX_DAY' => $langs->trans('Day'), 'EX_MON' => $langs->tr * View */ -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -194,7 +194,7 @@ if ($action != 'edit') echo ''; echo ''; - echo ''; + echo ''; } @@ -224,7 +224,7 @@ $var=true; foreach ($rules as $rule) { echo ''; - + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -240,8 +240,8 @@ foreach ($rules as $rule) elseif ($rule->fk_user > 0) echo $tab_apply['U'].' ('.$rule->getUserName().')'; } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -250,7 +250,7 @@ foreach ($rules as $rule) else { if ($rule->fk_c_type_fees == -1) echo $langs->trans('AllExpenseReport'); - else + else { $key = getDictvalue(MAIN_DB_PREFIX.'c_type_fees', 'code', $rule->fk_c_type_fees, false, 'id'); if ($key != $langs->trans($key)) echo $langs->trans($key); @@ -258,9 +258,9 @@ foreach ($rules as $rule) } } echo ''; - - - + + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -271,8 +271,8 @@ foreach ($rules as $rule) echo $tab_rules_type[$rule->code_expense_rules_type]; } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -283,8 +283,8 @@ foreach ($rules as $rule) echo dol_print_date($rule->dates, 'day'); } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -295,8 +295,8 @@ foreach ($rules as $rule) echo dol_print_date($rule->datee, 'day'); } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -307,8 +307,8 @@ foreach ($rules as $rule) echo price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency); } echo ''; - - + + echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -319,8 +319,8 @@ foreach ($rules as $rule) echo yn($rule->restrictive, 1, 1); } echo ''; - - + + echo ''; if ($object->id != $rule->id) { @@ -333,7 +333,7 @@ foreach ($rules as $rule) echo ''.$langs->trans('Cancel').''; } echo ''; - + echo ''; $var=!$var; } @@ -355,9 +355,9 @@ echo ''; dol_fiche_end(); From d858426b7b5735775181359cc82d38b6f365d065 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 22:33:39 +0100 Subject: [PATCH 70/91] Update modSyslog.class.php --- htdocs/core/modules/modSyslog.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/modSyslog.class.php b/htdocs/core/modules/modSyslog.class.php index 8c84214ca47..b3e83f90ca2 100644 --- a/htdocs/core/modules/modSyslog.class.php +++ b/htdocs/core/modules/modSyslog.class.php @@ -82,7 +82,7 @@ class modSyslog extends DolibarrModules // Cronjobs $this->cronjobs = array( - 0=>array('label'=>'CompressSyslogs', 'jobtype'=>'method', 'class'=>'core/class/utils.class.php', 'objectname'=>'Utils', 'method'=>'compressSyslogs', 'parameters'=>'', 'comment'=>'PurgeDeleteTemporaryFiles', 'frequency'=>1, 'unitfrequency'=> 3600 * 24, 'priority'=>50, 'status'=>1, 'test'=>true), + 0=>array('label'=>'CompressSyslogs', 'jobtype'=>'method', 'class'=>'core/class/utils.class.php', 'objectname'=>'Utils', 'method'=>'compressSyslogs', 'parameters'=>'', 'comment'=>'PurgeDeleteTemporaryFiles', 'frequency'=>1, 'unitfrequency'=> 3600 * 24, 'priority'=>50, 'status'=>0, 'test'=>true), ); } } From a34709c112a4fb2a9425eaf1699d9d7d03b0ce33 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Fri, 9 Mar 2018 22:36:00 +0100 Subject: [PATCH 71/91] fix better thirdparty link --- htdocs/comm/index.php | 2 +- htdocs/comm/propal/card.php | 2 +- htdocs/comm/propal/contact.php | 2 +- htdocs/comm/propal/document.php | 2 +- htdocs/compta/facture/card.php | 2 +- htdocs/compta/facture/contact.php | 2 +- htdocs/compta/facture/document.php | 2 +- htdocs/compta/facture/info.php | 2 +- htdocs/compta/facture/note.php | 2 +- htdocs/compta/index.php | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 91004c86f67..5ec77389f63 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -266,7 +266,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas=$obj->canvas; - print $companystatic->getNomUrl(1,'customer',16); + print $companystatic->getNomUrl(1,'supplier',16); print ''; print ''.price($obj->total_ht).''; $i++; diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 60db23814b3..51a1caa9502 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1824,7 +1824,7 @@ if ($action == 'create') $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherProposals").')'; // Project if (! empty($conf->projet->enabled)) diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 01e851769a7..eff22ba4358 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -164,7 +164,7 @@ if ($object->id > 0) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index ba373c78f44..e292a61686e 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -114,7 +114,7 @@ if ($object->id > 0) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 37f38b732fe..4807ac3dddd 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -3270,7 +3270,7 @@ else if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; // Project if (! empty($conf->projet->enabled)) diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index 2c95366f9a9..61f37d221f8 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -155,7 +155,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index 8b76f9b167f..a9396e445c9 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -125,7 +125,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/info.php b/htdocs/compta/facture/info.php index 00272fee9b3..2347178b05d 100644 --- a/htdocs/compta/facture/info.php +++ b/htdocs/compta/facture/info.php @@ -69,7 +69,7 @@ $morehtmlref='
'; $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty -$morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); +$morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index 755ac413743..356ba3916a0 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -92,7 +92,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index c36037940b9..12a4ecee052 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -199,7 +199,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print $facturestatic->getNomUrl(1,''); print ''; print ''; - print $companystatic->getNomUrl(1,'',16); + print $companystatic->getNomUrl(1,'customer',16); print ''; print ''.price($obj->total_ttc).''; print ''; From 40d04482b030e4b697e23fcb51e37b00f7b2d47b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 22:45:16 +0100 Subject: [PATCH 72/91] Fix set time --- htdocs/admin/system/filecheck.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index 7a0a4745996..6fd623bf1bb 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -23,7 +23,7 @@ * \file htdocs/admin/system/filecheck.php * \brief Page to check Dolibarr files integrity */ -set_time_limit(0); + require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; @@ -40,6 +40,8 @@ $error=0; * View */ +@set_time_limit(300); + llxHeader(); print load_fiche_titre($langs->trans("FileCheckDolibarr"),'','title_setup'); From 42aa7a25f904c3ff63a1b9cf073d8e73a314d70c Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Fri, 9 Mar 2018 22:54:45 +0100 Subject: [PATCH 73/91] FIX include cache issue --- htdocs/modulebuilder/index.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 3b2e36e21d8..1058f38ffd2 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -490,8 +490,7 @@ if ($dirins && $action == 'addproperty' && !empty($module) && ! empty($tabobj)) setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); - sleep(4); // With sleep 2, after the header("Location...", the new page output does not see the change. TODO Why do we need this sleep ? - + // Make a redirect to reload all data header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.'&tabobj='.$objectname.'&nocache='.time()); @@ -526,8 +525,7 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); - sleep(4); // With sleep 2, after the header("Location...", the new page output does not see the change. TODO Why do we need this sleep ? - + // Make a redirect to reload all data header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.'&tabobj='.$objectname); @@ -1550,6 +1548,8 @@ elseif (! empty($module)) print '


'; + opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! + if (empty($forceddirread)) { $result = dol_include_once($pathtoclass); From 9efea6e30ec4848eddd1a1d82d7996ed516a78fa Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 22:59:44 +0100 Subject: [PATCH 74/91] Fix var not defined --- htdocs/adherents/class/adherent.class.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 20041333ee6..c55e1bb3fc1 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -33,7 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; /** @@ -1429,8 +1429,8 @@ class Adherent extends CommonObject $result=$customer->create_from_member($this, $companyname, $companyalias); if ($result < 0) { - $this->error = $company->error; - $this->errors = $company->errors; + $this->error = $customer->error; + $this->errors = $customer->errors; $error++; } else From 1d69d8e51ebe6b9e65c0e3f3c7c1325f181ba9b8 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Fri, 9 Mar 2018 23:03:23 +0100 Subject: [PATCH 75/91] add function_exist --- htdocs/modulebuilder/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 1058f38ffd2..dbc69c943dd 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -1548,7 +1548,7 @@ elseif (! empty($module)) print '


'; - opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! + if(function_exists('opcache_invalidate')) opcache_invalidate($dirread.'/'.$pathtoclass,true); // remove the include cache hell ! if (empty($forceddirread)) { From c1d148458bb05c5633f34fbd9f46ede563d7a86c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 9 Mar 2018 23:44:00 +0100 Subject: [PATCH 76/91] Fix migration --- htdocs/install/mysql/migration/7.0.0-8.0.0.sql | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 227562ea9bc..7c82c54fb94 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -32,6 +32,10 @@ -- VMYSQL4.1 ALTER TABLE llx_product_association ADD COLUMN rowid integer AUTO_INCREMENT PRIMARY KEY; +ALTER TABLE llx_website_page ADD COLUMN fk_user_create integer; +ALTER TABLE llx_website_page ADD COLUMN fk_user_modif integer; +ALTER TABLE llx_website_page ADD COLUMN type_container varchar(16) NOT NULL DEFAULT 'page'; + -- For 8.0 From 5e468133237e2148550c3b205c0a4d09829a9ebc Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Fri, 9 Mar 2018 23:45:28 +0100 Subject: [PATCH 77/91] Add phone research --- htdocs/societe/list.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 9861f4b8d66..d046c325eca 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -9,6 +9,7 @@ * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2017 Rui Strecht * Copyright (C) 2017 Juanjo Menent + * Copyright (C) 2018 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -137,6 +138,7 @@ $fieldstosearchall = array( 's.siren'=>"ProfId1", 's.siret'=>"ProfId2", 's.ape'=>"ProfId3", + 's.phone'=>"Phone", ); if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4']='ProfId4'; if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5']='ProfId5'; From 5d1e54c6fd2d90f95e66cd271853cc0ac7bdd8ae Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Fri, 9 Mar 2018 23:48:50 +0100 Subject: [PATCH 78/91] Add phone search --- htdocs/contact/list.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 6e62cef1eb0..e2ad6031937 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -7,6 +7,7 @@ * Copyright (C) 2013 Cédric Salvador * Copyright (C) 2013 Alexandre Spangaro * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -133,6 +134,7 @@ $fieldstosearchall = array( 'p.firstname'=>'Firstname', 'p.email'=>'EMail', 's.nom'=>"ThirdParty", + 'p.phone'=>"Phone", ); // Definition of fields for list From aaf68b904e3261bceaa4b6c8f0250b82c881139d Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Sat, 10 Mar 2018 00:00:23 +0100 Subject: [PATCH 79/91] Add mass action proposal closed --- htdocs/core/actions_massactions.inc.php | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 5a713168c48..9a9298528eb 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -1,5 +1,6 @@ + * Copyright (C) 2018 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -973,7 +974,41 @@ if (! $error && $massaction == 'validate' && $permtocreate) //var_dump($listofobjectthirdparties);exit; } } +// Closed records +if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permtoclose) { + $db->begin(); + $objecttmp = new $objectclass($db); + $nbok = 0; + foreach ($toselect as $toselectid) { + $result = $objecttmp->fetch($toselectid); + if ($result > 0) { + $result = $objecttmp->cloture($user, 3); + if ($result <= 0) { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } else + $nbok++; + } + else { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (!$error) { + if ($nbok > 1) + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + else + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + $db->commit(); + } + else { + $db->rollback(); + } +} // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete) { From 9075ed4107c12a3aa59aac9cc70fe3c239fe5408 Mon Sep 17 00:00:00 2001 From: Inovea Conseil Date: Sat, 10 Mar 2018 00:04:58 +0100 Subject: [PATCH 80/91] Add mass action proposal closed --- htdocs/comm/propal/list.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index cdcd5bf014b..de7715bdcf4 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -12,6 +12,7 @@ * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2017 Charlene Benke + * Copyright (C) 2018 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -214,6 +215,7 @@ if (empty($reshook)) $objectlabel='Proposals'; $permtoread = $user->rights->propal->lire; $permtodelete = $user->rights->propal->supprimer; + $permtoclose = $user->rights->propal->cloturer; $uploaddir = $conf->propal->multidir_output[$conf->entity]; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -389,7 +391,8 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->propal->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + if ($user->rights->propal->cloturer) $arrayofmassactions['closed']=$langs->trans("Closed"); + if (in_array($massaction, array('presend','predelete','closed'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); // Lignes des champs de filtre From 8e84b733dc4a489901379410ad505efe63b68526 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 00:13:41 +0100 Subject: [PATCH 81/91] fix scrutinizer --- htdocs/adherents/class/adherent.class.php | 5 +++-- htdocs/compta/bank/class/account.class.php | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index c55e1bb3fc1..3247fdf31e4 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1602,8 +1602,9 @@ class Adherent extends CommonObject // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; + $lang_id=GETPOST('lang_id'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($lang_id)) + $newlang = $lang_id; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $customer->default_lang; if (! empty($newlang)) { diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 719a48c3e3c..b019dd7068c 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -509,6 +509,8 @@ class Account extends CommonObject { global $langs,$conf, $hookmanager; + $error=0; + // Clean parameters if (! $this->min_allowed) $this->min_allowed=0; if (! $this->min_desired) $this->min_desired=0; @@ -668,7 +670,7 @@ class Account extends CommonObject * @param int $notrigger 1=Disable triggers * @return int <0 if KO, >0 if OK */ - function update(User $user = null, $notrigger = 0) + function update(User $user, $notrigger = 0) { global $langs,$conf, $hookmanager; @@ -1135,6 +1137,8 @@ class Account extends CommonObject */ function solde($option=0) { + $solde=0; + $sql = "SELECT sum(amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."bank"; $sql.= " WHERE fk_account = ".$this->id; @@ -1149,8 +1153,13 @@ class Account extends CommonObject $solde = $obj->amount; } $this->db->free($resql); - return $solde; + } else { + $this->errors[]=$this->db->lasterror; + return -1; } + + return $solde; + } /** @@ -1593,7 +1602,7 @@ class Account extends CommonObject $this->code_banque = '123'; $this->code_guichet = '456'; $this->number = 'ABC12345'; - $this->cle_rib = 50; + $this->cle_rib = '50'; $this->bic = 'AA12'; $this->iban = 'FR999999999'; $this->domiciliation = 'My bank address'; @@ -1904,7 +1913,7 @@ class AccountLine extends CommonObject */ function update_conciliation(User $user, $cat) { - global $conf; + global $conf,$langs; $this->db->begin(); @@ -2132,9 +2141,10 @@ class AccountLine extends CommonObject * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param int $maxlen Longueur max libelle * @param string $option Option ('showall') + * @param int $notooltip 1=Disable tooltip * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlen=0,$option='') + function getNomUrl($withpicto=0,$maxlen=0,$option='',$notooltip=0) { global $langs; From 63fb53159c06c057ffb6d35930bc4e5614c07fa2 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 01:12:47 +0100 Subject: [PATCH 82/91] fix scrunitizer --- htdocs/compta/facture/class/facture.class.php | 53 ++++++++----------- htdocs/core/class/commoninvoice.class.php | 2 +- 2 files changed, 22 insertions(+), 33 deletions(-) diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index e4438d4771a..382002fddc7 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -86,11 +86,11 @@ class Facture extends CommonInvoice //var $amount; public $remise_absolue; public $remise_percent; - public $total_ht=0; - public $total_tva=0; - public $total_localtax1=0; - public $total_localtax2=0; - public $total_ttc=0; + public $total_ht=0.0; + public $total_tva=0.0; + public $total_localtax1=0.0; + public $total_localtax2=0.0; + public $total_ttc=0.0; public $revenuestamp; //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon @@ -140,7 +140,7 @@ class Facture extends CommonInvoice public $situation_counter; /** - * @var bool Final situation flag + * @var int Final situation flag */ public $situation_final; @@ -303,13 +303,13 @@ class Facture extends CommonInvoice $this->entity = $_facrec->entity; // Invoice created in same entity than template // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI - $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project; + $this->fk_project = (int)GETPOST('projectid','int') > 0 ? (int)GETPOST('projectid','int') : $_facrec->fk_project; $this->note_public = GETPOST('note_public','none') ? GETPOST('note_public','none') : $_facrec->note_public; $this->note_private = GETPOST('note_private','none') ? GETPOST('note_private','none') : $_facrec->note_private; $this->modelpdf = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf; - $this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id; - $this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id; - $this->fk_account = GETPOST('fk_account') > 0 ? GETPOST('fk_account') : $_facrec->fk_account; + $this->cond_reglement_id = (int)GETPOST('cond_reglement_id') > 0 ? (int)GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id; + $this->mode_reglement_id = (int)GETPOST('mode_reglement_id') > 0 ? (int)GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id; + $this->fk_account = (int)GETPOST('fk_account') > 0 ? (int)GETPOST('fk_account') : $_facrec->fk_account; // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result $this->total_ht = $_facrec->total_ht; @@ -860,7 +860,7 @@ class Facture extends CommonInvoice } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) { - $this->fetchObjectLinked('', '', $object->id, 'facture'); + $this->fetchObjectLinked('', '', $facture->id, 'facture'); foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) { @@ -1519,7 +1519,7 @@ class Facture extends CommonInvoice * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=null, $notrigger=0) + function update(User $user, $notrigger=0) { $error=0; @@ -1535,17 +1535,6 @@ class Facture extends CommonInvoice if (isset($this->note_public)) $this->note_public=trim($this->note_public); if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf); if (isset($this->import_key)) $this->import_key=trim($this->import_key); - if (empty($this->situation_cycle_ref)) { - $this->situation_cycle_ref = 'null'; - } - - if (empty($this->situation_counter)) { - $this->situation_counter = 'null'; - } - - if (empty($this->situation_final)) { - $this->situation_final = '0'; - } // Check parameters // Put here code to add control on parameters values @@ -1585,9 +1574,9 @@ class Facture extends CommonInvoice $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").","; $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ", situation_cycle_ref=".$this->situation_cycle_ref; - $sql.= ", situation_counter=".$this->situation_counter; - $sql.= ", situation_final=".$this->situation_final; + $sql.= ", situation_cycle_ref=".(empty($this->situation_cycle_ref)?"null":$this->situation_cycle_ref); + $sql.= ", situation_counter=".(empty($this->situation_counter)?"null":$this->situation_counter); + $sql.= ", situation_final=".(empty($this->situation_counter)?"0":$this->situation_counter); $sql.= " WHERE rowid=".$this->id; @@ -1810,9 +1799,9 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG); // Test to avoid invoice deletion (allowed if draft) - $test = $this->is_erasable(); + $result = $this->is_erasable(); - if ($test <= 0) return 0; + if ($result <= 0) return 0; $error=0; @@ -2556,7 +2545,7 @@ class Facture extends CommonInvoice * @param double $pu_ht_devise Unit price in currency * @return int <0 if KO, Id of line if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null, $pu_ht_devise = 0) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id=0, $fk_unit = null, $pu_ht_devise = 0) { // Deprecation warning if ($label) { @@ -3061,7 +3050,7 @@ class Facture extends CommonInvoice // For triggers $result = $line->fetch($rowid); - if (! ($result > 0)) dol_print_error($db, $line->error, $line->errors); + if (! ($result > 0)) dol_print_error($this->db, $line->error, $line->errors); if ($line->delete($user) > 0) { @@ -4379,7 +4368,7 @@ class FactureLigne extends CommonInvoiceLine if (empty($this->subprice)) $this->subprice=0; if (empty($this->special_code)) $this->special_code=0; if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null'; + if (empty($this->fk_prev_id)) $this->fk_prev_id = 0; if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; if (empty($this->pa_ht)) $this->pa_ht=0; @@ -4462,7 +4451,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= " ".price2num($this->total_localtax1).","; $sql.= " ".price2num($this->total_localtax2); $sql.= ", " . $this->situation_percent; - $sql.= ", " . $this->fk_prev_id; + $sql.= ", " . (!empty($this->fk_prev_id)?$this->fk_prev_id:"null"); $sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); $sql.= ", ".$user->id; $sql.= ", ".$user->id; diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 7d1f8feda8d..9ce569edb35 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -676,7 +676,7 @@ abstract class CommonInvoiceLine extends CommonObjectLine { /** * Quantity - * @var int + * @var double */ public $qty; From 40fb803ffd3c43c4971a63f0252454f1e362ea88 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 09:34:33 +0100 Subject: [PATCH 83/91] scrunitizer --- htdocs/compta/facture/class/paymentterm.class.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index 9c1f0020d36..3697a61672b 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -57,7 +57,6 @@ class PaymentTerm // extends CommonObject function __construct($db) { $this->db = $db; - return 1; } @@ -332,11 +331,11 @@ class PaymentTerm // extends CommonObject } - /** + /** * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ function delete($user, $notrigger=0) From 594497d085f51adf0963d05faec3c1f5aad7a906 Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 10:34:11 +0100 Subject: [PATCH 84/91] fix scrunitizer --- htdocs/contrat/class/contrat.class.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index f1b0c5cdfb9..a9dec780ba8 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -899,17 +899,20 @@ class Contrat extends CommonObject if ($result > 0) { $modCodeContract = new $module(); - } - if (!empty($modCodeContract->code_auto)) { - // Mise a jour ref - $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { - if ($this->id) + if (!empty($modCodeContract->code_auto)) { + // Mise a jour ref + $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; + if ($this->db->query($sql)) { - $this->ref="(PROV".$this->id.")"; + if ($this->id) + { + $this->ref="(PROV".$this->id.")"; + } } + } else { + $error++; + $this->error='Failed to get PROV number'; } } @@ -1336,6 +1339,7 @@ class Contrat extends CommonObject function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0) { global $user, $langs, $conf, $mysoc; + $error=0; dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); @@ -1544,6 +1548,8 @@ class Contrat extends CommonObject { global $user, $conf, $langs, $mysoc; + $error=0; + // Clean parameters $qty=trim($qty); $desc=trim($desc); From 26686a05c29d1b3d3a3876bded3d014abbe4cbeb Mon Sep 17 00:00:00 2001 From: florian HENRY Date: Sat, 10 Mar 2018 10:38:56 +0100 Subject: [PATCH 85/91] fix scrunituzer --- htdocs/core/class/commondocgenerator.class.php | 1 - 1 file changed, 1 deletion(-) diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index a4ea3a70447..4d45f5aabbb 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -44,7 +44,6 @@ abstract class CommonDocGenerator */ public function __construct($db) { $this->db = $db; - return 1; } From 5d692482a3ea7dd2638453b8ea771e9063afe717 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Sat, 10 Mar 2018 11:18:05 +0100 Subject: [PATCH 86/91] fix good write to add --- htdocs/modulebuilder/template/myobject_card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/modulebuilder/template/myobject_card.php b/htdocs/modulebuilder/template/myobject_card.php index a82ec237006..4e43063cc94 100644 --- a/htdocs/modulebuilder/template/myobject_card.php +++ b/htdocs/modulebuilder/template/myobject_card.php @@ -113,7 +113,7 @@ if (empty($reshook)) { $error=0; - $permissiontoadd = $user->rights->mymodule->create; + $permissiontoadd = $user->rights->mymodule->write; $permissiontodelete = $user->rights->mymodule->delete; $backurlforlist = dol_buildpath('/mymodule/myobject_list.php',1); From a833c271e11cfdee5d122e556380eef37ed17eb0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:37:44 +0100 Subject: [PATCH 87/91] Missing user --- htdocs/variants/class/ProductAttributeValue.class.php | 7 ++++--- htdocs/variants/create_val.php | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/htdocs/variants/class/ProductAttributeValue.class.php b/htdocs/variants/class/ProductAttributeValue.class.php index 9c9d9929f46..9b455851507 100644 --- a/htdocs/variants/class/ProductAttributeValue.class.php +++ b/htdocs/variants/class/ProductAttributeValue.class.php @@ -140,15 +140,16 @@ class ProductAttributeValue /** * Creates a value for a product attribute * - * @return int <0 KO >0 OK + * @param User $user Object user + * @return int <0 KO >0 OK */ - public function create() + public function create(User $user) { if (!$this->fk_product_attribute) { return -1; } - //Ref must be uppercase + // Ref must be uppercase $this->ref = strtoupper($this->ref); $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_value (fk_product_attribute, ref, value, entity) diff --git a/htdocs/variants/create_val.php b/htdocs/variants/create_val.php index 7c624765e32..b290182a042 100644 --- a/htdocs/variants/create_val.php +++ b/htdocs/variants/create_val.php @@ -65,7 +65,7 @@ if ($action == 'add') $objectval->ref = $ref; $objectval->value = $value; - if ($objectval->create() > 0) { + if ($objectval->create($user) > 0) { setEventMessage($langs->trans('RecordSaved')); header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id); exit(); From d00b549f91dc9f00b8e39e5761e00c5a3c630fcd Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:46:45 +0100 Subject: [PATCH 88/91] Remove duplicate perm --- htdocs/core/modules/modStock.class.php | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/htdocs/core/modules/modStock.class.php b/htdocs/core/modules/modStock.class.php index ccbf6f83f57..ca518ed8851 100644 --- a/htdocs/core/modules/modStock.class.php +++ b/htdocs/core/modules/modStock.class.php @@ -128,13 +128,7 @@ class modStock extends DolibarrModules $this->rights[6][1] = 'inventoryCreatePermission'; // Permission label $this->rights[6][3] = 0; // Permission by default for new user (0/1) $this->rights[6][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - $this->rights[6][5] = 'create'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - - $this->rights[7][0] = 1013; - $this->rights[7][1] = 'inventoryWritePermission'; // Permission label - $this->rights[7][3] = 0; // Permission by default for new user (0/1) - $this->rights[7][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - $this->rights[7][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) + $this->rights[6][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[8][0] = 1014; $this->rights[8][1] = 'inventoryValidatePermission'; // Permission label From b0bd8cf9105a6fc17af2624c910600203773f652 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Sat, 10 Mar 2018 12:56:19 +0100 Subject: [PATCH 89/91] Update facture.class.php --- htdocs/compta/facture/class/facture.class.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 382002fddc7..349be5ed9cd 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -86,11 +86,11 @@ class Facture extends CommonInvoice //var $amount; public $remise_absolue; public $remise_percent; - public $total_ht=0.0; - public $total_tva=0.0; - public $total_localtax1=0.0; - public $total_localtax2=0.0; - public $total_ttc=0.0; + public $total_ht=0; + public $total_tva=0; + public $total_localtax1=0; + public $total_localtax2=0; + public $total_ttc=0; public $revenuestamp; //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon From b370a3096c10a89de2a94e8323e0a025ac74d5c9 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Sat, 10 Mar 2018 14:14:31 +0100 Subject: [PATCH 90/91] fix commonobject isInt for module builder capabilities --- htdocs/core/class/commonobject.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index f4a60385a37..6616745888b 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5527,7 +5527,7 @@ abstract class CommonObject $label = $val['label']; $type = $val['type']; $size = $val['css']; - + // Convert var to be able to share same code than showOutputField of extrafields if (preg_match('/varchar\((\d+)\)/', $type, $reg)) { @@ -6203,7 +6203,7 @@ abstract class CommonObject { if(is_array($info)) { - if(isset($info['type']) && ($info['type']=='int' || $info['type']=='integer' )) return true; + if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true; else return false; } else return false; From 129c032118e6ba1fe251051e05d87a69dbdb6635 Mon Sep 17 00:00:00 2001 From: Alexis Algoud Date: Sat, 10 Mar 2018 16:46:57 +0100 Subject: [PATCH 91/91] NEW hidden conf to set nb weeks to show into user view --- htdocs/comm/action/peruser.php | 346 +++++++++++++++++---------------- 1 file changed, 179 insertions(+), 167 deletions(-) diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php index a4154f5a9e4..a4acd64f83c 100644 --- a/htdocs/comm/action/peruser.php +++ b/htdocs/comm/action/peruser.php @@ -245,7 +245,9 @@ $next_day = $next['day']; // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) $firstdaytoshow=dol_mktime(0,0,0,$first_month,$first_day,$first_year); -$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); + +$nb_weeks_to_show = !empty($conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER) ? (int)$conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER * 7 : 7; +$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, $nb_weeks_to_show, 'd'); //print $firstday.'-'.$first_month.'-'.$first_year; //print dol_print_date($firstdaytoshow,'dayhour'); //print dol_print_date($lastdaytoshow,'dayhour'); @@ -465,7 +467,7 @@ if ($filtert > 0 || $usergroup > 0) } // Sort on date $sql.= ' ORDER BY fk_user_action, datep'; //fk_user_action -//print $sql;exit; + dol_syslog("comm/action/peruser.php", LOG_DEBUG); $resql=$db->query($sql); @@ -619,183 +621,193 @@ echo '' ; //print "begin_d=".$begin_d." end_d=".$end_d; - +$currentdaytoshow = $firstdaytoshow; echo '
'; -echo ''; -echo ''; -echo ''; -$i=0; // 0 = sunday, -while ($i < 7) -{ - if (($i + 1) < $begin_d || ($i + 1) > $end_d) - { - $i++; - continue; - } - echo '\n"; - $i++; -} -echo "\n"; - -echo ''; -echo ''; -$i=0; -while ($i < 7) -{ - if (($i + 1) < $begin_d || ($i + 1) > $end_d) - { - $i++; - continue; - } - for ($h = $begin_h; $h < $end_h; $h++) - { - echo '"; - } - echo "\n"; - $i++; -} -echo "\n"; - - -// Define $usernames -$usernames = array(); //init -$usernamesid = array(); -/* Use this to have list of users only if users have events */ -if (! empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) -{ - foreach ($eventarray as $daykey => $notused) - { - // Get all assigned users for each event - foreach ($eventarray[$daykey] as $index => $event) - { - $event->fetch_userassigned(); - $listofuserid=$event->userassigned; - foreach($listofuserid as $userid => $tmp) - { - if (! in_array($userid, $usernamesid)) $usernamesid[$userid] = $userid; - } - } - } -} -/* Use this list to have for all users */ -else -{ - $sql = "SELECT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - if ($usergroup > 0) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; - $sql.= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user').")"; - if ($usergroup > 0) $sql.= " AND ug.fk_usergroup = ".$usergroup; - //print $sql; - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $usernamesid[$obj->rowid]=$obj->rowid; - $i++; - } - } - } - else dol_print_error($db); -} -//var_dump($usernamesid); -foreach($usernamesid as $id) -{ - $tmpuser=new User($db); - $result=$tmpuser->fetch($id); - $usernames[]=$tmpuser; -} - -/* -if ($filtert > 0) -{ - $tmpuser = new User($db); - $tmpuser->fetch($filtert); - $usernames[] = $tmpuser; -} -else if ($usergroup) -{ - $tmpgroup = new UserGroup($db); - $tmpgroup->fetch($usergroup); - $usernames = $tmpgroup->listUsersForGroup(); -} -else -{ - $tmpgroup = new UserGroup($db); - //$tmpgroup->fetch($usergroup); No fetch, we want all users for all groups - $usernames = $tmpgroup->listUsersForGroup(); -}*/ - -// Load array of colors by type -$colorsbytype=array(); -$labelbytype=array(); -$sql="SELECT code, color, libelle FROM ".MAIN_DB_PREFIX."c_actioncomm ORDER BY position"; -$resql=$db->query($sql); -while ($obj = $db->fetch_object($resql)) -{ - $colorsbytype[$obj->code]=$obj->color; - $labelbytype[$obj->code]=$obj->libelle; -} - -// Loop on each user to show calendar -$todayarray=dol_getdate($now,'fast'); -$sav = $tmpday; -$showheader = true; -$var = false; -foreach ($usernames as $username) -{ - $var = ! $var; - echo ""; - echo ''; - $tmpday = $sav; - - // Lopp on each day of week - $i = 0; - for ($iter_day = 0; $iter_day < 8; $iter_day++) +while($currentdaytoshow<$lastdaytoshow) { + + echo '
'; - echo $langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7)); - print "
"; - if ($i) print dol_print_date(dol_time_plus_duree($firstdaytoshow, $i, 'd'),'day'); - else print dol_print_date($firstdaytoshow,'day'); - echo "
'; - print ''.sprintf("%02d",$h).''; - print "
'; - print $username->getNomUrl(-1,'',0,0,20,1,''); - print '
'; + + echo ''; + echo ''; + $i=0; // 0 = sunday, + while ($i < 7) { if (($i + 1) < $begin_d || ($i + 1) > $end_d) { $i++; continue; } - - // Show days of the current week - $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); - $tmparray = dol_getdate($curtime,'fast'); - $tmpday = $tmparray['mday']; - $tmpmonth = $tmparray['mon']; - $tmpyear = $tmparray['year']; - - $style='cal_current_month'; - if ($iter_day == 6) $style.=' cal_other_month'; - $today=0; - if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; - if ($today) $style='cal_today_peruser'; - - show_day_events2($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); - + echo '\n"; $i++; } echo "\n"; - $showheader = false; + + echo ''; + echo ''; + $i=0; + while ($i < 7) + { + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + for ($h = $begin_h; $h < $end_h; $h++) + { + echo '"; + } + echo "\n"; + $i++; + } + echo "\n"; + + + // Define $usernames + $usernames = array(); //init + $usernamesid = array(); + /* Use this to have list of users only if users have events */ + if (! empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) + { + foreach ($eventarray as $daykey => $notused) + { + // Get all assigned users for each event + foreach ($eventarray[$daykey] as $index => $event) + { + $event->fetch_userassigned(); + $listofuserid=$event->userassigned; + foreach($listofuserid as $userid => $tmp) + { + if (! in_array($userid, $usernamesid)) $usernamesid[$userid] = $userid; + } + } + } + } + /* Use this list to have for all users */ + else + { + $sql = "SELECT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + if ($usergroup > 0) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; + $sql.= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user').")"; + if ($usergroup > 0) $sql.= " AND ug.fk_usergroup = ".$usergroup; + //print $sql; + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $usernamesid[$obj->rowid]=$obj->rowid; + $i++; + } + } + } + else dol_print_error($db); + } + //var_dump($usernamesid); + foreach($usernamesid as $id) + { + $tmpuser=new User($db); + $result=$tmpuser->fetch($id); + $usernames[]=$tmpuser; + } + + /* + if ($filtert > 0) + { + $tmpuser = new User($db); + $tmpuser->fetch($filtert); + $usernames[] = $tmpuser; + } + else if ($usergroup) + { + $tmpgroup = new UserGroup($db); + $tmpgroup->fetch($usergroup); + $usernames = $tmpgroup->listUsersForGroup(); + } + else + { + $tmpgroup = new UserGroup($db); + //$tmpgroup->fetch($usergroup); No fetch, we want all users for all groups + $usernames = $tmpgroup->listUsersForGroup(); + }*/ + + // Load array of colors by type + $colorsbytype=array(); + $labelbytype=array(); + $sql="SELECT code, color, libelle FROM ".MAIN_DB_PREFIX."c_actioncomm ORDER BY position"; + $resql=$db->query($sql); + while ($obj = $db->fetch_object($resql)) + { + $colorsbytype[$obj->code]=$obj->color; + $labelbytype[$obj->code]=$obj->libelle; + } + + // Loop on each user to show calendar + $todayarray=dol_getdate($now,'fast'); + $sav = $tmpday; + $showheader = true; + $var = false; + foreach ($usernames as $username) + { + $var = ! $var; + echo ""; + echo ''; + $tmpday = $sav; + + // Lopp on each day of week + $i = 0; + for ($iter_day = 0; $iter_day < 8; $iter_day++) + { + + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + + // Show days of the current week + $curtime = dol_time_plus_duree($currentdaytoshow, $iter_day, 'd'); + $tmparray = dol_getdate($curtime,'fast'); + $tmpday = $tmparray['mday']; + $tmpmonth = $tmparray['mon']; + $tmpyear = $tmparray['year']; + + $style='cal_current_month'; + if ($iter_day == 6) $style.=' cal_other_month'; + $today=0; + if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; + if ($today) $style='cal_today_peruser'; + + show_day_events2($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); + + $i++; + } + echo "\n"; + $showheader = false; + } + + echo "
'; + echo $langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7)); + print "
"; + if ($i) print dol_print_date(dol_time_plus_duree($currentdaytoshow, $i, 'd'),'day'); + else print dol_print_date($currentdaytoshow,'day'); + echo "
'; + print ''.sprintf("%02d",$h).''; + print "
'; + print $username->getNomUrl(-1,'',0,0,20,1,''); + print '
\n"; + echo "
"; + + $currentdaytoshow = dol_time_plus_duree($currentdaytoshow, 7, 'd'); + } -echo "\n"; echo '
'; if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && ! empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) @@ -910,7 +922,7 @@ function show_day_events2($username, $day, $month, $year, $monthshown, $style, & $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 $nextindextouse=count($colorindexused); // At first run this is 0, so first user has 0, next 1, ... //if ($username->id && $day==1) var_dump($eventarray); - + // We are in a particular day for $username, now we scan all events foreach ($eventarray as $daykey => $notused) {